diff --git a/.gitignore b/.gitignore index 4fc816a..20f3419 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ target private.key config.json messages +users.db diff --git a/src/data/mod.rs b/src/data/mod.rs index ca69f9c..994db7e 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -1,2 +1,3 @@ pub mod config; pub mod messages; +pub mod users; diff --git a/src/data/users.rs b/src/data/users.rs new file mode 100644 index 0000000..f9bc526 --- /dev/null +++ b/src/data/users.rs @@ -0,0 +1,62 @@ +use std::{collections::HashMap, path::PathBuf}; + +use rusqlite::{Connection, params}; +use tokio::sync::Mutex; + +use crate::types::ClientMeta; + +pub struct UserMetaStore { + conn: Mutex, +} + +impl UserMetaStore { + pub fn new(path: PathBuf) -> anyhow::Result { + let conn = Connection::open(&path)?; + conn.execute( + "CREATE TABLE IF NOT EXISTS users ( + pubkey TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + avatar TEXT + )", + [], + )?; + Ok(Self { + conn: Mutex::new(conn), + }) + } + + pub async fn get_users( + &self, + pubkeys: &[String], + ) -> anyhow::Result> { + let conn = self.conn.lock().await; + let placeholders = pubkeys.iter().map(|_| "?").collect::>().join(","); + let query = format!( + "SELECT pubkey, display_name, avatar FROM users WHERE pubkey IN ({placeholders})" + ); + + let mut stmt = conn.prepare(&query)?; + let rows = stmt.query_map(rusqlite::params_from_iter(pubkeys), |row| { + Ok(( + row.get::<_, String>(0)?, + ClientMeta { + display_name: row.get(1)?, + avatar: row.get(2)?, + }, + )) + })?; + + rows.collect::, _>>() + .map_err(Into::into) + } + + pub async fn upsert_user(&self, pubkey: &str, meta: &ClientMeta) -> anyhow::Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO users (pubkey, display_name, avatar) VALUES (?1, ?2, ?3) + ON CONFLICT(pubkey) DO UPDATE SET display_name = ?2, avatar = ?3", + params![pubkey, meta.display_name, meta.avatar], + )?; + Ok(()) + } +} diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs index d15c575..53143f7 100644 --- a/src/protocol/mod.rs +++ b/src/protocol/mod.rs @@ -9,6 +9,7 @@ use crate::{data::messages::StoredMessage, server::Server, types::ClientMeta}; pub mod initialize; pub mod message; +pub mod user; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "method")] @@ -25,6 +26,10 @@ pub enum ClientMethod { messages: HashMap>, }, + Users { + users: HashMap, + }, + Error { error: Cow<'static, str>, }, @@ -53,6 +58,10 @@ pub enum ServerMethod { Meta(ClientMeta), + GetUsers { + pubkeys: Vec, + }, + Error { error: String, }, @@ -93,6 +102,10 @@ pub async fn read_loop( ServerMethod::GetMessages { channel_id, chunk } => { message::get_messages(server, verifying_key, socket, channel_id, chunk).await?; } + + ServerMethod::GetUsers { pubkeys } => { + user::get_users(server, verifying_key, socket, pubkeys).await?; + } } socket_lock = socket.lock().await; diff --git a/src/protocol/user.rs b/src/protocol/user.rs new file mode 100644 index 0000000..8bc0ac1 --- /dev/null +++ b/src/protocol/user.rs @@ -0,0 +1,23 @@ +use std::sync::Arc; + +use axum::extract::ws::WebSocket; +use ed25519_dalek::VerifyingKey; +use tokio::sync::Mutex; + +use crate::{ + protocol::{ClientMethod, send_socket}, + server::Server, +}; + +pub async fn get_users( + server: &Arc, + _verifying_key: VerifyingKey, + socket: &Arc>, + pubkeys: Vec, +) -> anyhow::Result<()> { + let users = server.user_store.get_users(&pubkeys).await?; + + send_socket(&mut *socket.lock().await, &ClientMethod::Users { users }).await?; + + Ok(()) +} diff --git a/src/server.rs b/src/server.rs index 9440f7e..c6ca1f3 100644 --- a/src/server.rs +++ b/src/server.rs @@ -12,7 +12,7 @@ use ed25519_dalek::{SigningKey, VerifyingKey}; use tokio::{sync::Mutex, task::JoinSet}; use crate::{ - data::{config::Config, messages::MessageStore}, + data::{config::Config, messages::MessageStore, users::UserMetaStore}, protocol::{ClientMethod, read_loop, send_socket}, types::ClientMeta, }; @@ -29,6 +29,7 @@ pub struct Server { pub config: Config, pub clients: Mutex>>, pub message_store: MessageStore, + pub user_store: UserMetaStore, } impl Server { @@ -38,6 +39,7 @@ impl Server { config: Config::get().await?, clients: Mutex::new(HashMap::new()), message_store: MessageStore::new(PathBuf::from("messages"))?, + user_store: UserMetaStore::new(PathBuf::from("users.db"))?, })) } } @@ -49,6 +51,14 @@ impl Server { ws.on_upgrade(move |socket: WebSocket| async move { match UserConnections::initialize(&s, socket).await { Ok((client, public_key, meta)) => { + if let Err(e) = s + .user_store + .upsert_user(&crate::signature::to_string(&public_key), &meta) + .await + { + eprintln!("Failed to upsert client: {e}"); + } + let client = Arc::new(Mutex::new(client)); let mut clients_meta = s.clients.lock().await;