Send message
This commit is contained in:
+25
-20
@@ -1,5 +1,6 @@
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, Connection};
|
||||
use rusqlite::{Connection, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
@@ -9,14 +10,19 @@ pub struct MessageStore {
|
||||
connections: Mutex<HashMap<String, Connection>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MessageData {
|
||||
pub content: String,
|
||||
pub timestamp: u64,
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StoredMessage {
|
||||
pub id: String,
|
||||
pub author_pubkey: String,
|
||||
pub content: String,
|
||||
pub timestamp: i64,
|
||||
pub signature: String,
|
||||
pub channel_id: String,
|
||||
pub author: String,
|
||||
#[serde(flatten)]
|
||||
pub data: MessageData,
|
||||
}
|
||||
|
||||
impl MessageStore {
|
||||
@@ -48,7 +54,6 @@ impl MessageStore {
|
||||
content TEXT NOT NULL,
|
||||
timestamp INTEGER NOT NULL,
|
||||
signature TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)?;
|
||||
@@ -68,15 +73,14 @@ impl MessageStore {
|
||||
pub fn insert_message(&self, channel_id: &str, msg: &StoredMessage) -> Result<()> {
|
||||
self.with_channel(channel_id, |conn| {
|
||||
conn.execute(
|
||||
"INSERT INTO messages (id, author_pubkey, content, timestamp, signature, channel_id)
|
||||
"INSERT INTO messages (id, author_pubkey, content, timestamp, signature)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
params![
|
||||
msg.id,
|
||||
msg.author_pubkey,
|
||||
msg.content,
|
||||
msg.timestamp,
|
||||
msg.signature,
|
||||
msg.channel_id,
|
||||
msg.author,
|
||||
msg.data.content,
|
||||
msg.data.timestamp,
|
||||
msg.data.signature,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
@@ -87,7 +91,7 @@ impl MessageStore {
|
||||
pub fn get_recent_messages(&self, channel_id: &str, limit: u32) -> Result<Vec<StoredMessage>> {
|
||||
self.with_channel(channel_id, |conn| {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, author_pubkey, content, timestamp, signature, channel_id
|
||||
"SELECT id, author_pubkey, content, timestamp, signature
|
||||
FROM messages
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT ?1",
|
||||
@@ -96,11 +100,12 @@ impl MessageStore {
|
||||
let rows = stmt.query_map(params![limit], |row| {
|
||||
Ok(StoredMessage {
|
||||
id: row.get(0)?,
|
||||
author_pubkey: row.get(1)?,
|
||||
content: row.get(2)?,
|
||||
timestamp: row.get(3)?,
|
||||
signature: row.get(4)?,
|
||||
channel_id: row.get(5)?,
|
||||
author: row.get(1)?,
|
||||
data: MessageData {
|
||||
content: row.get(2)?,
|
||||
timestamp: row.get(3)?,
|
||||
signature: row.get(4)?,
|
||||
},
|
||||
})
|
||||
})?;
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
use crate::data::messages::{MessageData, StoredMessage};
|
||||
use crate::server::Server;
|
||||
use axum::extract::ws::WebSocket;
|
||||
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub async fn send_message(
|
||||
server: &Arc<Server>,
|
||||
verifying_key: VerifyingKey,
|
||||
socket: &Arc<Mutex<WebSocket>>,
|
||||
message: MessageData,
|
||||
channel_id: String,
|
||||
) -> anyhow::Result<()> {
|
||||
let server_timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64;
|
||||
|
||||
if server_timestamp.saturating_sub(message.timestamp) > 2000 {
|
||||
anyhow::bail!(
|
||||
"Message timestamp out of range ({server_timestamp} - {}) < 2000",
|
||||
message.timestamp
|
||||
);
|
||||
}
|
||||
|
||||
let server_pubkey_string = crate::signature::to_string(&server.key.verifying_key());
|
||||
let signed_string = format!(
|
||||
"{}@{}@{}",
|
||||
message.timestamp, server_pubkey_string, message.content
|
||||
);
|
||||
|
||||
let signature = crate::signature::from_string_sig(&message.signature)
|
||||
.map_err(|_| anyhow::anyhow!("Invalid signature encoding"))?;
|
||||
|
||||
verifying_key
|
||||
.verify(signed_string.as_bytes(), &signature)
|
||||
.map_err(|_| anyhow::anyhow!("Signature verification failed"))?;
|
||||
|
||||
let stored = StoredMessage {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
author: crate::signature::to_string(&verifying_key),
|
||||
data: message,
|
||||
};
|
||||
|
||||
server.message_store.insert_message(&channel_id, &stored)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+17
-2
@@ -1,12 +1,14 @@
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
|
||||
use axum::extract::ws::{Message, Utf8Bytes, WebSocket};
|
||||
use ed25519_dalek::VerifyingKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::types::ClientMeta;
|
||||
use crate::{server::Server, types::ClientMeta};
|
||||
|
||||
pub mod initialize;
|
||||
pub mod message;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "method")]
|
||||
@@ -35,6 +37,11 @@ pub enum ServerMethod {
|
||||
hostname: String,
|
||||
},
|
||||
|
||||
SendMessage {
|
||||
channel_id: String,
|
||||
data: crate::data::messages::MessageData,
|
||||
},
|
||||
|
||||
Meta(ClientMeta),
|
||||
|
||||
Error {
|
||||
@@ -42,7 +49,11 @@ pub enum ServerMethod {
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn read_loop(socket: &Arc<Mutex<WebSocket>>) -> anyhow::Result<()> {
|
||||
pub async fn read_loop(
|
||||
server: &Arc<Server>,
|
||||
verifying_key: VerifyingKey,
|
||||
socket: &Arc<Mutex<WebSocket>>,
|
||||
) -> anyhow::Result<()> {
|
||||
while let Some(message) = read_socket(&mut *socket.lock().await).await? {
|
||||
match message {
|
||||
ServerMethod::Initialize { .. } => {
|
||||
@@ -61,6 +72,10 @@ pub async fn read_loop(socket: &Arc<Mutex<WebSocket>>) -> anyhow::Result<()> {
|
||||
ServerMethod::Error { error } => {
|
||||
eprintln!("Client error: {error}");
|
||||
}
|
||||
|
||||
ServerMethod::SendMessage { channel_id, data } => {
|
||||
message::send_message(server, verifying_key, socket, data, channel_id).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ impl Server {
|
||||
|
||||
clients.connections.insert(conid, client.clone());
|
||||
|
||||
if let Err(e) = read_loop(&client).await {
|
||||
if let Err(e) = read_loop(&s, public_key, &client).await {
|
||||
eprintln!("Failed to handle client: {e}");
|
||||
} else {
|
||||
println!("Client connection closed")
|
||||
|
||||
Reference in New Issue
Block a user