From 700e2a49bd41079cec24b74833faa3354b2cc327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 21:34:07 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20fixed=20auth?= =?UTF-8?q?=20per=20connection,=20one=20hub,=20one=20fan-out=20and=20one?= =?UTF-8?q?=20room=20owner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A connection now authenticates once with Hello/Welcome; login, logout and account switches reconnect instead of mutating auth mid connection. The server actor and its state copies are replaced by a Hub of clients with presence transitions and kicks, events fan out through one publish path that encodes once and never blocks, and voice plus shares live in one Rooms owner with a single leave path. Media control moves to Down::Media. --- crates/client/src/accounts.rs | 4 + crates/client/src/gui.rs | 12 +- crates/client/src/gui/chat.rs | 16 +- crates/client/src/gui/composer.rs | 7 +- crates/client/src/gui/settings_page.rs | 3 + crates/client/src/net/events.rs | 23 +- crates/client/src/net/link.rs | 94 +- crates/client/src/net/mod.rs | 41 +- crates/client/src/net/share.rs | 19 +- crates/common/src/event.rs | 48 +- crates/common/src/lib.rs | 1 + crates/common/src/request.rs | 10 +- crates/common/src/session.rs | 14 + crates/server/src/attachment.rs | 17 +- crates/server/src/authentication.rs | 45 +- crates/server/src/datagram.rs | 17 +- crates/server/src/hub.rs | 218 +++++ crates/server/src/lib.rs | 6 +- crates/server/src/network.rs | 528 ++++-------- crates/server/src/overview.rs | 12 +- crates/server/src/publish.rs | 117 +++ crates/server/src/request.rs | 1094 ++++++++++-------------- crates/server/src/retention.rs | 48 +- crates/server/src/rooms.rs | 748 ++++++++++++++++ crates/server/src/share.rs | 347 -------- crates/server/src/user_community.rs | 9 + crates/server/src/voice.rs | 323 ------- 27 files changed, 1978 insertions(+), 1843 deletions(-) create mode 100644 crates/common/src/session.rs create mode 100644 crates/server/src/hub.rs create mode 100644 crates/server/src/publish.rs create mode 100644 crates/server/src/rooms.rs delete mode 100644 crates/server/src/share.rs delete mode 100644 crates/server/src/voice.rs diff --git a/crates/client/src/accounts.rs b/crates/client/src/accounts.rs index a113fee..1a244c5 100644 --- a/crates/client/src/accounts.rs +++ b/crates/client/src/accounts.rs @@ -48,6 +48,10 @@ impl Accounts { } } + pub fn suspend(&mut self) { + self.active = None; + } + pub fn detach(&mut self) { self.active = None; save(self); diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index e1b3cb5..b18d539 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -735,6 +735,7 @@ impl Yumush { if self.user.is_some() { self.end_session(window, cx); } + self.accounts.suspend(); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { @@ -945,6 +946,7 @@ impl Yumush { Event::VoiceMuted { user_id, muted: true, + .. } if self.is_me(user_id) => self.set_muted(true, cx), Event::ShareStopped { user_id, kind, .. } if self.is_watching(user_id, *kind) => { self.close_viewer(cx) @@ -1182,7 +1184,7 @@ impl Yumush { self.apply_pushed(Event::CommunityDeleted { community_id }, cx); } Event::ReportCreated => self.report_created(window, cx), - Event::Announcement { text } => self.set_announcement(text), + Event::SettingsUpdated(settings) => self.server = Some(settings), event => { let voice = matches!( event, @@ -1231,12 +1233,6 @@ impl Yumush { } } - fn set_announcement(&mut self, text: String) { - if let Some(settings) = self.server.as_mut() { - settings.announcement = text; - } - } - fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context) { match event { NetworkEvent::Connected => { @@ -1250,7 +1246,7 @@ impl Yumush { | Event::Removed { .. } | Event::CommunityDeleted { .. } | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)), - Event::Announcement { text } => self.set_announcement(text), + Event::SettingsUpdated(settings) => self.server = Some(settings), event => self.apply_pushed(event, cx), }, } diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 7e44a05..6ebc724 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -547,9 +547,11 @@ impl Chat { } } } - Event::MessageDeleted(message) => { - if self.is_selected(&message.community_id) { - self.forget_message(&message.id); + Event::MessagesDeleted { community_id, ids } => { + if self.is_selected(&community_id) { + for id in &ids { + self.forget_message(id); + } } } Event::MemberJoined { @@ -613,7 +615,7 @@ impl Chat { } } } - Event::VoiceMuted { user_id, muted } => { + Event::VoiceMuted { user_id, muted, .. } => { if muted { self.server_muted.insert(user_id); } else { @@ -648,8 +650,7 @@ impl Chat { shares.retain(|share| share.user_id != user_id || share.kind != kind); } } - Event::ShareLayers { .. } | Event::KeyframeWanted { .. } => {} - Event::ReportCreated | Event::Announcement { .. } => {} + Event::ReportCreated | Event::SettingsUpdated(_) => {} } } @@ -1839,6 +1840,9 @@ impl Yumush { let latest = before.is_none() && window.is_window_active(); cx.spawn_in(window, async move |this, cx| { + if before.is_none() { + let _ = network.watch_community(Some(&community_id)).await; + } let Some(page) = ok_or_notify( network .read_messages(&community_id, before.as_deref()) diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index ccc721a..d87c20b 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -321,12 +321,7 @@ impl Yumush { cx.notify(); } - fn slow_down( - &mut self, - seconds: u64, - window: &mut Window, - cx: &mut Context, - ) { + fn slow_down(&mut self, seconds: u64, window: &mut Window, cx: &mut Context) { self.chat.slowed_until = Some(now_ms() + seconds * 1000); cx.spawn_in(window, async move |this, cx| { diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 5f9bbbb..2fb53f2 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -230,6 +230,9 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { yumush.end_session(window, cx); }); + if let Err(error) = network.detach().await { + notify_error(&this, cx, error); + } } Err(error) => notify_error(&this, cx, error), } diff --git a/crates/client/src/net/events.rs b/crates/client/src/net/events.rs index 0ee0875..a8cd4b6 100644 --- a/crates/client/src/net/events.rs +++ b/crates/client/src/net/events.rs @@ -1,5 +1,5 @@ use common::{ - event::Event, + event::Down, frame::{self, DOWN_MAX}, }; use tokio::sync::mpsc; @@ -15,14 +15,19 @@ pub(super) async fn event_receive_loop( return; }; - while let Ok(event) = frame::read::(&mut receive_stream, DOWN_MAX).await { - share.lock().unwrap().event(&event); - if event_sender - .send(NetworkEvent::Pushed(Box::new(event))) - .await - .is_err() - { - return; + while let Ok(down) = frame::read::(&mut receive_stream, DOWN_MAX).await { + match down { + Down::Event(event) => { + share.lock().unwrap().event(&event); + if event_sender + .send(NetworkEvent::Pushed(event)) + .await + .is_err() + { + return; + } + } + Down::Media(media) => share.lock().unwrap().media(&media), } } } diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index 3c79b78..207789e 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -4,10 +4,11 @@ use common::{ constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, error::Error, frame::{self, DOWN_MAX, Sending, UP_MAX}, - model::Attachment, + model::{Attachment, User}, open::{Blob, Open, Upload}, request::Request, response::Response, + session::{Hello, Welcome}, transport::{Close, alpn, transport}, validate::{validate_attachment_name, validate_attachment_size}, }; @@ -272,6 +273,19 @@ pub(super) async fn send( Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) } +async fn hello(connection: &quinn::Connection, token: Option) -> Result { + let (send_stream, mut receive_stream) = connection.open_bi().await?; + let mut send_stream = Sending::new(send_stream); + let hello = Hello { + token, + device: device_name(), + }; + frame::write(&mut send_stream, &hello, UP_MAX).await?; + send_stream.finish()?; + + Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) +} + pub(super) async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Fail> { match send(connection, &request).await? { Response::Done => Ok(()), @@ -410,6 +424,7 @@ async fn actor( shared: Shared, ) { let mut token: Option = None; + let mut pending: Option, Fail>>> = None; let mut endpoints = Endpoints::default(); let mut attempt = 0u32; 'session: loop { @@ -441,42 +456,52 @@ async fn actor( }; }; - if let Some(stored) = token.clone() { - let request = Request::Resume { token: stored }; - match send(&connection, &request).await { - Ok(Response::Session { token: resumed, .. }) => { - token = Some(resumed); - } - Err(error) => { - warn!("session resume failed: {error}"); - if let Some(reason) = connection.close_reason() { - let event = LinkError::from(reason); - if event == LinkError::Closed(Close::Banned) { - let _ = event_sender.send(NetworkEvent::Disconnected(event)).await; - while command_receiver.recv().await.is_some() {} + let welcome = match hello(&connection, token.clone()).await { + Ok(welcome) => welcome, + Err(Fail::Server(error)) + if token.is_some() + && (pending.is_some() + || matches!(error, Error::Unauthenticated | Error::NotFound)) => + { + warn!("session rejected: {error}"); + token = None; + connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); + match pending.take() { + Some(reply) => { + let _ = reply.send(Err(Fail::Server(error))); + } + None => { + if event_sender.send(NetworkEvent::SessionLost).await.is_err() { return; } } - tokio::time::sleep(backoff(attempt)).await; - attempt += 1; - continue 'session; } - Ok(_) => { - warn!("session resume rejected"); - token = None; - - if event_sender.send(NetworkEvent::SessionLost).await.is_err() { + continue 'session; + } + Err(error) => { + warn!("hello failed: {error}"); + if let Some(reason) = connection.close_reason() { + let event = LinkError::from(reason); + if event == LinkError::Closed(Close::Banned) { + let _ = event_sender.send(NetworkEvent::Disconnected(event)).await; + while command_receiver.recv().await.is_some() {} return; } } + tokio::time::sleep(backoff(attempt)).await; + attempt += 1; + continue 'session; } - } + }; attempt = 0; info!("connected"); if event_sender.send(NetworkEvent::Connected).await.is_err() { return; } + if let Some(reply) = pending.take() { + let _ = reply.send(Ok(welcome.user)); + } tokio::spawn(event_receive_loop( connection.clone(), @@ -490,22 +515,6 @@ async fn actor( tokio::select! { command = command_receiver.recv() => match command { Some(Command::Request { request, reply }) => match &request { - Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { - hang_up(&shared); - - let response = send(&connection, &request).await; - if let Ok(Response::Session { token: session_token, .. }) = &response { - token = Some(session_token.clone()); - } - let _ = reply.send(response); - } - Request::Logout | Request::Detach => { - token = None; - hang_up(&shared); - - let connection = connection.clone(); - answer(reply, async move { send(&connection, &request).await }); - } Request::JoinVoice { .. } => { let shared = shared.clone(); let settings = shared.voice_settings.lock().unwrap().clone(); @@ -532,6 +541,13 @@ async fn actor( answer(reply, async move { send(&connection, &request).await }); } }, + Some(Command::SignIn { token: next, reply }) => { + token = next; + pending = Some(reply); + hang_up(&shared); + connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); + break; + } Some(Command::StartShare { kind, settings, reply }) => { let connection = connection.clone(); let share = shared.share.clone(); diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index dd7d8ac..6776e5b 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -105,6 +105,10 @@ enum Command { request: Request, reply: oneshot::Sender>, }, + SignIn { + token: Option, + reply: oneshot::Sender, Fail>>, + }, Upload { community_id: String, path: PathBuf, @@ -160,18 +164,18 @@ impl NetworkHandle { self.ask(|reply| Command::Request { request, reply }).await } + async fn switch(&self, token: Option) -> Result, Fail> { + self.ask(|reply| Command::SignIn { token, reply }).await + } + async fn sign_in(&self, request: Request) -> Result<(User, String), Fail> { - let session = match self.request(request).await? { + let (user, token) = match self.request(request).await? { Response::Session { user, token } => (user, token), _ => return Err(Fail::Protocol), }; - let _ = self - .done(Request::SetDevice { - name: device_name(), - }) - .await; + self.switch(Some(token.clone())).await?; - Ok(session) + Ok((user, token)) } pub async fn sessions(&self, user_id: &str) -> Result, Fail> { @@ -206,14 +210,16 @@ impl NetworkHandle { } pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { - self.sign_in(Request::Resume { - token: token.to_string(), - }) - .await + let user = self + .switch(Some(token.to_string())) + .await? + .ok_or(Fail::Protocol)?; + + Ok((user, token.to_string())) } pub async fn detach(&self) -> Result<(), Fail> { - self.done(Request::Detach).await + self.switch(None).await.map(|_| ()) } pub async fn register( @@ -244,7 +250,9 @@ impl NetworkHandle { } pub async fn logout(&self) -> Result<(), Fail> { - self.done(Request::Logout).await + let result = self.done(Request::Logout).await; + self.detach().await?; + result } pub async fn update_user(&self, username: &str) -> Result { @@ -995,6 +1003,13 @@ impl NetworkHandle { .await } + pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> { + self.done(Request::WatchCommunity { + community_id: community_id.map(str::to_string), + }) + .await + } + pub async fn read_messages( &self, community_id: &str, diff --git a/crates/client/src/net/share.rs b/crates/client/src/net/share.rs index 8a2abcc..ef28d1b 100644 --- a/crates/client/src/net/share.rs +++ b/crates/client/src/net/share.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use common::{ - event::Event, + event::{Event, Media}, request::Request, response::Response, share::{Fps, Kind, Quality, Resolution, Source}, @@ -28,21 +28,24 @@ pub(super) struct Share { impl Share { pub(super) fn event(&mut self, event: &Event) { - match event { - Event::ShareLayers { kind, layers } => { + if let Event::ShareStopped { user_id, kind, .. } = event { + self.watching.remove(&(user_id.clone(), *kind)); + } + } + + pub(super) fn media(&mut self, media: &Media) { + match media { + Media::Layers { kind, layers } => { if let Some(sharing) = self.sharing.get_mut(kind) { sharing.set_layers(layers); } } - Event::KeyframeWanted { kind, layer } => { + Media::Keyframe { kind, layer } => { if let Some(sharing) = self.sharing.get(kind) { sharing.keyframe(*layer); } } - Event::ShareStopped { user_id, kind, .. } => { - self.watching.remove(&(user_id.clone(), *kind)); - } - _ => {} + Media::VoiceEnded => {} } } diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs index c33449c..925db71 100644 --- a/crates/common/src/event.rs +++ b/crates/common/src/event.rs @@ -1,7 +1,7 @@ use bitcode::{Decode, Encode}; use crate::model::{ - Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, User, + Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, ServerSettings, User, }; use crate::share::{Kind, Layer, Share}; @@ -9,7 +9,10 @@ use crate::share::{Kind, Layer, Share}; pub enum Event { MessageCreated(Message), MessageUpdated(Message), - MessageDeleted(Message), + MessagesDeleted { + community_id: String, + ids: Vec, + }, MemberJoined { community_id: String, member: Member, @@ -54,12 +57,11 @@ pub enum Event { }, ReportCreated, VoiceMuted { + community_id: Option, user_id: String, muted: bool, }, - Announcement { - text: String, - }, + SettingsUpdated(ServerSettings), Typing { community_id: String, user_id: String, @@ -73,31 +75,17 @@ pub enum Event { user_id: String, kind: Kind, }, - ShareLayers { - kind: Kind, - layers: Vec, - }, - KeyframeWanted { - kind: Kind, - layer: Layer, - }, } -impl Event { - pub fn community_id(&self) -> Option<&str> { - match self { - Self::MessageCreated(message) - | Self::MessageUpdated(message) - | Self::MessageDeleted(message) => Some(&message.community_id), - Self::CommunityUpdated(community) => Some(&community.id), - Self::MemberJoined { community_id, .. } - | Self::MemberLeft { community_id, .. } - | Self::RankChanged { community_id, .. } - | Self::VoiceJoined { community_id, .. } - | Self::VoiceLeft { community_id, .. } - | Self::ShareStarted { community_id, .. } - | Self::ShareStopped { community_id, .. } => Some(community_id), - _ => None, - } - } +#[derive(Debug, Clone, Encode, Decode)] +pub enum Media { + Layers { kind: Kind, layers: Vec }, + Keyframe { kind: Kind, layer: Layer }, + VoiceEnded, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub enum Down { + Event(Box), + Media(Media), } diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 5e8d5b2..075e3c0 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -9,6 +9,7 @@ pub mod open; pub mod permission; pub mod request; pub mod response; +pub mod session; pub mod share; pub mod time; pub mod transport; diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index c328ebe..0773c50 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -16,9 +16,6 @@ pub enum Request { username: String, password: String, }, - Resume { - token: String, - }, Logout, ReadUser { user_id: String, @@ -131,6 +128,9 @@ pub enum Request { Pins { community_id: String, }, + WatchCommunity { + community_id: Option, + }, ReadMessages { community_id: String, before: Option, @@ -205,7 +205,6 @@ pub enum Request { DeclineInvitation { community_id: String, }, - Detach, Logs { community_id: String, }, @@ -249,9 +248,6 @@ pub enum Request { username: String, password: String, }, - SetDevice { - name: String, - }, Sessions { user_id: String, }, diff --git a/crates/common/src/session.rs b/crates/common/src/session.rs new file mode 100644 index 0000000..427cf32 --- /dev/null +++ b/crates/common/src/session.rs @@ -0,0 +1,14 @@ +use bitcode::{Decode, Encode}; + +use crate::model::User; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Hello { + pub token: Option, + pub device: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Welcome { + pub user: Option, +} diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index 399b78f..3139428 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -668,7 +668,7 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { #[cfg(test)] mod tests { - use std::{io::Cursor, sync::Mutex}; + use std::io::Cursor; use common::{ model::{AttachmentKind, Rank}, @@ -679,8 +679,10 @@ mod tests { use crate::{ attachment::{store, thumb_path}, - community, database, message, - network::{Services, State}, + community, database, + hub::{Client, Signed}, + message, + network::Services, request::handle, test, user, user_community, }; @@ -710,10 +712,10 @@ mod tests { .await .unwrap(); - let state = Mutex::new(State::Authenticated { - user: user.clone(), + let client = Client::detached(Some(Signed { + user_id: user.id.clone(), token: "token".to_string(), - }); + })); let (reply, _) = handle( Request::CreateMessage { community_id: community.id.clone(), @@ -721,10 +723,9 @@ mod tests { attachments: vec![attachment.id.clone()], reply_to: None, }, - &state, + &client, &db, &Services::default(), - None, &test::directory(), &test::directory(), ) diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 2217748..245cdef 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -3,11 +3,14 @@ use common::{ error::Error as CommonError, model::{SessionInfo, User}, permission, time, + transport::Close, validate::{validate_device, validate_password, validate_username}, }; use turso::Connection; -use crate::{database::new_id, error::ServerError, invite, server_ban, server_settings, user}; +use crate::{ + database::new_id, error::ServerError, hub::Hub, invite, server_ban, server_settings, user, +}; const SALT_LENGTH: usize = 16; const TOKEN_LENGTH: usize = 32; @@ -101,7 +104,7 @@ pub async fn sessions(user_id: &str, conn: &Connection) -> Result Result<(), ServerError> { } pub async fn resume(token: &str, conn: &Connection) -> Result { - let user = user::by_session_token(token, conn).await?; + let user = match user::by_session_token(token, conn).await { + Err(ServerError::Wire(CommonError::WrongCredentials)) => { + return Err(CommonError::Unauthenticated.into()); + } + user => user?, + }; admit(&user, conn).await?; seen(&user.id, token, conn).await?; @@ -197,7 +205,7 @@ pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> { Ok(()) } -pub async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { +pub(crate) async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) .await?; @@ -210,8 +218,33 @@ pub async fn reset_password( conn: &Connection, ) -> Result<(), ServerError> { validate_password(password)?; - user::set_password_hash(user_id, &hash(password)?, conn).await?; - revoke_sessions(user_id, conn).await + user::set_password_hash(user_id, &hash(password)?, conn).await +} + +pub enum Revoke<'a> { + User(&'a str), + Session { + user_id: &'a str, + session_id: &'a str, + }, +} + +pub async fn revoke(hub: &Hub, target: Revoke<'_>, conn: &Connection) -> Result<(), ServerError> { + match target { + Revoke::User(user_id) => { + revoke_sessions(user_id, conn).await?; + hub.kick_user(user_id, Close::Revoked); + } + Revoke::Session { + user_id, + session_id, + } => { + let token = revoke_session(user_id, session_id, conn).await?; + hub.kick_token(&token, Close::Revoked); + } + } + + Ok(()) } #[cfg(test)] diff --git a/crates/server/src/datagram.rs b/crates/server/src/datagram.rs index 360f8f9..c996734 100644 --- a/crates/server/src/datagram.rs +++ b/crates/server/src/datagram.rs @@ -1,19 +1,12 @@ -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use quinn::Connection; -use crate::network::{Shared, State, publish}; +use crate::{hub::Client, network::Shared, publish::publish}; -pub(crate) async fn relay_datagrams( - connection: Connection, - state: Arc>, - shared: Shared, -) { +pub(crate) async fn relay_datagrams(connection: Connection, client: Arc, shared: Shared) { while let Ok(bytes) = connection.read_datagram().await { - if matches!(*state.lock().unwrap(), State::Authenticated { .. }) { - shared.services.voice.relay(connection.stable_id(), &bytes); - let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); - publish(&shared, broadcasts).await; - } + let broadcasts = shared.services.rooms.relay(&client, &bytes); + publish(&shared, broadcasts).await; } } diff --git a/crates/server/src/hub.rs b/crates/server/src/hub.rs new file mode 100644 index 0000000..c32340f --- /dev/null +++ b/crates/server/src/hub.rs @@ -0,0 +1,218 @@ +use std::{ + collections::{HashMap, HashSet}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, +}; + +use bytes::Bytes; +use common::transport::Close; +use quinn::Connection; +use tokio::sync::mpsc::{self, error::TrySendError}; +use tracing::warn; + +pub type ConnId = u64; + +const QUEUE_LENGTH: usize = 256; + +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +pub struct Signed { + pub user_id: String, + pub token: String, +} + +pub struct Client { + pub id: ConnId, + pub conn: Option, + pub me: Option, + tx: mpsc::Sender, + pub closed: AtomicBool, + pub watching: Mutex>, + pub ghost_logged: Mutex>, +} + +impl Client { + pub fn new(conn: Option, me: Option) -> (Arc, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(QUEUE_LENGTH); + let client = Arc::new(Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), + conn, + me, + tx, + closed: AtomicBool::new(false), + watching: Mutex::new(None), + ghost_logged: Mutex::new(HashSet::new()), + }); + + (client, rx) + } + + pub fn detached(me: Option) -> Arc { + Self::new(None, me).0 + } + + pub fn user_id(&self) -> Option<&str> { + self.me.as_ref().map(|me| me.user_id.as_str()) + } + + pub fn close(&self, close: Close) { + if let Some(conn) = &self.conn { + conn.close(close.code(), close.reason().as_bytes()); + } + } + + pub fn first_visit(&self, community_id: &str) -> bool { + self.ghost_logged + .lock() + .unwrap() + .insert(community_id.to_string()) + } + + pub fn watch(&self, community_id: Option<&str>) { + *self.watching.lock().unwrap() = community_id.map(str::to_string); + } + + fn watches(&self, community_id: &str) -> bool { + self.watching.lock().unwrap().as_deref() == Some(community_id) + } +} + +pub enum Presence { + None, + Online(String), + Offline(String), +} + +#[derive(Clone, Default)] +pub struct Hub(Arc>>>); + +impl Hub { + pub fn add(&self, client: Arc) -> Presence { + let mut clients = self.0.lock().unwrap(); + let user_id = client.user_id().map(str::to_string); + let was_online = user_id + .as_deref() + .is_some_and(|user_id| Self::online_in(&clients, user_id)); + clients.insert(client.id, client); + + match user_id { + Some(user_id) if !was_online => Presence::Online(user_id), + _ => Presence::None, + } + } + + pub fn remove(&self, id: ConnId) -> Presence { + let mut clients = self.0.lock().unwrap(); + let Some(client) = clients.remove(&id) else { + return Presence::None; + }; + + match client.user_id() { + Some(user_id) if !Self::online_in(&clients, user_id) => { + Presence::Offline(user_id.to_string()) + } + _ => Presence::None, + } + } + + fn online_in(clients: &HashMap>, user_id: &str) -> bool { + clients + .values() + .any(|client| client.user_id() == Some(user_id)) + } + + pub fn is_online(&self, user_id: &str) -> bool { + Self::online_in(&self.0.lock().unwrap(), user_id) + } + + pub fn user_ids(&self) -> Vec { + let mut user_ids: Vec = self + .0 + .lock() + .unwrap() + .values() + .filter_map(|client| client.user_id().map(str::to_string)) + .collect(); + user_ids.sort(); + user_ids.dedup(); + + user_ids + } + + pub fn online(&self) -> usize { + self.user_ids().len() + } + + pub fn conns_of(&self, user_ids: &[String]) -> Vec { + self.0 + .lock() + .unwrap() + .values() + .filter(|client| { + client + .user_id() + .is_some_and(|id| user_ids.iter().any(|u| u == id)) + }) + .map(|client| client.id) + .collect() + } + + pub fn watchers(&self, community_id: &str) -> Vec { + self.0 + .lock() + .unwrap() + .values() + .filter(|client| client.watches(community_id)) + .map(|client| client.id) + .collect() + } + + pub fn all(&self) -> Vec { + self.0.lock().unwrap().keys().copied().collect() + } + + pub fn send(&self, ids: &[ConnId], bytes: &Bytes, droppable: bool) { + let clients = self.0.lock().unwrap(); + for id in ids { + let Some(client) = clients.get(id) else { + continue; + }; + match client.tx.try_send(bytes.clone()) { + Ok(()) | Err(TrySendError::Closed(_)) => {} + Err(TrySendError::Full(_)) if droppable => {} + Err(TrySendError::Full(_)) => { + warn!("client {} too slow", client.id); + client.close(Close::Slow); + } + } + } + } + + fn kick_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { + let targets: Vec> = self + .0 + .lock() + .unwrap() + .values() + .filter(|client| client.me.as_ref().is_some_and(&matches)) + .cloned() + .collect(); + for client in targets { + client.close(close); + } + } + + pub fn kick_user(&self, user_id: &str, close: Close) { + self.kick_where(|me| me.user_id == user_id, close); + } + + pub fn kick_token(&self, token: &str, close: Close) { + self.kick_where(|me| me.token == token, close); + } + + pub fn kick_all_except(&self, keep: &[String], close: Close) { + self.kick_where(|me| !keep.contains(&me.user_id), close); + } +} diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 3df6446..ac39fe7 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -9,6 +9,7 @@ pub mod datagram; pub mod direct; pub mod error; pub mod friend; +pub mod hub; pub mod invitation; pub mod invite; pub mod log; @@ -16,17 +17,17 @@ pub mod message; pub mod network; pub mod notes; pub mod overview; +pub mod publish; pub mod rate_limit; pub mod report; pub mod request; pub mod retention; +pub mod rooms; pub mod server_ban; pub mod server_settings; -pub mod share; pub mod stats; pub mod user; pub mod user_community; -pub mod voice; #[cfg(test)] mod test; @@ -87,7 +88,6 @@ pub async fn showtime() -> Result<(), ServerError> { let attachments = sibling_directory(&config.database_path, "attachments")?; let backups = sibling_directory(&config.database_path, "backups")?; tokio::spawn(attachment::collect(database.clone(), attachments.clone())); - tokio::spawn(retention::collect(database.clone(), attachments.clone())); network::serve( &config.server_address, diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index 4bc8e9a..9eec529 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -1,19 +1,16 @@ -use std::{ - collections::{HashMap, HashSet}, - path::PathBuf, - sync::{Arc, Mutex}, -}; +use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; +use bytes::Bytes; use common::{ - event::Event as Push, frame::{self, DOWN_MAX, Sending, UP_MAX}, model::User, open::Open, request::Request, + session::{Hello, Welcome}, transport::Close, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; -use tokio::{sync::mpsc, task::JoinHandle}; +use tokio::sync::mpsc; use tracing::{info, warn}; use crate::{ @@ -21,187 +18,38 @@ use crate::{ database::{self, DB}, datagram, error::ServerError, + hub::{Client, Hub, Presence, Signed}, + publish::publish, rate_limit::RateLimit, - request::{self, Broadcast}, - server_ban, - share::Shares, - voice::Voice, + request, retention, + rooms::Rooms, + server_ban, stats, user, }; -const CHANNEL_LENGTH: usize = 2048; -const SESSION_LENGTH: usize = 64; - -struct Signed { - user_id: String, - token: String, - connection: Connection, -} - -#[derive(Clone, Default)] -pub struct Presence(Arc>>); - -#[derive(Default)] -struct VisitBook { - seen: HashMap>, - watching: HashMap, -} - -#[derive(Clone, Default)] -pub struct Visits(Arc>); - -impl Visits { - pub fn first(&self, connection_id: usize, community_id: &str) -> bool { - self.0 - .lock() - .unwrap() - .seen - .entry(connection_id) - .or_default() - .insert(community_id.to_string()) - } - - pub fn watch(&self, connection_id: usize, community_id: Option<&str>) { - let watching = &mut self.0.lock().unwrap().watching; - match community_id { - Some(community_id) => watching.insert(connection_id, community_id.to_string()), - None => watching.remove(&connection_id), - }; - } - - fn watches(&self, connection_id: usize, community_id: &str) -> bool { - self.0 - .lock() - .unwrap() - .watching - .get(&connection_id) - .is_some_and(|watched| watched == community_id) - } - - pub fn forget(&self, connection_id: usize) { - let mut book = self.0.lock().unwrap(); - book.seen.remove(&connection_id); - book.watching.remove(&connection_id); - } -} +const HELLO_DEADLINE: Duration = Duration::from_secs(5); #[derive(Clone, Default)] pub struct Services { - pub voice: Voice, - pub share: Shares, - pub presence: Presence, + pub rooms: Rooms, + pub hub: Hub, pub rate_limit: RateLimit, - pub visits: Visits, -} - -impl Presence { - pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) { - let mut signed = self.0.lock().unwrap(); - if connection.close_reason().is_some() { - return; - } - signed.insert( - connection.stable_id(), - Signed { - user_id: user_id.to_string(), - token: token.to_string(), - connection: connection.clone(), - }, - ); - } - - pub fn is_online(&self, user_id: &str) -> bool { - self.0 - .lock() - .unwrap() - .values() - .any(|signed| signed.user_id == user_id) - } - - pub fn sign_out(&self, connection_id: usize) { - self.0.lock().unwrap().remove(&connection_id); - } - - pub fn user_ids(&self) -> Vec { - let mut user_ids: Vec = self - .0 - .lock() - .unwrap() - .values() - .map(|signed| signed.user_id.clone()) - .collect(); - user_ids.sort(); - user_ids.dedup(); - - user_ids - } - - pub fn online(&self) -> usize { - self.user_ids().len() - } - - fn close_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { - let connections: Vec = self - .0 - .lock() - .unwrap() - .values() - .filter(|signed| matches(signed)) - .map(|signed| signed.connection.clone()) - .collect(); - for connection in connections { - connection.close(close.code(), close.reason().as_bytes()); - } - } - - pub fn disconnect(&self, user_id: &str, close: Close) { - self.close_where(|signed| signed.user_id == user_id, close); - } - - pub fn disconnect_except(&self, keep: &[String], close: Close) { - self.close_where(|signed| !keep.contains(&signed.user_id), close); - } - - pub fn disconnect_token(&self, token: &str) { - self.close_where(|signed| signed.token == token, Close::Revoked); - } -} - -#[derive(Clone)] -pub enum State { - Anonymous, - Authenticated { user: User, token: String }, -} - -enum Event { - Connected { - connection_id: usize, - connection: Connection, - send_stream: SendStream, - }, - Signed { - connection_id: usize, - user_id: Option, - }, - Broadcast(Box), -} - -struct Session { - connection_id: usize, - user_id: Option, - connection: Connection, - event_sender: mpsc::Sender>, - writer: JoinHandle<()>, } #[derive(Clone)] pub(crate) struct Shared { - event_sender: mpsc::Sender, - db: DB, + pub(crate) db: DB, pub(crate) services: Services, - directory: PathBuf, + pub(crate) directory: PathBuf, backups: PathBuf, } +struct Pending { + client: Arc, + events: mpsc::Receiver, + reply_stream: Sending, + user: Option, +} + pub async fn serve( server_address: &str, server_config: quinn::ServerConfig, @@ -212,17 +60,15 @@ pub async fn serve( let endpoint = Endpoint::server(server_config, server_address.parse()?)?; info!("listening on {server_address}"); - let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); - let services = Services::default(); - tokio::spawn(the_actor(event_receiver, services.visits.clone())); let shared = Shared { - event_sender, db, - services, + services: Services::default(), directory, backups, }; + tokio::spawn(retention::collect(shared.clone())); + while let Some(incoming) = endpoint.accept().await { tokio::spawn(handle_connection(incoming, shared.clone())); } @@ -247,31 +93,58 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv return Ok(()); } let connection = incoming.await?; - let send_stream = connection.open_uni().await?; - let _ = shared - .event_sender - .send(Event::Connected { - connection_id: connection.stable_id(), - connection: connection.clone(), - send_stream, - }) - .await; - - let state = Arc::new(Mutex::new(State::Anonymous)); + let pending = match tokio::time::timeout(HELLO_DEADLINE, greet(&connection, &shared)).await { + Ok(Ok(Some(pending))) => pending, + Ok(Ok(None)) => return Ok(()), + Ok(Err(error)) => { + close(&connection, Close::Protocol); + return Err(error); + } + Err(_) => { + close(&connection, Close::Protocol); + return Ok(()); + } + }; + let Pending { + client, + events, + reply_stream, + user, + } = pending; + let hub = &shared.services.hub; + + let presence = hub.add(Arc::clone(&client)); + match welcome(&client, reply_stream, user, &shared).await { + Ok(true) => {} + Ok(false) => { + publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; + let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; + return Ok(()); + } + Err(error) => { + publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; + close(&connection, Close::Protocol); + return Err(error); + } + } + let send_stream = match connection.open_uni().await { + Ok(stream) => stream, + Err(error) => { + publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; + return Err(error.into()); + } + }; + tokio::spawn(write_events(events, send_stream)); + publish_presence(&shared, presence).await; tokio::spawn(datagram::relay_datagrams( connection.clone(), - Arc::clone(&state), + Arc::clone(&client), shared.clone(), )); while let Ok(streams) = connection.accept_bi().await { - let route = route( - connection.clone(), - Arc::clone(&state), - streams, - shared.clone(), - ); + let route = route(Arc::clone(&client), streams, shared.clone()); tokio::spawn(async move { if let Err(error) = route.await { warn!("stream: {error}"); @@ -279,39 +152,114 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv }); } - shared.services.presence.sign_out(connection.stable_id()); - shared.services.visits.forget(connection.stable_id()); + client.closed.store(true, Ordering::Release); + let presence = hub.remove(client.id); - if let Some((user_id, token)) = signed_in(&state) { + if let Some(me) = &client.me { let conn = database::connect(&shared.db).await?; - let mut broadcasts = request::leave_connection_voice( - &shared.services.voice, - &shared.services.share, - Some(&connection), - &conn, - ) - .await?; - broadcasts - .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); + let mut broadcasts = match shared.services.rooms.leave(client.id) { + Some(departure) => request::departed(departure, &conn).await?, + None => Vec::new(), + }; + if let Presence::Offline(user_id) = &presence { + broadcasts.extend(request::presence_changed(hub, user_id, &conn).await?); + } publish(&shared, broadcasts).await; - authentication::seen(&user_id, &token, &conn).await?; + authentication::seen(&me.user_id, &me.token, &conn).await?; } Ok(()) } +fn close(connection: &Connection, close: Close) { + connection.close(close.code(), close.reason().as_bytes()); +} + +async fn greet(connection: &Connection, shared: &Shared) -> Result, ServerError> { + let (send_stream, mut receive_stream) = connection.accept_bi().await?; + let mut reply_stream = Sending::new(send_stream); + let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; + + match admit(hello, connection, shared).await { + Ok((me, user)) => { + let (client, events) = Client::new(Some(connection.clone()), me); + + Ok(Some(Pending { + client, + events, + reply_stream, + user, + })) + } + Err(error) => { + let reply: Result = Err(error.into()); + frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; + reply_stream.finish()?; + let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; + + Ok(None) + } + } +} + +async fn admit( + hello: Hello, + connection: &Connection, + shared: &Shared, +) -> Result<(Option, Option), ServerError> { + let Some(token) = hello.token else { + return Ok((None, None)); + }; + let conn = database::connect(&shared.db).await?; + let user = authentication::resume(&token, &conn).await?; + stats::mark_active(&user.id, &conn).await?; + request::record_address(&user, Some(connection), &conn).await?; + if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await { + warn!("device: {error}"); + } + let me = Signed { + user_id: user.id.clone(), + token, + }; + + Ok((Some(me), Some(user))) +} + +async fn welcome( + client: &Client, + mut reply_stream: Sending, + user: Option, + shared: &Shared, +) -> Result { + let checked = match &client.me { + Some(me) => { + let conn = database::connect(&shared.db).await?; + authentication::resume(&me.token, &conn).await.map(Some) + } + None => Ok(user.clone()), + }; + let accepted = checked.is_ok(); + let reply: Result = match checked { + Ok(_) => Ok(Welcome { user }), + Err(error) => Err(error.into()), + }; + frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; + reply_stream.finish()?; + + Ok(accepted) +} + async fn route( - connection: Connection, - state: Arc>, + client: Arc, (send_stream, mut receive_stream): (SendStream, RecvStream), shared: Shared, ) -> Result<(), ServerError> { let send_stream = Sending::new(send_stream); let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; - let user = signed_user(&state); match open { - Open::Call(request) => answer(connection, state, request, send_stream, shared).await, + Open::Call(request) => answer(client, request, send_stream, shared).await, Open::Upload(upload) => { + let user = signed_user(&client, &shared).await?; attachment::upload( user.as_ref(), upload, @@ -323,6 +271,7 @@ async fn route( .await } Open::Fetch(blob) => { + let user = signed_user(&client, &shared).await?; attachment::fetch( user.as_ref(), blob, @@ -336,54 +285,30 @@ async fn route( } } +async fn signed_user(client: &Client, shared: &Shared) -> Result, ServerError> { + let Some(me) = &client.me else { + return Ok(None); + }; + let conn = database::connect(&shared.db).await?; + + Ok(Some(user::read(&me.user_id, &conn).await?)) +} + async fn answer( - connection: Connection, - state: Arc>, + client: Arc, request: Request, mut send_stream: Sending, shared: Shared, ) -> Result<(), ServerError> { - let before = signed_in(&state); let (response, broadcasts) = request::handle( request, - &state, + &client, &shared.db, &shared.services, - Some(&connection), &shared.directory, &shared.backups, ) .await; - let after = signed_in(&state); - - if before != after { - let connection_id = connection.stable_id(); - shared.services.visits.forget(connection_id); - match &after { - Some((user_id, token)) => shared - .services - .presence - .sign_in(&connection, user_id, token), - None => shared.services.presence.sign_out(connection_id), - } - let before_id = before.map(|(user_id, _)| user_id); - let after_id = after.map(|(user_id, _)| user_id); - let _ = shared - .event_sender - .send(Event::Signed { - connection_id, - user_id: after_id.clone(), - }) - .await; - if let Some(user_id) = &before_id { - broadcast_presence(&shared, user_id).await; - } - if after_id != before_id - && let Some(user_id) = &after_id - { - broadcast_presence(&shared, user_id).await; - } - } publish(&shared, broadcasts).await; @@ -393,18 +318,19 @@ async fn answer( Ok(()) } -pub(crate) async fn publish(shared: &Shared, broadcasts: Vec) { - for broadcast in broadcasts { - let _ = shared - .event_sender - .send(Event::Broadcast(Box::new(broadcast))) - .await; +fn first_named(first: Presence, second: Presence) -> Presence { + match first { + Presence::None => second, + named => named, } } -async fn broadcast_presence(shared: &Shared, user_id: &str) { +async fn publish_presence(shared: &Shared, presence: Presence) { + let (Presence::Online(user_id) | Presence::Offline(user_id)) = presence else { + return; + }; let broadcasts = match database::connect(&shared.db).await { - Ok(conn) => request::presence_changed(&shared.services.presence, user_id, &conn).await, + Ok(conn) => request::presence_changed(&shared.services.hub, &user_id, &conn).await, Err(error) => Err(error), }; match broadcasts { @@ -413,94 +339,12 @@ async fn broadcast_presence(shared: &Shared, user_id: &str) { } } -fn signed_user(state: &Mutex) -> Option { - match &*state.lock().unwrap() { - State::Anonymous => None, - State::Authenticated { user, .. } => Some(user.clone()), - } -} - -fn signed_in(state: &Mutex) -> Option<(String, String)> { - match &*state.lock().unwrap() { - State::Anonymous => None, - State::Authenticated { user, token } => Some((user.id.clone(), token.clone())), - } -} - -async fn write_session(mut event_receiver: mpsc::Receiver>, send_stream: SendStream) { +async fn write_events(mut events: mpsc::Receiver, send_stream: SendStream) { let mut send_stream = Sending::new(send_stream); - while let Some(event) = event_receiver.recv().await { - if let Err(error) = frame::write(&mut send_stream, &*event, DOWN_MAX).await { - warn!("session write: {error}"); + while let Some(bytes) = events.recv().await { + if let Err(error) = send_stream.get().write_all(&bytes).await { + warn!("event write: {error}"); break; } } } - -async fn the_actor(mut event_receiver: mpsc::Receiver, visits: Visits) { - let mut sessions: Vec = Vec::new(); - - while let Some(event) = event_receiver.recv().await { - sessions.retain(|session| { - !session.writer.is_finished() && session.connection.close_reason().is_none() - }); - - match event { - Event::Connected { - connection_id, - connection, - send_stream, - } => { - let (event_sender, event_receiver) = mpsc::channel(SESSION_LENGTH); - let writer = tokio::spawn(write_session(event_receiver, send_stream)); - - sessions.push(Session { - connection_id, - user_id: None, - connection, - event_sender, - writer, - }); - } - Event::Signed { - connection_id, - user_id, - } => { - if let Some(session) = sessions - .iter_mut() - .find(|session| session.connection_id == connection_id) - { - session.user_id = user_id; - } - } - Event::Broadcast(broadcast) => { - let community_id = broadcast.event.community_id().map(str::to_string); - let event = Arc::new(broadcast.event); - - sessions.retain(|session| { - let Some(user_id) = &session.user_id else { - return true; - }; - let watching = community_id.as_deref().is_some_and(|community_id| { - visits.watches(session.connection_id, community_id) - }); - if !broadcast.user_ids.contains(user_id) && !watching { - return true; - } - - match session.event_sender.try_send(Arc::clone(&event)) { - Ok(()) => true, - Err(error) => { - warn!("session dropped {user_id}: {error}"); - session.writer.abort(); - session - .connection - .close(Close::Slow.code(), Close::Slow.reason().as_bytes()); - false - } - } - }); - } - } - } -} diff --git a/crates/server/src/overview.rs b/crates/server/src/overview.rs index d8df43f..4dc4df3 100644 --- a/crates/server/src/overview.rs +++ b/crates/server/src/overview.rs @@ -1,13 +1,9 @@ use common::model::{Overview, Role}; use turso::Connection; -use crate::{community::Kind, error::ServerError, network::Presence, voice::Voice}; +use crate::{community::Kind, error::ServerError, hub::Hub, rooms::Rooms}; -pub async fn read( - presence: &Presence, - voice: &Voice, - conn: &Connection, -) -> Result { +pub async fn read(hub: &Hub, rooms: &Rooms, conn: &Connection) -> Result { let mut rows = conn .query( "SELECT @@ -33,8 +29,8 @@ pub async fn read( users: count(0)?, builders: count(1)?, communities: count(2)?, - online: presence.online() as u64, - voice: voice.count() as u64, + online: hub.online() as u64, + voice: rooms.count() as u64, storage_bytes: count(3)?, }) } diff --git a/crates/server/src/publish.rs b/crates/server/src/publish.rs new file mode 100644 index 0000000..4422ac6 --- /dev/null +++ b/crates/server/src/publish.rs @@ -0,0 +1,117 @@ +use std::collections::BTreeSet; + +use bytes::Bytes; +use common::{ + event::{Down, Event, Media}, + frame::{self, DOWN_MAX}, +}; +use tracing::warn; + +use crate::{ + community, database, error::ServerError, friend, hub::ConnId, network::Shared, user, + user_community, +}; + +pub enum To { + User(String), + Users(Vec), + Community(String), + CommunityExcept(String, String), + Related(String), + Builders, + Everyone, + Conn(ConnId), +} + +pub struct Broadcast { + pub to: To, + pub down: Down, +} + +impl Broadcast { + pub fn new(to: To, event: Event) -> Self { + Self { + to, + down: Down::Event(Box::new(event)), + } + } + + pub fn media(conn: ConnId, media: Media) -> Self { + Self { + to: To::Conn(conn), + down: Down::Media(media), + } + } +} + +pub(crate) async fn publish(shared: &Shared, broadcasts: Vec) { + for broadcast in broadcasts { + let ids = match resolve(shared, &broadcast.to).await { + Ok(ids) => ids, + Err(error) => { + warn!("resolve: {error}"); + continue; + } + }; + let droppable = matches!(&broadcast.down, Down::Event(event) if matches!(**event, Event::Typing { .. })); + let framed = frame::encode(&broadcast.down); + if framed.len() - 4 > DOWN_MAX as usize { + warn!("event too large: {} bytes", framed.len() - 4); + continue; + } + let bytes = Bytes::from(framed); + shared.services.hub.send(&ids, &bytes, droppable); + } +} + +async fn resolve(shared: &Shared, to: &To) -> Result, ServerError> { + let hub = &shared.services.hub; + let ids = match to { + To::Conn(id) => vec![*id], + To::Everyone => hub.all(), + To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), + To::Users(user_ids) => hub.conns_of(user_ids), + To::Builders => { + let conn = database::connect(&shared.db).await?; + hub.conns_of(&user::builder_ids(&conn).await?) + } + To::Community(community_id) => community_conns(shared, community_id).await?, + To::CommunityExcept(community_id, user_id) => { + let mut ids = community_conns(shared, community_id).await?; + let own = hub.conns_of(std::slice::from_ref(user_id)); + ids.retain(|id| !own.contains(id)); + ids + } + To::Related(user_id) => { + let conn = database::connect(&shared.db).await?; + hub.conns_of(&related_user_ids(user_id, &conn).await?) + } + }; + + Ok(ids) +} + +async fn community_conns(shared: &Shared, community_id: &str) -> Result, ServerError> { + let hub = &shared.services.hub; + let conn = database::connect(&shared.db).await?; + let mut ids = hub.conns_of(&user_community::member_ids(community_id, &conn).await?); + ids.extend(hub.watchers(community_id)); + ids.sort_unstable(); + ids.dedup(); + Ok(ids) +} + +pub(crate) async fn related_user_ids( + user_id: &str, + conn: &turso::Connection, +) -> Result, ServerError> { + let mut user_ids = BTreeSet::from([user_id.to_string()]); + for community in community::communities_of(user_id, conn).await? { + user_ids.extend(user_community::member_ids(&community.id, conn).await?); + } + for friend in friend::state(user_id, conn).await?.friends { + user_ids.insert(friend.id); + } + + Ok(user_ids.into_iter().collect()) +} diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index c5c2438..6248fce 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -1,8 +1,4 @@ -use std::{ - collections::{BTreeMap, BTreeSet}, - path::Path, - sync::Mutex, -}; +use std::{collections::BTreeMap, path::Path}; use common::{ error::Error as CommonError, @@ -29,33 +25,29 @@ use crate::{ database::{self, DB}, direct, error::ServerError, - friend, invitation, invite, log, message, - network::{self, Services, State}, + friend, + hub::{Client, Hub}, + invitation, invite, log, message, + network::Services, notes, overview, + publish::{Broadcast, To, related_user_ids}, rate_limit::RateLimit, - report, server_ban, server_settings, - share::Shares, - stats, user, user_community, - voice::{CallEnd, Left, Voice}, + report, + rooms::{Departure, Rooms}, + server_ban, server_settings, stats, user, user_community, }; -pub struct Broadcast { - pub event: Event, - pub user_ids: Vec, -} - type Outcome = (Response, Vec); pub async fn handle( request: Request, - state: &Mutex, + client: &Client, db: &DB, services: &Services, - connection: Option<&quinn::Connection>, directory: &Path, backups: &Path, ) -> (Result, Vec) { - match dispatch(request, state, db, services, connection, directory, backups).await { + match dispatch(request, client, db, services, directory, backups).await { Ok((response, broadcasts)) => (Ok(response), broadcasts), Err(error) => (Err(error.into()), Vec::new()), } @@ -63,20 +55,18 @@ pub async fn handle( async fn dispatch( request: Request, - state: &Mutex, + client: &Client, db: &DB, services: &Services, - connection: Option<&quinn::Connection>, directory: &Path, backups: &Path, ) -> Result { let Services { - voice, - share, - presence, + rooms, + hub, rate_limit, - visits, } = services; + let connection = client.conn.as_ref(); let mut conn = database::connect(db).await?; let outcome = match request { @@ -89,43 +79,30 @@ async fn dispatch( let (user, token) = authentication::register(&username, &password, invite.as_deref(), &mut conn) .await?; - enter(state, user, token, voice, share, connection, &conn).await? + (Response::Session { user, token }, Vec::new()) } Request::Login { username, password } => { limit_logins(rate_limit, connection, &conn).await?; let (user, token) = authentication::login(&username, &password, &conn).await?; - enter(state, user, token, voice, share, connection, &conn).await? - } - Request::Resume { token } => { - let user = authentication::resume(&token, &conn).await?; - enter(state, user, token, voice, share, connection, &conn).await? - } - Request::Detach => { - authenticated(state, &conn).await?; - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; - set_state(state, State::Anonymous); - (Response::Done, broadcasts) + (Response::Session { user, token }, Vec::new()) } Request::Logout => { - authenticated(state, &conn).await?; - let token = session_token(state)?; - authentication::logout(&token, &conn).await?; - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; - set_state(state, State::Anonymous); - (Response::Done, broadcasts) + authenticated(client, &conn).await?; + let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; + authentication::logout(&me.token, &conn).await?; + (Response::Done, Vec::new()) } Request::ReadUser { user_id } => { - authenticated(state, &conn).await?; + authenticated(client, &conn).await?; ( Response::User(user::read(&user_id, &conn).await?), Vec::new(), ) } Request::UpdateUser { username } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let user = user::update(&me.id, &username, &conn).await?; - cache_user(state, user.clone()); - let broadcasts = user_updated(&user, &conn).await?; + let broadcasts = user_updated(&user); (Response::User(user), broadcasts) } Request::ServerSettings => ( @@ -133,9 +110,8 @@ async fn dispatch( Vec::new(), ), Request::UpdateServerSettings { settings } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; validate_server_settings(&settings)?; - let previous = server_settings::read(&conn).await?; server_settings::update(&settings, &conn).await?; admin_log::record( Some(&me.id), @@ -147,28 +123,16 @@ async fn dispatch( .await?; if settings.maintenance { let builders = user::builder_ids(&conn).await?; - presence.disconnect_except(&builders, Close::Maintenance); + hub.kick_all_except(&builders, Close::Maintenance); } - let broadcasts = if settings.announcement == previous.announcement { - Vec::new() - } else { - vec![Broadcast { - event: Event::Announcement { - text: settings.announcement.clone(), - }, - user_ids: presence.user_ids(), - }] - }; + let broadcasts = vec![Broadcast::new( + To::Everyone, + Event::SettingsUpdated(settings.clone()), + )]; (Response::ServerSettings(settings), broadcasts) } - Request::SetDevice { name } => { - authenticated(state, &conn).await?; - let token = session_token(state)?; - authentication::set_device(&token, &name, &conn).await?; - (Response::Done, Vec::new()) - } Request::Sessions { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; ( Response::Sessions(authentication::sessions(&user_id, &conn).await?), @@ -179,10 +143,17 @@ async fn dispatch( user_id, session_id, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; - let token = authentication::revoke_session(&user_id, &session_id, &conn).await?; - presence.disconnect_token(&token); + authentication::revoke( + hub, + authentication::Revoke::Session { + user_id: &user_id, + session_id: &session_id, + }, + &conn, + ) + .await?; admin_log::record( Some(&me.id), Some(&user_id), @@ -194,7 +165,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::RenameUser { user_id, username } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let target = managed(&me, &user_id, &conn).await?; let user = user::update(&user_id, &username, &conn).await?; admin_log::record( @@ -207,11 +178,11 @@ async fn dispatch( &conn, ) .await?; - let broadcasts = user_updated(&user, &conn).await?; + let broadcasts = user_updated(&user); (Response::User(user), broadcasts) } Request::CreateUser { username, password } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; let user = authentication::create_account(&username, &password, &conn).await?; admin_log::record( Some(&me.id), @@ -224,7 +195,7 @@ async fn dispatch( (Response::User(user), Vec::new()) } Request::Users => { - builder(state, &conn).await?; + builder(client, &conn).await?; (Response::Users(user::all(&conn).await?), Vec::new()) } Request::AdminLogs { @@ -234,7 +205,7 @@ async fn dispatch( after_ms, before_ms, } => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( Response::AdminLogs( admin_log::list( @@ -251,21 +222,21 @@ async fn dispatch( ) } Request::DailyStats { days } => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( Response::DailyStats(stats::daily(days, &conn).await?), Vec::new(), ) } Request::Overview => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( - Response::Overview(overview::read(presence, voice, &conn).await?), + Response::Overview(overview::read(hub, rooms, &conn).await?), Vec::new(), ) } Request::SuspendUser { user_id, suspended } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; user::set_suspended(&user_id, suspended, &conn).await?; let action = if suspended { @@ -275,16 +246,14 @@ async fn dispatch( }; admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?; if suspended { - authentication::revoke_sessions(&user_id, &conn).await?; - presence.disconnect(&user_id, Close::Revoked); + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; } (Response::Done, Vec::new()) } Request::RevokeSessions { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; - authentication::revoke_sessions(&user_id, &conn).await?; - presence.disconnect(&user_id, Close::Revoked); + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; admin_log::record( Some(&me.id), Some(&user_id), @@ -296,10 +265,10 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::ResetPassword { user_id, password } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; authentication::reset_password(&user_id, &password, &conn).await?; - presence.disconnect(&user_id, Close::Revoked); + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; admin_log::record( Some(&me.id), Some(&user_id), @@ -311,7 +280,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::ClearProfile { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; user::set_avatar(&user_id, None, &mut conn).await?; let user = user::update_status(&user_id, "", &conn).await?; @@ -323,11 +292,11 @@ async fn dispatch( &conn, ) .await?; - let broadcasts = user_updated(&user, &conn).await?; + let broadcasts = user_updated(&user); (Response::User(user), broadcasts) } Request::SetRole { user_id, role } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure(permission::can_set_role(me.role, me.id == user_id))?; let user = user::set_role_by_id(&user_id, role, &conn).await?; admin_log::record( @@ -338,33 +307,32 @@ async fn dispatch( &conn, ) .await?; - let mut broadcasts = user_updated(&user, &conn).await?; + let mut broadcasts = user_updated(&user); if permission::is_builder(role) { - broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); + broadcasts.extend(voice_unmuted(rooms, &user_id, &conn).await?); } else { user::set_ghost(&user_id, false, &conn).await?; - presence.disconnect(&user_id, Close::Revoked); + hub.kick_user(&user_id, Close::Revoked); } (Response::User(user), broadcasts) } Request::UpdateStatus { status } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let user = user::update_status(&me.id, &status, &conn).await?; - cache_user(state, user.clone()); - let broadcasts = user_updated(&user, &conn).await?; + let broadcasts = user_updated(&user); (Response::User(user), broadcasts) } Request::UpdatePresence { presence: chosen } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; user::update_presence(&me.id, chosen, &conn).await?; - let broadcasts = presence_changed(presence, &me.id, &conn).await?; + let broadcasts = presence_changed(hub, &me.id, &conn).await?; (Response::Done, broadcasts) } Request::ReadPresences => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let mut presences = Vec::new(); for user_id in related_user_ids(&me.id, &conn).await? { - let effective = effective_presence(presence, &user_id, &conn).await?; + let effective = effective_presence(hub, &user_id, &conn).await?; if effective != Presence::Offline || user_id == me.id { presences.push((user_id, effective)); } @@ -372,29 +340,27 @@ async fn dispatch( (Response::Presences(presences), Vec::new()) } Request::UpdateAvatar { image } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?; let user = user::set_avatar(&me.id, Some(&image), &mut conn).await?; - cache_user(state, user.clone()); - let broadcasts = user_updated(&user, &conn).await?; + let broadcasts = user_updated(&user); (Response::User(user), broadcasts) } Request::RemoveAvatar => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let user = user::set_avatar(&me.id, None, &mut conn).await?; - cache_user(state, user.clone()); - let broadcasts = user_updated(&user, &conn).await?; + let broadcasts = user_updated(&user); (Response::User(user), broadcasts) } Request::ReadAvatar { avatar_id } => { - authenticated(state, &conn).await?; + authenticated(client, &conn).await?; ( Response::Avatar(user::avatar(&avatar_id, &conn).await?), Vec::new(), ) } Request::DeleteUser { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_delete_user( me.role, @@ -414,34 +380,32 @@ async fn dispatch( .await?; } for community_id in user_community::owned(&user_id, &tx).await? { - let members = user_community::members(&community_id, &tx).await?; - broadcasts.extend(voice_closed(voice, share, &community_id, &tx).await?); + let member_ids = user_community::member_ids(&community_id, &tx).await?; + broadcasts.extend(voice_closed(rooms, &community_id, &tx).await?); community::delete(&community_id, &user_id, &tx).await?; let event = Event::CommunityDeleted { community_id }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Users(member_ids), event)); } for community in community::communities_of(&user_id, &tx).await? { - let members = user_community::members(&community.id, &tx).await?; + let member_ids = user_community::member_ids(&community.id, &tx).await?; if community.kind.is_direct() { community::delete(&community.id, &user_id, &tx).await?; } let event = Event::UserDeleted { user_id: user_id.clone(), }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Users(member_ids), event)); } - broadcasts.extend(leave_user_voice(voice, share, &user_id, &tx).await?); + broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?); let deleted = user::delete(&user_id, &tx).await?; tx.commit().await?; - if me.id == user_id { - set_state(state, State::Anonymous); - } else { - presence.disconnect(&user_id, Close::Revoked); + if me.id != user_id { + hub.kick_user(&user_id, Close::Revoked); } (Response::User(deleted), broadcasts) } Request::CreateCommunity { name } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let limit = server_settings::read(&conn).await?.max_communities_per_user; let owned = user_community::owned_groups(&me.id, &conn).await?; ensure_with( @@ -456,7 +420,7 @@ async fn dispatch( (Response::Community(community), Vec::new()) } Request::ReadCommunity { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Community(community::read(&community_id, &me.id, &conn).await?), @@ -464,7 +428,7 @@ async fn dispatch( ) } Request::UpdateCommunity { community_id, name } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; allowed(&me, &community_id, &conn, permission::can_rename_community).await?; let updated = community::update(&community_id, &name, &me.id, &conn).await?; @@ -472,18 +436,17 @@ async fn dispatch( name: updated.name.clone(), }; log::record(&community_id, Some(&me.id), None, &action, &conn).await?; - let members = user_community::members(&community_id, &conn).await?; let event = Event::CommunityUpdated(updated.clone()); ( Response::Community(updated), - vec![broadcast(event, &members)], + vec![Broadcast::new(To::Community(community_id), event)], ) } Request::UpdateCommunityAvatar { community_id, image, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; allowed(&me, &community_id, &conn, permission::can_rename_community).await?; if let Some(bytes) = &image { @@ -497,19 +460,18 @@ async fn dispatch( LogAction::AvatarRemoved }; log::record(&community_id, Some(&me.id), None, &action, &conn).await?; - let members = user_community::members(&community_id, &conn).await?; let event = Event::CommunityUpdated(updated.clone()); ( Response::Community(updated), - vec![broadcast(event, &members)], + vec![Broadcast::new(To::Community(community_id), event)], ) } Request::DeleteCommunity { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; allowed(&me, &community_id, &conn, permission::can_delete_community).await?; let tx = conn.transaction().await?; - let members = user_community::members(&community_id, &tx).await?; + let member_ids = user_community::member_ids(&community_id, &tx).await?; let owned = user_community::rank(&me.id, &community_id, &tx).await? == Some(Rank::Owner); let deleted = community::delete(&community_id, &me.id, &tx).await?; @@ -524,43 +486,44 @@ async fn dispatch( .await?; } tx.commit().await?; - let mut broadcasts = voice_closed(voice, share, &community_id, &conn).await?; + let mut broadcasts = voice_closed(rooms, &community_id, &conn).await?; let event = Event::CommunityDeleted { community_id: deleted.id.clone(), }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Users(member_ids), event)); (Response::Community(deleted), broadcasts) } Request::LeaveCommunity { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; allowed(&me, &community_id, &conn, permission::can_leave).await?; let tx = conn.transaction().await?; user_community::leave(&me.id, &community_id, &tx).await?; log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?; - let members = user_community::members(&community_id, &tx).await?; - if members.is_empty() { + if user_community::member_ids(&community_id, &tx) + .await? + .is_empty() + { community::delete(&community_id, &me.id, &tx).await?; } tx.commit().await?; - let mut broadcasts = - leave_room_voice(voice, share, &community_id, &me.id, &conn).await?; + let mut broadcasts = leave_room_voice(rooms, &community_id, &me.id, &conn).await?; let event = Event::MemberLeft { - community_id, + community_id: community_id.clone(), user_id: me.id, }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Community(community_id), event)); (Response::Done, broadcasts) } Request::Communities => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ( Response::Communities(community::communities_of(&me.id, &conn).await?), Vec::new(), ) } Request::Members { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Members(user_community::members(&community_id, &conn).await?), @@ -572,7 +535,7 @@ async fn dispatch( user_id, reason, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; remove_member( &me, Removal { @@ -581,8 +544,7 @@ async fn dispatch( reason, sanction: Sanction::Kick, }, - voice, - share, + rooms, &mut conn, ) .await? @@ -592,7 +554,7 @@ async fn dispatch( user_id, reason, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; remove_member( &me, Removal { @@ -601,8 +563,7 @@ async fn dispatch( reason, sanction: Sanction::Ban, }, - voice, - share, + rooms, &mut conn, ) .await? @@ -611,7 +572,7 @@ async fn dispatch( community_id, user_id, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_unban).await?; user_community::unban(&user_id, &community_id, &conn).await?; log::record( @@ -625,7 +586,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::Bans { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_unban).await?; ( Response::Bans(user_community::bans(&community_id, &conn).await?), @@ -637,7 +598,7 @@ async fn dispatch( user_id, rank, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_set_rank( @@ -654,13 +615,15 @@ async fn dispatch( &conn, ) .await?; - let members = user_community::members(&community_id, &conn).await?; let event = Event::RankChanged { - community_id, + community_id: community_id.clone(), user_id, rank, }; - (Response::Done, vec![broadcast(event, &members)]) + ( + Response::Done, + vec![Broadcast::new(To::Community(community_id), event)], + ) } Request::CreateMessage { community_id, @@ -668,7 +631,7 @@ async fn dispatch( attachments, reply_to, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let settings = server_settings::read(&conn).await?; limit_messages(&me, rate_limit, &settings)?; validate_new_message( @@ -689,8 +652,7 @@ async fn dispatch( .await?; stats::mark_active(&me.id, &tx).await?; tx.commit().await?; - let broadcast = - message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?; + let broadcast = message_event(&created, Event::MessageCreated); (Response::Message(created), vec![broadcast]) } Request::ForwardMessages { @@ -698,7 +660,7 @@ async fn dispatch( community_id, snippet, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?; validate_forward(message_ids.len())?; ensure(permission::can_post( @@ -721,16 +683,14 @@ async fn dispatch( let created = message::forward(&me, &community_id, &sources, mode, directory, &tx).await?; tx.commit().await?; - let members = user_community::members(&community_id, &conn).await?; - let mut broadcasts = Vec::new(); - for message in &created { - let event = Event::MessageCreated(message.clone()); - broadcasts.push(broadcast_with(event, &members, &me.id)); - } + let broadcasts = created + .iter() + .map(|message| message_event(message, Event::MessageCreated)) + .collect(); (Response::Messages(created), broadcasts) } Request::UpdateMessage { message_id, body } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let existing = message::read(&message_id, &conn).await?; allowed(&me, &existing.community_id, &conn, permission::can_post).await?; ensure(existing.user_id == me.id)?; @@ -740,8 +700,7 @@ async fn dispatch( server_settings::read(&conn).await?.max_message_length as usize, )?; let updated = message::update(&message_id, &body, &conn).await?; - let broadcast = - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + let broadcast = message_event(&updated, Event::MessageUpdated); (Response::Message(updated), vec![broadcast]) } Request::CreatePoll { @@ -750,7 +709,7 @@ async fn dispatch( options, multiple, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let settings = server_settings::read(&conn).await?; limit_messages(&me, rate_limit, &settings)?; validate_poll(&question, &options)?; @@ -761,15 +720,14 @@ async fn dispatch( .await?; stats::mark_active(&me.id, &tx).await?; tx.commit().await?; - let broadcast = - message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?; + let broadcast = message_event(&created, Event::MessageCreated); (Response::Message(created), vec![broadcast]) } Request::Vote { message_id, positions, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_read( actor_rank(&me, &existing.community_id, &conn).await?, @@ -777,36 +735,33 @@ async fn dispatch( let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?; validate_vote(poll, &positions)?; let updated = message::vote(&message_id, &me.id, &positions, &conn).await?; - let broadcast = - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + let broadcast = message_event(&updated, Event::MessageUpdated); (Response::Done, vec![broadcast]) } Request::ClosePoll { message_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_close_poll( actor_rank(&me, &existing.community_id, &conn).await?, existing.user_id == me.id, ))?; let updated = message::close_poll(&message_id, &conn).await?; - let broadcast = - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + let broadcast = message_event(&updated, Event::MessageUpdated); (Response::Done, vec![broadcast]) } Request::React { message_id, emoji } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; validate_reaction(&emoji)?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_read( actor_rank(&me, &existing.community_id, &conn).await?, ))?; let updated = message::react(&message_id, &me.id, &emoji, &conn).await?; - let broadcast = - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + let broadcast = message_event(&updated, Event::MessageUpdated); (Response::Done, vec![broadcast]) } Request::Pin { message_id, pinned } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let existing = message::read(&message_id, &conn).await?; let direct = community::is_direct(&existing.community_id, &conn).await?; ensure(permission::can_pin( @@ -814,12 +769,11 @@ async fn dispatch( direct, ))?; let updated = message::pin(&message_id, pinned, &conn).await?; - let broadcast = - message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + let broadcast = message_event(&updated, Event::MessageUpdated); (Response::Done, vec![broadcast]) } Request::Unreads => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ( Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?), Vec::new(), @@ -829,14 +783,14 @@ async fn dispatch( community_id, message_id, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure(!is_outsider(&me.id, &community_id, &conn).await?)?; message::ensure_in_community(&message_id, &community_id, &conn).await?; user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?; (Response::Done, Vec::new()) } Request::Pins { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Messages(message::pinned(&community_id, &conn).await?), @@ -844,7 +798,7 @@ async fn dispatch( ) } Request::DeleteMessage { message_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let existing = message::read(&message_id, &conn).await?; let author = user::read(&existing.user_id, &conn).await?; ensure(permission::can_delete_message( @@ -874,33 +828,26 @@ async fn dispatch( ) .await?; } - let broadcast = - message_broadcast(&deleted, Event::MessageDeleted, &me.id, &conn).await?; + let event = Event::MessagesDeleted { + community_id: deleted.community_id.clone(), + ids: vec![deleted.id.clone()], + }; + let broadcast = Broadcast::new(To::Community(deleted.community_id.clone()), event); (Response::Message(deleted), vec![broadcast]) } - Request::ReadMessages { - community_id, - before, - } => { - let me = authenticated(state, &conn).await?; + Request::WatchCommunity { community_id } => { + let me = authenticated(client, &conn).await?; + let Some(community_id) = community_id else { + client.watch(None); + return Ok((Response::Done, Vec::new())); + }; allowed(&me, &community_id, &conn, permission::can_read).await?; let outsider = is_outsider(&me.id, &community_id, &conn).await?; - if before.is_none() - && let Some(connection) = connection - { - visits.watch( - connection.stable_id(), - outsider.then_some(community_id.as_str()), - ); - } - let visit = before.is_none() - && permission::is_builder(me.role) + client.watch(outsider.then_some(community_id.as_str())); + let visit = permission::is_builder(me.role) && outsider && user::is_ghost(&me.id, &conn).await?; - if visit - && connection - .is_some_and(|connection| visits.first(connection.stable_id(), &community_id)) - { + if visit && client.first_visit(&community_id) { let community = community::label(&community_id, &conn).await?; admin_log::record( Some(&me.id), @@ -911,84 +858,85 @@ async fn dispatch( ) .await?; } + (Response::Done, Vec::new()) + } + Request::ReadMessages { + community_id, + before, + } => { + let me = authenticated(client, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; let messages = message::read_page(&community_id, before.as_deref(), &conn).await?; (Response::Messages(messages), Vec::new()) } Request::JoinVoice { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_join_voice).await?; ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?; ensure( permission::is_builder(me.role) || community::voice_enabled(&community_id, &conn).await?, )?; - let Some(connection) = connection else { - return Err(CommonError::Server.into()); - }; - let members = user_community::members(&community_id, &conn).await?; let muted = user::voice_muted(&me.id, &conn).await?; let outsider = is_outsider(&me.id, &community_id, &conn).await?; let ghost = outsider || user::is_ghost(&me.id, &conn).await?; let starts_call = !ghost && community::is_direct(&community_id, &conn).await? - && voice.participants(&community_id).is_empty(); - let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost); - let mut broadcasts = match joined { - Some(previous) => voice_left(share, previous, &conn).await?, + && rooms.participants(&community_id).is_empty(); + let joined = rooms.join(client, &community_id, muted, ghost)?; + let mut broadcasts = match joined.departure { + Some(departure) => departed(departure, &conn).await?, None => Vec::new(), }; if starts_call { let created = message::create_call_log(&community_id, &me.id, CallLog::Started, &conn) .await?; - broadcasts.push(broadcast(Event::MessageCreated(created), &members)); + broadcasts.push(message_event(&created, Event::MessageCreated)); } - if !ghost { - broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members)); + if !ghost && !joined.transferred { + broadcasts.extend(voice_joined(&community_id, &me.id, muted)); } ( - Response::Voice(voice.participants(&community_id)), + Response::Voice(rooms.participants(&community_id)), broadcasts, ) } Request::Typing { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; let broadcasts = if user::is_ghost(&me.id, &conn).await? { Vec::new() } else { - let members: Vec = user_community::members(&community_id, &conn) + let others: Vec = user_community::member_ids(&community_id, &conn) .await? .into_iter() - .filter(|member| member.user.id != me.id) + .filter(|user_id| *user_id != me.id) .collect(); let event = Event::Typing { community_id, user_id: me.id.clone(), }; - vec![broadcast(event, &members)] + vec![Broadcast::new(To::Users(others), event)] }; (Response::Done, broadcasts) } Request::LeaveVoice => { - authenticated(state, &conn).await?; - ( - Response::Done, - leave_connection_voice(voice, share, connection, &conn).await?, - ) + authenticated(client, &conn).await?; + let broadcasts = match rooms.leave(client.id) { + Some(departure) => departed(departure, &conn).await?, + None => Vec::new(), + }; + (Response::Done, broadcasts) } Request::StartShare { kind, source } => { - let me = authenticated(state, &conn).await?; - let Some(community_id) = voice.room_of(&me.id) else { + let me = authenticated(client, &conn).await?; + let Some(community_id) = rooms.room_of_conn(client.id) else { return Err(CommonError::NotFound.into()); }; allowed(&me, &community_id, &conn, permission::can_share).await?; ensure(!source.encode.is_empty())?; ensure(!user::is_ghost(&me.id, &conn).await?)?; - let Some(connection) = connection else { - return Err(CommonError::Server.into()); - }; - let members = user_community::members(&community_id, &conn).await?; let event = Event::ShareStarted { community_id: community_id.clone(), share: Share { @@ -997,22 +945,27 @@ async fn dispatch( source: source.clone(), }, }; - let mut broadcasts = vec![broadcast(event, &members)]; - broadcasts.extend(share.start(&community_id, &me.id, kind, connection.clone(), source)); + let mut broadcasts = vec![Broadcast::new(To::Community(community_id.clone()), event)]; + broadcasts.extend( + rooms + .start_share(client.id, kind, source) + .ok_or(CommonError::NotFound)?, + ); (Response::Done, broadcasts) } Request::StopShare { kind } => { - let me = authenticated(state, &conn).await?; - ( - Response::Done, - share_stopped(share, &me.id, kind, &conn).await?, - ) + let me = authenticated(client, &conn).await?; + let broadcasts = match rooms.stop_share(client.id, kind) { + Some(community_id) => vec![share_ended(&community_id, &me.id, kind)], + None => Vec::new(), + }; + (Response::Done, broadcasts) } Request::Shares { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; - (Response::Shares(share.list(&community_id)), Vec::new()) + (Response::Shares(rooms.shares(&community_id)), Vec::new()) } Request::WatchShare { user_id, @@ -1020,56 +973,50 @@ async fn dispatch( quality, decode, } => { - let me = authenticated(state, &conn).await?; - let Some(connection) = connection else { - return Err(CommonError::Server.into()); - }; - let room = voice.room_of(&me.id); - ensure(room.is_some() && room == voice.room_of(&user_id))?; - let broadcasts = share - .watch(&user_id, kind, &me.id, connection.clone(), quality, &decode) + authenticated(client, &conn).await?; + let broadcasts = rooms + .watch(client.id, &user_id, kind, quality, &decode) .ok_or(CommonError::NotFound)?; (Response::Done, broadcasts) } Request::UnwatchShare { user_id, kind } => { - let me = authenticated(state, &conn).await?; + authenticated(client, &conn).await?; - (Response::Done, share.unwatch(&user_id, kind, &me.id)) + (Response::Done, rooms.unwatch(client.id, &user_id, kind)) } Request::RequestKeyframe { user_id, kind } => { - let me = authenticated(state, &conn).await?; - let keyframe = share - .keyframe(&user_id, kind, &me.id) + authenticated(client, &conn).await?; + let keyframe = rooms + .keyframe(client.id, &user_id, kind) .ok_or(CommonError::NotFound)?; (Response::Done, vec![keyframe]) } Request::DeclineCall { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure(community::is_direct(&community_id, &conn).await?)?; allowed(&me, &community_id, &conn, permission::can_read).await?; - let participants = voice.participants(&community_id); + let participants = rooms.participants(&community_id); ensure(!participants.is_empty() && !participants.contains(&me.id))?; - voice.decline(&community_id); + rooms.decline(&community_id); let created = message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?; - let members = user_community::members(&community_id, &conn).await?; ( Response::Done, - vec![broadcast(Event::MessageCreated(created), &members)], + vec![message_event(&created, Event::MessageCreated)], ) } Request::VoiceParticipants { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; ( - Response::Voice(voice.participants(&community_id)), + Response::Voice(rooms.participants(&community_id)), Vec::new(), ) } Request::FindUser { username } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let found = user::by_username(&username, &conn) .await? .filter(|found| found.id != me.id) @@ -1077,16 +1024,16 @@ async fn dispatch( (Response::User(found), Vec::new()) } Request::OpenDirect { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; match direct::open(&me.id, &user_id, &mut conn).await? { direct::Opening::Created(community) => { let peer_view = community::read(&community.id, &user_id, &conn).await?; ( Response::Community(community), - vec![Broadcast { - event: Event::CommunityAdded(peer_view), - user_ids: vec![user_id], - }], + vec![Broadcast::new( + To::User(user_id), + Event::CommunityAdded(peer_view), + )], ) } direct::Opening::Existing(community) => { @@ -1095,33 +1042,33 @@ async fn dispatch( } } Request::OpenNotes => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ( Response::Community(notes::open(&me.id, &mut conn).await?), Vec::new(), ) } Request::Friends => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ( Response::Friends(friend::state(&me.id, &conn).await?), Vec::new(), ) } Request::AddFriend { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; friend::add(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) } Request::AcceptFriend { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; friend::accept(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) } Request::RemoveFriend { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; friend::remove(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) @@ -1130,7 +1077,7 @@ async fn dispatch( community_id, user_id, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; let target = user::read(&user_id, &conn).await?; @@ -1158,14 +1105,14 @@ async fn dispatch( (Response::Done, vec![broadcast]) } Request::Invitations => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ( Response::Invitations(invitation::of(&me.id, &conn).await?), Vec::new(), ) } Request::AcceptInvitation { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let tx = conn.transaction().await?; invitation::take(&community_id, &me.id, &tx).await?; let banned = user_community::is_banned(&me.id, &community_id, &tx).await?; @@ -1173,21 +1120,20 @@ async fn dispatch( user_community::join(&me.id, &community_id, Rank::Member, &tx).await?; log::record(&community_id, Some(&me.id), None, &LogAction::Joined, &tx).await?; let community = community::read(&community_id, &me.id, &tx).await?; - let members = user_community::members(&community_id, &tx).await?; tx.commit().await?; let event = Event::MemberJoined { - community_id, + community_id: community_id.clone(), member: Member { user: me.clone(), rank: Rank::Member, }, }; - let mut broadcasts = vec![broadcast(event, &members)]; + let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)]; broadcasts.push(invitations_updated(&me.id, &conn).await?); (Response::Community(community), broadcasts) } Request::DeclineInvitation { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; invitation::take(&community_id, &me.id, &conn).await?; ( Response::Done, @@ -1195,7 +1141,7 @@ async fn dispatch( ) } Request::Logs { community_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read_logs).await?; ( Response::Logs(log::list(&community_id, &conn).await?), @@ -1203,7 +1149,7 @@ async fn dispatch( ) } Request::AllCommunities => { - builder(state, &conn).await?; + builder(client, &conn).await?; let mut summaries = Vec::new(); for community in community::groups(&conn).await? { let members = user_community::members(&community.id, &conn).await?; @@ -1223,7 +1169,7 @@ async fn dispatch( community_id, user_id, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure_editable(&community_id, &conn).await?; allowed( &me, @@ -1281,18 +1227,17 @@ async fn dispatch( user_id: changed_id, rank, }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Community(community_id.clone()), event)); } (Response::Done, broadcasts) } Request::TimeoutUser { user_id, minutes } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); user::set_timeout(&user_id, until, &conn).await?; if until.is_some() { - authentication::revoke_sessions(&user_id, &conn).await?; - presence.disconnect(&user_id, Close::Revoked); + authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; } admin_log::record( Some(&me.id), @@ -1309,7 +1254,7 @@ async fn dispatch( reason, scope, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let target = managed(&me, &user_id, &conn).await?; validate_reason(reason.as_deref())?; let tx = conn.transaction().await?; @@ -1338,44 +1283,44 @@ async fn dispatch( ) .await?; tx.commit().await?; - presence.disconnect(&user_id, Close::Banned); + hub.kick_user(&user_id, Close::Banned); (Response::Done, Vec::new()) } Request::ServerBans => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( Response::ServerBans(server_ban::list(&conn).await?), Vec::new(), ) } Request::RemoveServerBan { id } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; server_ban::remove(&id, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?; (Response::Done, Vec::new()) } Request::CreateInviteCode { uses, hours } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure(permission::is_builder(me.role) && uses > 0)?; let code = invite::create(uses, hours, &me, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?; (Response::InviteCode(code), Vec::new()) } Request::InviteCodes => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( Response::InviteCodes(invite::list(&conn).await?), Vec::new(), ) } Request::DeleteInviteCode { code } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; invite::delete(&code, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?; (Response::Done, Vec::new()) } Request::ReportMessage { message_id, reason } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; let message = message::read(&message_id, &conn).await?; let actor = actor_rank(&me, &message.community_id, &conn).await?; ensure(permission::can_read(actor) && me.id != message.user_id)?; @@ -1394,10 +1339,10 @@ async fn dispatch( &conn, ) .await?; - (Response::Done, vec![report_created(&conn).await?]) + (Response::Done, vec![report_created()]) } Request::ReportUser { user_id, reason } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; user::read(&user_id, &conn).await?; ensure(me.id != user_id)?; validate_reason(Some(&reason))?; @@ -1406,17 +1351,17 @@ async fn dispatch( CommonError::Taken, )?; report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?; - (Response::Done, vec![report_created(&conn).await?]) + (Response::Done, vec![report_created()]) } Request::Reports { status } => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( Response::Reports(report::list(status, &conn).await?), Vec::new(), ) } Request::HandleReport { report_id, status } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?; let target = report::handle(&report_id, status, &me.id, &conn).await?; admin_log::record( @@ -1436,7 +1381,7 @@ async fn dispatch( after_ms, before_ms, } => { - builder(state, &conn).await?; + builder(client, &conn).await?; let hits = message::search( text.as_deref(), user_id.as_deref(), @@ -1449,31 +1394,36 @@ async fn dispatch( (Response::MessageHits(hits), Vec::new()) } Request::SearchCommunity { community_id, text } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_read).await?; let hits = message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?; (Response::MessageHits(hits), Vec::new()) } Request::PurgeUser { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; let tx = conn.transaction().await?; let upload_ids = attachment::uploads_of(&user_id, &tx).await?; let message_ids = message::ids_of_user(&user_id, &tx).await?; - let mut members = BTreeMap::new(); - let mut broadcasts = Vec::new(); + let mut deleted: BTreeMap> = BTreeMap::new(); for message_id in &message_ids { - let deleted = message::delete(message_id, &tx).await?; - if !members.contains_key(&deleted.community_id) { - let community_members = - user_community::members(&deleted.community_id, &tx).await?; - members.insert(deleted.community_id.clone(), community_members); - } - let community_members = &members[&deleted.community_id]; - let event = Event::MessageDeleted(deleted); - broadcasts.push(broadcast(event, community_members)); + let message = message::delete(message_id, &tx).await?; + deleted + .entry(message.community_id) + .or_default() + .push(message.id); } + let broadcasts = deleted + .into_iter() + .map(|(community_id, ids)| { + let event = Event::MessagesDeleted { + community_id: community_id.clone(), + ids, + }; + Broadcast::new(To::Community(community_id), event) + }) + .collect(); attachment::delete_uploads(&user_id, &tx).await?; admin_log::record( Some(&me.id), @@ -1493,7 +1443,7 @@ async fn dispatch( user_id, community_id, } => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( Response::AttachmentInfos( attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?, @@ -1502,7 +1452,7 @@ async fn dispatch( ) } Request::DeleteAttachment { attachment_id } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; let stored = attachment::read(&attachment_id, &conn).await?; let community = community::label(&stored.community_id, &conn).await?; let tx = conn.transaction().await?; @@ -1518,20 +1468,19 @@ async fn dispatch( let mut broadcasts = Vec::new(); if let Some(message_id) = &stored.message_id { let updated = message::read(message_id, &tx).await?; - let members = user_community::members(&updated.community_id, &tx).await?; - broadcasts = vec![broadcast(Event::MessageUpdated(updated), &members)]; + broadcasts = vec![message_event(&updated, Event::MessageUpdated)]; } tx.commit().await?; attachment::remove_files(&[attachment_id], directory); (Response::Done, broadcasts) } Request::StorageUsage => { - builder(state, &conn).await?; + builder(client, &conn).await?; let (users, communities) = attachment::usage(&conn).await?; (Response::StorageUsage { users, communities }, Vec::new()) } Request::CreateBackup => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; let backup = backup::create(&conn, backups).await?; let action = AdminAction::BackupCreated { name: backup.name.clone(), @@ -1540,27 +1489,27 @@ async fn dispatch( (Response::Backup(backup), Vec::new()) } Request::Backups => { - builder(state, &conn).await?; + builder(client, &conn).await?; (Response::Backups(backup::list(backups)?), Vec::new()) } Request::DeleteBackup { name } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; backup::delete(&name, backups)?; let action = AdminAction::BackupDeleted { name }; admin_log::record(Some(&me.id), None, None, &action, &conn).await?; (Response::Done, Vec::new()) } Request::VoiceRooms => { - builder(state, &conn).await?; + builder(client, &conn).await?; ( - Response::VoiceRooms(voice_rooms(voice, &conn).await?), + Response::VoiceRooms(voice_rooms(rooms, &conn).await?), Vec::new(), ) } Request::KickFromVoice { user_id } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; - let broadcasts = leave_user_voice(voice, share, &user_id, &conn).await?; + let broadcasts = leave_user_voice(rooms, &user_id, &conn).await?; if !broadcasts.is_empty() { admin_log::record( Some(&me.id), @@ -1574,7 +1523,7 @@ async fn dispatch( (Response::Done, broadcasts) } Request::ServerMute { user_id, muted } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; managed(&me, &user_id, &conn).await?; user::set_voice_muted(&user_id, muted, &conn).await?; admin_log::record( @@ -1585,28 +1534,15 @@ async fn dispatch( &conn, ) .await?; - let mut user_ids = BTreeSet::from([user_id.clone()]); - if let Some(community_id) = voice.set_muted(&user_id, muted) - && !user::is_ghost(&user_id, &conn).await? - { - for member in user_community::members(&community_id, &conn).await? { - user_ids.insert(member.user.id); - } - } - let event = Event::VoiceMuted { user_id, muted }; - ( - Response::Done, - vec![Broadcast { - event, - user_ids: user_ids.into_iter().collect(), - }], - ) + let community_id = rooms.set_muted(&user_id, muted); + let broadcast = voice_muted(community_id, &user_id, muted, &conn).await?; + (Response::Done, vec![broadcast]) } Request::SetCommunityVoice { community_id, enabled, } => { - let me = authenticated(state, &conn).await?; + let me = authenticated(client, &conn).await?; allowed(&me, &community_id, &conn, permission::can_manage_voice).await?; let tx = conn.transaction().await?; community::set_voice_enabled(&community_id, enabled, &tx).await?; @@ -1621,19 +1557,18 @@ async fn dispatch( ) .await?; } - let members = user_community::members(&community_id, &tx).await?; tx.commit().await?; let mut broadcasts = Vec::new(); if !enabled { - broadcasts.extend(voice_silenced(voice, share, &community_id, &conn).await?); + broadcasts.extend(voice_silenced(rooms, &community_id, &conn).await?); } let event = Event::CommunityUpdated(updated.clone()); - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Community(community_id), event)); (Response::Community(updated), broadcasts) } Request::SetGhost { enabled } => { - let me = builder(state, &conn).await?; + let me = builder(client, &conn).await?; user::set_ghost(&me.id, enabled, &conn).await?; let action = if enabled { AdminAction::GhostEnabled @@ -1642,38 +1577,29 @@ async fn dispatch( }; admin_log::record(Some(&me.id), None, None, &action, &conn).await?; let mut broadcasts = Vec::new(); - let outsider = match voice.room_of(&me.id) { + let outsider = match rooms.room_of(&me.id) { Some(community_id) => is_outsider(&me.id, &community_id, &conn).await?, None => false, }; - if !outsider - && let Some(Left { - community_id, - ghost_seconds: seconds, - call, - .. - }) = voice.set_ghost(&me.id, enabled) - { - let members = user_community::members(&community_id, &conn).await?; + if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) { + let community_id = departure.community_id.clone(); if enabled { - broadcasts.extend(share_left(share, &me.id, &conn).await?); - broadcasts - .extend(call_ended(&community_id, &me.id, call, &members, &conn).await?); - broadcasts.push(Broadcast { - event: Event::VoiceLeft { - community_id, - user_id: me.id.clone(), - }, - user_ids: members - .iter() - .map(|member| member.user.id.clone()) - .filter(|user_id| *user_id != me.id) - .collect(), - }); + broadcasts.extend(shares_ended(&mut departure)); + broadcasts.extend( + call_ended(&community_id, &me.id, departure.call_log, &conn).await?, + ); + let event = Event::VoiceLeft { + community_id: community_id.clone(), + user_id: me.id.clone(), + }; + broadcasts.push(Broadcast::new( + To::CommunityExcept(community_id, me.id.clone()), + event, + )); } else { let muted = user::voice_muted(&me.id, &conn).await?; - broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members)); - if let Some(seconds) = seconds { + broadcasts.extend(voice_joined(&community_id, &me.id, muted)); + if let Some(seconds) = departure.ghost_seconds { record_ghost_voice(&me.id, &community_id, seconds, &conn).await?; } } @@ -1685,9 +1611,9 @@ async fn dispatch( Ok(outcome) } -async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result, ServerError> { +async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result, ServerError> { let mut rooms = Vec::new(); - for (community_id, user_ids, ghosts) in voice.rooms() { + for (community_id, user_ids, ghosts) in occupied.list() { let community = community::label(&community_id, conn).await?; let mut users = Vec::new(); let mut muted = Vec::new(); @@ -1711,11 +1637,8 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result, Ok(rooms) } -async fn report_created(conn: &Connection) -> Result { - Ok(Broadcast { - event: Event::ReportCreated, - user_ids: user::builder_ids(conn).await?, - }) +fn report_created() -> Broadcast { + Broadcast::new(To::Builders, Event::ReportCreated) } fn ip_of(connection: Option<&quinn::Connection>) -> Option { @@ -1744,7 +1667,7 @@ fn limit_messages( Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?) } -async fn record_address( +pub(crate) async fn record_address( user: &User, connection: Option<&quinn::Connection>, conn: &Connection, @@ -1766,8 +1689,7 @@ struct Removal { async fn remove_member( me: &User, removal: Removal, - voice: &Voice, - share: &Shares, + rooms: &Rooms, conn: &mut Connection, ) -> Result { let Removal { @@ -1785,7 +1707,6 @@ async fn remove_member( ))?; let community = community::read(&community_id, &me.id, conn).await?; let tx = conn.transaction().await?; - let members = user_community::members(&community_id, &tx).await?; user_community::leave(&user_id, &community_id, &tx).await?; let action = match sanction { Sanction::Ban => { @@ -1800,52 +1721,36 @@ async fn remove_member( }; log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; tx.commit().await?; - let mut broadcasts = leave_room_voice(voice, share, &community_id, &user_id, conn).await?; - broadcasts.push(Broadcast { - event: Event::Removed { - community_id: community_id.clone(), - community_name: community.name, - sanction, - reason, - }, - user_ids: vec![user_id.clone()], - }); + let mut broadcasts = leave_room_voice(rooms, &community_id, &user_id, conn).await?; + let removed = Event::Removed { + community_id: community_id.clone(), + community_name: community.name, + sanction, + reason, + }; + broadcasts.push(Broadcast::new(To::User(user_id.clone()), removed)); let event = Event::MemberLeft { - community_id, + community_id: community_id.clone(), user_id, }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Community(community_id), event)); Ok((Response::Done, broadcasts)) } -async fn related_user_ids(user_id: &str, conn: &Connection) -> Result, ServerError> { - let mut user_ids = BTreeSet::from([user_id.to_string()]); - for community in community::communities_of(user_id, conn).await? { - for member in user_community::members(&community.id, conn).await? { - user_ids.insert(member.user.id); - } - } - for friend in friend::state(user_id, conn).await?.friends { - user_ids.insert(friend.id); - } - - Ok(user_ids.into_iter().collect()) -} - -async fn user_updated(user: &User, conn: &Connection) -> Result, ServerError> { - Ok(vec![Broadcast { - event: Event::UserUpdated(user.clone()), - user_ids: related_user_ids(&user.id, conn).await?, - }]) +fn user_updated(user: &User) -> Vec { + vec![Broadcast::new( + To::Related(user.id.clone()), + Event::UserUpdated(user.clone()), + )] } async fn effective_presence( - presence: &network::Presence, + hub: &Hub, user_id: &str, conn: &Connection, ) -> Result { - if !presence.is_online(user_id) { + if !hub.is_online(user_id) { return Ok(Presence::Offline); } @@ -1853,19 +1758,21 @@ async fn effective_presence( } pub async fn presence_changed( - presence: &network::Presence, + hub: &Hub, user_id: &str, conn: &Connection, ) -> Result, ServerError> { - let presence = effective_presence(presence, user_id, conn).await?; + let presence = effective_presence(hub, user_id, conn).await?; - Ok(vec![Broadcast { - event: Event::PresenceChanged { - user_id: user_id.to_string(), - presence, - }, - user_ids: related_user_ids(user_id, conn).await?, - }]) + let event = Event::PresenceChanged { + user_id: user_id.to_string(), + presence, + }; + + Ok(vec![Broadcast::new( + To::Related(user_id.to_string()), + event, + )]) } async fn friends_updated( @@ -1874,132 +1781,110 @@ async fn friends_updated( ) -> Result, ServerError> { let mut broadcasts = Vec::new(); for user_id in user_ids { - broadcasts.push(Broadcast { - event: Event::FriendsUpdated(friend::state(user_id, conn).await?), - user_ids: vec![user_id.to_string()], - }); + let event = Event::FriendsUpdated(friend::state(user_id, conn).await?); + broadcasts.push(Broadcast::new(To::User(user_id.to_string()), event)); } Ok(broadcasts) } async fn invitations_updated(user_id: &str, conn: &Connection) -> Result { - Ok(Broadcast { - event: Event::InvitationsUpdated(invitation::of(user_id, conn).await?), - user_ids: vec![user_id.to_string()], - }) + let event = Event::InvitationsUpdated(invitation::of(user_id, conn).await?); + + Ok(Broadcast::new(To::User(user_id.to_string()), event)) } async fn leave_user_voice( - voice: &Voice, - share: &Shares, + rooms: &Rooms, user_id: &str, conn: &Connection, ) -> Result, ServerError> { - match voice.leave(user_id) { - Some(left) => voice_left(share, left, conn).await, - None => Ok(Vec::new()), - } -} - -pub async fn leave_connection_voice( - voice: &Voice, - share: &Shares, - connection: Option<&quinn::Connection>, - conn: &Connection, -) -> Result, ServerError> { - match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) { - Some(left) => voice_left(share, left, conn).await, + match rooms.leave_user(user_id) { + Some(departure) => departed(departure, conn).await, None => Ok(Vec::new()), } } async fn leave_room_voice( - voice: &Voice, - share: &Shares, + rooms: &Rooms, community_id: &str, user_id: &str, conn: &Connection, ) -> Result, ServerError> { - match voice.leave_room(community_id, user_id) { - Some(left) => voice_left(share, left, conn).await, + match rooms.leave_room(community_id, user_id) { + Some(departure) => departed(departure, conn).await, None => Ok(Vec::new()), } } async fn voice_unmuted( - voice: &Voice, + rooms: &Rooms, user_id: &str, conn: &Connection, ) -> Result, ServerError> { - let Some(community_id) = voice.set_muted(user_id, false) else { + let Some(community_id) = rooms.set_muted(user_id, false) else { return Ok(Vec::new()); }; + + Ok(vec![ + voice_muted(Some(community_id), user_id, false, conn).await?, + ]) +} + +async fn voice_muted( + community_id: Option, + user_id: &str, + muted: bool, + conn: &Connection, +) -> Result { let mut user_ids = vec![user_id.to_string()]; - if !user::is_ghost(user_id, conn).await? { - user_ids.extend( - user_community::members(&community_id, conn) - .await? - .into_iter() - .map(|member| member.user.id), - ); + if let Some(community_id) = &community_id + && !user::is_ghost(user_id, conn).await? + { + user_ids.extend(user_community::member_ids(community_id, conn).await?); } + let event = Event::VoiceMuted { + community_id, + user_id: user_id.to_string(), + muted, + }; - Ok(vec![Broadcast { - event: Event::VoiceMuted { - user_id: user_id.to_string(), - muted: false, - }, - user_ids, - }]) + Ok(Broadcast::new(To::Users(user_ids), event)) } async fn voice_silenced( - voice: &Voice, - share: &Shares, + rooms: &Rooms, community_id: &str, conn: &Connection, ) -> Result, ServerError> { let mut broadcasts = Vec::new(); - for user_id in voice.room_users(community_id) { + for user_id in rooms.room_users(community_id) { if permission::is_builder(user::read(&user_id, conn).await?.role) { continue; } - if let Some(left) = voice.leave_room(community_id, &user_id) { - broadcasts.extend(voice_left(share, left, conn).await?); - } + broadcasts.extend(leave_room_voice(rooms, community_id, &user_id, conn).await?); } Ok(broadcasts) } async fn voice_closed( - voice: &Voice, - share: &Shares, + rooms: &Rooms, community_id: &str, conn: &Connection, ) -> Result, ServerError> { let mut broadcasts = Vec::new(); - for left in voice.remove_room(community_id) { - broadcasts.extend(voice_left(share, left, conn).await?); + for departure in rooms.close_room(community_id) { + broadcasts.extend(departed(departure, conn).await?); } Ok(broadcasts) } -fn call_log_of(end: CallEnd) -> Option { - match end { - CallEnd::Answered { seconds } => Some(CallLog::Ended { seconds }), - CallEnd::Unanswered => Some(CallLog::Missed), - CallEnd::Declined => None, - } -} - async fn call_ended( community_id: &str, user_id: &str, - call: Option, - members: &[Member], + call: Option, conn: &Connection, ) -> Result, ServerError> { let Some(call) = call else { @@ -2008,140 +1893,70 @@ async fn call_ended( if !community::is_direct(community_id, conn).await? { return Ok(Vec::new()); } - let Some(call) = call_log_of(call) else { - return Ok(Vec::new()); - }; let created = message::create_call_log(community_id, user_id, call, conn).await?; - Ok(vec![broadcast(Event::MessageCreated(created), members)]) + Ok(vec![message_event(&created, Event::MessageCreated)]) } -async fn voice_left( - share: &Shares, - left: Left, +pub async fn departed( + mut departure: Departure, conn: &Connection, ) -> Result, ServerError> { - let mut broadcasts = share_left(share, &left.user_id, conn).await?; - let Some(seconds) = left.ghost_seconds else { - let members = user_community::members(&left.community_id, conn).await?; - broadcasts.extend( - call_ended(&left.community_id, &left.user_id, left.call, &members, conn).await?, - ); + let mut broadcasts = shares_ended(&mut departure); + if departure.quiet { + return Ok(broadcasts); + } + let Departure { + community_id, + user_id, + ghost_seconds, + call_log, + .. + } = departure; + let Some(seconds) = ghost_seconds else { + broadcasts.extend(call_ended(&community_id, &user_id, call_log, conn).await?); let event = Event::VoiceLeft { - community_id: left.community_id, - user_id: left.user_id, + community_id: community_id.clone(), + user_id, }; - broadcasts.push(broadcast(event, &members)); + broadcasts.push(Broadcast::new(To::Community(community_id), event)); return Ok(broadcasts); }; - record_ghost_voice(&left.user_id, &left.community_id, seconds, conn).await?; + record_ghost_voice(&user_id, &community_id, seconds, conn).await?; Ok(broadcasts) } -async fn share_ended( - community_id: &str, - user_id: &str, - kind: Kind, - conn: &Connection, -) -> Result { - let members = user_community::members(community_id, conn).await?; +fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast { let event = Event::ShareStopped { community_id: community_id.to_string(), user_id: user_id.to_string(), kind, }; - Ok(broadcast(event, &members)) -} - -async fn share_stopped( - share: &Shares, - user_id: &str, - kind: Kind, - conn: &Connection, -) -> Result, ServerError> { - let Some(community_id) = share.stop(user_id, kind) else { - return Ok(Vec::new()); - }; - - Ok(vec![share_ended(&community_id, user_id, kind, conn).await?]) -} - -async fn share_left( - share: &Shares, - user_id: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut broadcasts = Vec::new(); - for (community_id, kind) in share.stop_all(user_id) { - broadcasts.push(share_ended(&community_id, user_id, kind, conn).await?); - } - broadcasts.extend(share.leave_viewer(user_id)); - - Ok(broadcasts) + Broadcast::new(To::Community(community_id.to_string()), event) } -async fn enter( - state: &Mutex, - user: User, - token: String, - voice: &Voice, - share: &Shares, - connection: Option<&quinn::Connection>, - conn: &Connection, -) -> Result { - stats::mark_active(&user.id, conn).await?; - record_address(&user, connection, conn).await?; - let broadcasts = leave_connection_voice(voice, share, connection, conn).await?; +fn shares_ended(departure: &mut Departure) -> Vec { + let mut broadcasts: Vec = departure + .shares + .iter() + .map(|kind| share_ended(&departure.community_id, &departure.user_id, *kind)) + .collect(); + broadcasts.append(&mut departure.media); - Ok(sign_in(state, user, token, broadcasts)) -} - -fn sign_in(state: &Mutex, user: User, token: String, broadcasts: Vec) -> Outcome { - set_state( - state, - State::Authenticated { - user: user.clone(), - token: token.clone(), - }, - ); - - (Response::Session { user, token }, broadcasts) -} - -fn set_state(state: &Mutex, new_state: State) { - *state.lock().unwrap() = new_state; -} - -fn session(state: &Mutex) -> Result<(User, String), ServerError> { - match state.lock().unwrap().clone() { - State::Anonymous => Err(CommonError::Unauthenticated.into()), - State::Authenticated { user, token } => Ok((user, token)), - } + broadcasts } -fn session_token(state: &Mutex) -> Result { - Ok(session(state)?.1) -} +async fn authenticated(client: &Client, conn: &Connection) -> Result { + let user_id = client.user_id().ok_or(CommonError::Unauthenticated)?; -fn cache_user(state: &Mutex, user: User) { - if let State::Authenticated { user: cached, .. } = &mut *state.lock().unwrap() { - *cached = user; - } + user::read(user_id, conn).await } -async fn authenticated(state: &Mutex, conn: &Connection) -> Result { - let (cached, _) = session(state)?; - let user = user::read(&cached.id, conn).await?; - cache_user(state, user.clone()); - - Ok(user) -} - -async fn builder(state: &Mutex, conn: &Connection) -> Result { - let user = authenticated(state, conn).await?; +async fn builder(client: &Client, conn: &Connection) -> Result { + let user = authenticated(client, conn).await?; ensure(permission::is_builder(user.role))?; Ok(user) @@ -2203,46 +2018,30 @@ async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), Se ensure(!community::is_fixed(community_id, conn).await?) } -fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Broadcast { - let mut sent = broadcast(event, members); - if !sent.user_ids.iter().any(|id| id == user_id) { - sent.user_ids.push(user_id.to_string()); - } - - sent -} - -async fn message_broadcast( - message: &Message, - event: fn(Message) -> Event, - actor_id: &str, - conn: &Connection, -) -> Result { - let members = user_community::members(&message.community_id, conn).await?; - - Ok(broadcast_with(event(message.clone()), &members, actor_id)) +fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { + Broadcast::new( + To::Community(message.community_id.clone()), + event(message.clone()), + ) } -fn joined_broadcasts( - community_id: &str, - user_id: &str, - muted: bool, - members: &[Member], -) -> Vec { - let mut broadcasts = vec![broadcast( +fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec { + let to = || To::Community(community_id.to_string()); + let mut broadcasts = vec![Broadcast::new( + to(), Event::VoiceJoined { community_id: community_id.to_string(), user_id: user_id.to_string(), }, - members, )]; if muted { - broadcasts.push(broadcast( + broadcasts.push(Broadcast::new( + to(), Event::VoiceMuted { + community_id: Some(community_id.to_string()), user_id: user_id.to_string(), muted, }, - members, )); } @@ -2268,53 +2067,38 @@ async fn record_ghost_voice( Ok(()) } -fn broadcast(event: Event, members: &[Member]) -> Broadcast { - Broadcast { - event, - user_ids: members - .iter() - .map(|member| member.user.id.clone()) - .collect(), - } -} - #[cfg(test)] mod tests { - use std::sync::Mutex; + use std::sync::Arc; use common::{error::Error as CommonError, request::Request, response::Response}; use crate::{ database::{self, DB}, + hub::{Client, Signed}, message, - network::{Services, State}, + network::Services, request::handle, test, }; - async fn send( - request: Request, - state: &Mutex, - db: &DB, - services: &Services, - ) -> Response { - send_result(request, state, db, services) + async fn send(request: Request, client: &Client, db: &DB, services: &Services) -> Response { + send_result(request, client, db, services) .await .expect("request failed") } async fn send_result( request: Request, - state: &Mutex, + client: &Client, db: &DB, services: &Services, ) -> Result { handle( request, - state, + client, db, services, - None, &test::directory(), &test::directory(), ) @@ -2322,27 +2106,33 @@ mod tests { .0 } - async fn signed_in(username: &str, db: &DB, services: &Services) -> Mutex { - let state = Mutex::new(State::Anonymous); - send( + async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc { + let guest = Client::detached(None); + let Response::Session { user, token } = send( Request::Register { username: username.to_string(), password: "password".to_string(), invite: None, }, - &state, + &guest, db, services, ) - .await; + .await + else { + panic!("register failed"); + }; - state + Client::detached(Some(Signed { + user_id: user.id, + token, + })) } async fn invite_and_accept( community_id: &str, - owner: &Mutex, - member: &Mutex, + owner: &Client, + member: &Client, username: &str, db: &DB, services: &Services, diff --git a/crates/server/src/retention.rs b/crates/server/src/retention.rs index a4db7c2..a04c16a 100644 --- a/crates/server/src/retention.rs +++ b/crates/server/src/retention.rs @@ -1,27 +1,26 @@ -use std::{ - path::{Path, PathBuf}, - time::Duration, -}; +use std::{collections::BTreeMap, path::Path, time::Duration}; -use common::time; +use common::{event::Event, time}; use tracing::{error, info}; use turso::Connection; use crate::{ - attachment, - database::{self, DB}, + attachment, database, error::ServerError, - message, server_settings, + message, + network::Shared, + publish::{Broadcast, To, publish}, + server_settings, }; const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); const BATCH_SIZE: i64 = 500; -pub async fn collect(db: DB, directory: PathBuf) { +pub(crate) async fn collect(shared: Shared) { let mut interval = tokio::time::interval(SWEEP_INTERVAL); loop { interval.tick().await; - if let Err(error) = sweep(&db, &directory).await { + if let Err(error) = sweep(&shared).await { error!("retention sweep: {error}"); } } @@ -50,7 +49,7 @@ async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result Result { let mut purged = 0; loop { @@ -61,12 +60,28 @@ async fn purge_messages( let tx = conn.transaction().await?; let mut files = Vec::new(); + let mut deleted: BTreeMap> = BTreeMap::new(); for id in &ids { files.extend(attachment::ids_of_message(id, &tx).await?); - message::delete(id, &tx).await?; + let message = message::delete(id, &tx).await?; + deleted + .entry(message.community_id) + .or_default() + .push(message.id); } tx.commit().await?; - attachment::remove_files(&files, directory); + attachment::remove_files(&files, &shared.directory); + let broadcasts = deleted + .into_iter() + .map(|(community_id, ids)| { + let event = Event::MessagesDeleted { + community_id: community_id.clone(), + ids, + }; + Broadcast::new(To::Community(community_id), event) + }) + .collect(); + publish(shared, broadcasts).await; purged += ids.len() as u64; } } @@ -91,14 +106,15 @@ async fn purge_attachments( } } -async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { - let mut conn = database::connect(db).await?; +async fn sweep(shared: &Shared) -> Result<(), ServerError> { + let directory = &shared.directory; + let mut conn = database::connect(&shared.db).await?; let settings = server_settings::read(&conn).await?; let now = time::now_ms(); let messages = match settings.message_retention_days { 0 => 0, - days => purge_messages(&cutoff(now, days), &mut conn, directory).await?, + days => purge_messages(&cutoff(now, days), &mut conn, shared).await?, }; let attachments = match settings.attachment_retention_days { 0 => 0, diff --git a/crates/server/src/rooms.rs b/crates/server/src/rooms.rs new file mode 100644 index 0000000..768acde --- /dev/null +++ b/crates/server/src/rooms.rs @@ -0,0 +1,748 @@ +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + sync::{Arc, Mutex, atomic::Ordering}, + time::Instant, +}; + +use bytes::Bytes; +use common::{ + datagram::{Datagram, Fragment, encode_relay}, + error::Error, + event::{Event, Media}, + model::CallLog, + share::{Codec, Kind, Layer, Quality, Share, Source, choose}, + time, +}; +use quinn::Connection; + +use crate::{ + hub::{Client, ConnId}, + publish::{Broadcast, To}, +}; + +#[derive(Clone, Copy)] +enum Forward { + Waiting(Layer), + Live(Layer), + Switching { live: Layer, next: Layer }, +} + +impl Forward { + fn target(self) -> Layer { + match self { + Self::Waiting(layer) | Self::Live(layer) => layer, + Self::Switching { next, .. } => next, + } + } + + fn layers(self) -> Vec { + match self { + Self::Waiting(layer) | Self::Live(layer) => vec![layer], + Self::Switching { live, next } => vec![live, next], + } + } + + fn live(self) -> Option { + match self { + Self::Waiting(_) => None, + Self::Live(layer) | Self::Switching { live: layer, .. } => Some(layer), + } + } + + fn retarget(self, next: Layer) -> Self { + match self { + Self::Waiting(_) => Self::Waiting(next), + Self::Live(live) | Self::Switching { live, .. } if live == next => Self::Live(live), + Self::Live(live) | Self::Switching { live, .. } => Self::Switching { live, next }, + } + } + + fn on_keyframe(self, layer: Layer) -> Self { + match self { + Self::Waiting(next) | Self::Switching { next, .. } if next == layer => { + Self::Live(layer) + } + _ => self, + } + } +} + +struct Viewer { + user_id: String, + connection: Connection, + quality: Quality, + decode: Vec, + forward: Forward, +} + +struct Sharing { + source: Source, + viewers: Vec, +} + +impl Sharing { + fn layers(&self) -> BTreeSet { + self.viewers + .iter() + .flat_map(|viewer| viewer.forward.layers()) + .collect() + } + + fn viewer(&self, user_id: &str) -> Option<&Viewer> { + self.viewers.iter().find(|viewer| viewer.user_id == user_id) + } +} + +fn layers_changed( + sharer: ConnId, + kind: Kind, + sharing: &Sharing, + before: BTreeSet, +) -> Option { + let after = sharing.layers(); + + (after != before).then(|| { + Broadcast::media( + sharer, + Media::Layers { + kind, + layers: after.into_iter().collect(), + }, + ) + }) +} + +struct Sharer<'a> { + conn: ConnId, + user_id: &'a str, + community_id: &'a str, + kind: Kind, +} + +fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec { + let before = sharing.layers(); + let Sharing { source, viewers } = sharing; + let mut used: Vec = Vec::new(); + let mut keyframes = Vec::new(); + let mut stopped = Vec::new(); + viewers.retain_mut(|viewer| { + let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { + stopped.push(Broadcast::new( + To::User(viewer.user_id.clone()), + Event::ShareStopped { + community_id: sharer.community_id.to_string(), + user_id: sharer.user_id.to_string(), + kind: sharer.kind, + }, + )); + return false; + }; + if !used.contains(&layer) { + used.push(layer); + } + if viewer.forward.target() != layer { + keyframes.push(Broadcast::media( + sharer.conn, + Media::Keyframe { + kind: sharer.kind, + layer, + }, + )); + } + viewer.forward = viewer.forward.retarget(layer); + + true + }); + + let mut broadcasts: Vec = layers_changed(sharer.conn, sharer.kind, sharing, before) + .into_iter() + .collect(); + broadcasts.extend(keyframes); + broadcasts.extend(stopped); + + broadcasts +} + +fn remove_viewer( + sharer: ConnId, + kind: Kind, + sharing: &mut Sharing, + viewer_id: &str, +) -> Option { + let before = sharing.layers(); + sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); + + layers_changed(sharer, kind, sharing, before) +} + +struct Seat { + user_id: String, + connection: Connection, + muted: bool, + ghost: bool, + joined_at: Instant, + shares: BTreeMap, +} + +enum Outcome { + Ringing, + Declined, + Answered, +} + +struct Room { + seats: HashMap, + started_ms: u64, + outcome: Outcome, +} + +impl Room { + fn new() -> Self { + Self { + seats: HashMap::new(), + started_ms: time::now_ms(), + outcome: Outcome::Ringing, + } + } + + fn occupied(&self) -> bool { + self.seats.values().any(|seat| !seat.ghost) + } + + fn user_ids(&self, keep: impl Fn(&Seat) -> bool) -> Vec { + self.seats + .values() + .filter(|seat| keep(seat)) + .map(|seat| seat.user_id.clone()) + .collect() + } + + fn admit(&mut self) { + if self.occupied() { + self.outcome = Outcome::Answered; + } else { + self.started_ms = time::now_ms(); + self.outcome = Outcome::Ringing; + } + } + + fn call_log(&self) -> Option { + match self.outcome { + Outcome::Answered => Some(CallLog::Ended { + seconds: time::now_ms().saturating_sub(self.started_ms) / 1000, + }), + Outcome::Declined => None, + Outcome::Ringing => Some(CallLog::Missed), + } + } + + fn drop_viewer(&mut self, user_id: &str) -> Vec { + let mut broadcasts = Vec::new(); + for (conn, seat) in &mut self.seats { + for (kind, sharing) in &mut seat.shares { + broadcasts.extend(remove_viewer(*conn, *kind, sharing, user_id)); + } + } + + broadcasts + } +} + +pub struct Departure { + pub community_id: String, + pub user_id: String, + pub ghost_seconds: Option, + pub call_log: Option, + pub shares: Vec, + pub media: Vec, + pub quiet: bool, +} + +pub struct Joined { + pub departure: Option, + pub transferred: bool, +} + +#[derive(Default)] +struct Inner { + rooms: HashMap, + seat_of: HashMap, + conn_of_user: HashMap, +} + +impl Inner { + fn seat_conn(&self, user_id: &str) -> Option { + self.conn_of_user.get(user_id).copied() + } + + fn seat_mut(&mut self, id: ConnId) -> Option<(&str, &mut Room)> { + let community_id = self.seat_of.get(&id)?; + + Some((community_id.as_str(), self.rooms.get_mut(community_id)?)) + } + + fn take(&mut self, id: ConnId, notify: bool, quiet: bool) -> Option { + let community_id = self.seat_of.remove(&id)?; + let room = self.rooms.get_mut(&community_id)?; + let seat = room.seats.remove(&id)?; + if self.conn_of_user.get(&seat.user_id) == Some(&id) { + self.conn_of_user.remove(&seat.user_id); + } + let mut media = room.drop_viewer(&seat.user_id); + let call_log = (!quiet && !seat.ghost && !room.occupied()) + .then(|| room.call_log()) + .flatten(); + if !quiet && room.seats.is_empty() { + self.rooms.remove(&community_id); + } + if notify { + media.push(Broadcast::media(id, Media::VoiceEnded)); + } + + Some(Departure { + community_id, + ghost_seconds: seat.ghost.then(|| seat.joined_at.elapsed().as_secs()), + user_id: seat.user_id, + call_log, + shares: seat.shares.keys().copied().collect(), + media, + quiet, + }) + } +} + +#[derive(Clone, Default)] +pub struct Rooms(Arc>); + +impl Rooms { + pub fn join( + &self, + client: &Client, + community_id: &str, + muted: bool, + ghost: bool, + ) -> Result { + let connection = client.conn.clone().ok_or(Error::Server)?; + let user_id = client.user_id().ok_or(Error::Unauthenticated)?; + let mut inner = self.0.lock().unwrap(); + if client.closed.load(Ordering::Acquire) { + return Err(Error::Server); + } + let mut departure = None; + let mut transferred = false; + let mut joined_at = Instant::now(); + if let Some(previous) = inner.seat_conn(user_id) { + let same_room = inner.seat_of.get(&previous).map(String::as_str) == Some(community_id); + let kept_ghost = inner + .rooms + .get(community_id) + .and_then(|room| room.seats.get(&previous)) + .map(|seat| (seat.ghost, seat.joined_at)); + transferred = same_room && kept_ghost.is_some_and(|(was, _)| was == ghost); + if let (true, Some((_, at))) = (transferred, kept_ghost) { + joined_at = at; + } + departure = inner.take(previous, previous != client.id, transferred); + } + let room = inner + .rooms + .entry(community_id.to_string()) + .or_insert_with(Room::new); + if !ghost && !transferred { + room.admit(); + } + room.seats.insert( + client.id, + Seat { + user_id: user_id.to_string(), + connection, + muted, + ghost, + joined_at, + shares: BTreeMap::new(), + }, + ); + inner.seat_of.insert(client.id, community_id.to_string()); + inner.conn_of_user.insert(user_id.to_string(), client.id); + + Ok(Joined { + departure, + transferred, + }) + } + + pub fn leave(&self, id: ConnId) -> Option { + self.0.lock().unwrap().take(id, false, false) + } + + pub fn leave_user(&self, user_id: &str) -> Option { + let mut inner = self.0.lock().unwrap(); + let id = inner.seat_conn(user_id)?; + + inner.take(id, true, false) + } + + pub fn leave_room(&self, community_id: &str, user_id: &str) -> Option { + let mut inner = self.0.lock().unwrap(); + let id = inner.seat_conn(user_id)?; + if inner.seat_of.get(&id).map(String::as_str) != Some(community_id) { + return None; + } + + inner.take(id, true, false) + } + + pub fn close_room(&self, community_id: &str) -> Vec { + let mut inner = self.0.lock().unwrap(); + let Some(room) = inner.rooms.get(community_id) else { + return Vec::new(); + }; + let ids: Vec = room.seats.keys().copied().collect(); + let mut departures: Vec = ids + .into_iter() + .filter_map(|id| inner.take(id, true, false)) + .collect(); + for departure in &mut departures { + departure.call_log = None; + } + + departures + } + + pub fn decline(&self, community_id: &str) { + if let Some(room) = self.0.lock().unwrap().rooms.get_mut(community_id) + && matches!(room.outcome, Outcome::Ringing) + { + room.outcome = Outcome::Declined; + } + } + + pub fn set_muted(&self, user_id: &str, muted: bool) -> Option { + let mut inner = self.0.lock().unwrap(); + let id = inner.seat_conn(user_id)?; + let (community_id, room) = inner.seat_mut(id)?; + let community_id = community_id.to_string(); + room.seats.get_mut(&id)?.muted = muted; + + Some(community_id) + } + + pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { + let mut inner = self.0.lock().unwrap(); + let id = inner.seat_conn(user_id)?; + let (community_id, room) = inner.seat_mut(id)?; + let community_id = community_id.to_string(); + if room.seats.get(&id)?.ghost == ghost { + return None; + } + if !ghost { + room.admit(); + } + let seat = room.seats.get_mut(&id)?; + let ghost_seconds = seat.ghost.then(|| seat.joined_at.elapsed().as_secs()); + seat.ghost = ghost; + seat.joined_at = Instant::now(); + let shares: Vec = if ghost { + std::mem::take(&mut seat.shares).into_keys().collect() + } else { + Vec::new() + }; + let media = if ghost { + room.drop_viewer(user_id) + } else { + Vec::new() + }; + let call_log = (ghost && !room.occupied()) + .then(|| room.call_log()) + .flatten(); + + Some(Departure { + community_id, + user_id: user_id.to_string(), + ghost_seconds, + call_log, + shares, + media, + quiet: false, + }) + } + + pub fn room_of(&self, user_id: &str) -> Option { + let inner = self.0.lock().unwrap(); + + inner.seat_of.get(&inner.seat_conn(user_id)?).cloned() + } + + pub fn room_of_conn(&self, id: ConnId) -> Option { + self.0.lock().unwrap().seat_of.get(&id).cloned() + } + + pub fn room_users(&self, community_id: &str) -> Vec { + self.0 + .lock() + .unwrap() + .rooms + .get(community_id) + .map(|room| room.user_ids(|_| true)) + .unwrap_or_default() + } + + pub fn participants(&self, community_id: &str) -> Vec { + self.0 + .lock() + .unwrap() + .rooms + .get(community_id) + .map(|room| room.user_ids(|seat| !seat.ghost)) + .unwrap_or_default() + } + + pub fn count(&self) -> usize { + self.0.lock().unwrap().seat_of.len() + } + + pub fn list(&self) -> Vec<(String, Vec, Vec)> { + self.0 + .lock() + .unwrap() + .rooms + .iter() + .map(|(community_id, room)| { + ( + community_id.clone(), + room.user_ids(|_| true), + room.user_ids(|seat| seat.ghost), + ) + }) + .collect() + } + + pub fn shares(&self, community_id: &str) -> Vec { + let inner = self.0.lock().unwrap(); + let Some(room) = inner.rooms.get(community_id) else { + return Vec::new(); + }; + + room.seats + .values() + .flat_map(|seat| { + seat.shares.iter().map(|(kind, sharing)| Share { + user_id: seat.user_id.clone(), + kind: *kind, + source: sharing.source.clone(), + }) + }) + .collect() + } + + pub fn start_share(&self, id: ConnId, kind: Kind, source: Source) -> Option> { + let mut inner = self.0.lock().unwrap(); + let (community_id, room) = inner.seat_mut(id)?; + let community_id = community_id.to_string(); + let seat = room.seats.get_mut(&id)?; + let user_id = seat.user_id.clone(); + let sharer = Sharer { + conn: id, + user_id: &user_id, + community_id: &community_id, + kind, + }; + if let Some(sharing) = seat.shares.get_mut(&kind) { + sharing.source = source; + return Some(reroute(&sharer, sharing)); + } + seat.shares.insert( + kind, + Sharing { + source, + viewers: Vec::new(), + }, + ); + + Some(Vec::new()) + } + + pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option { + let mut inner = self.0.lock().unwrap(); + let (community_id, room) = inner.seat_mut(id)?; + let community_id = community_id.to_string(); + room.seats.get_mut(&id)?.shares.remove(&kind)?; + + Some(community_id) + } + + pub fn watch( + &self, + id: ConnId, + sharer_id: &str, + kind: Kind, + quality: Quality, + decode: &[Codec], + ) -> Option> { + let mut inner = self.0.lock().unwrap(); + let sharer_conn = inner.seat_conn(sharer_id)?; + let (_, room) = inner.seat_mut(id)?; + let viewer_seat = room.seats.get(&id)?; + let (viewer_id, connection) = (viewer_seat.user_id.clone(), viewer_seat.connection.clone()); + let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; + let before = sharing.layers(); + let used: Vec = before.iter().copied().collect(); + let layer = choose(&sharing.source, quality, decode, &used)?; + let forward = sharing + .viewer(&viewer_id) + .map_or(Forward::Waiting(layer), |viewer| { + viewer.forward.retarget(layer) + }); + sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); + sharing.viewers.push(Viewer { + user_id: viewer_id, + connection, + quality, + decode: decode.to_vec(), + forward, + }); + let mut broadcasts: Vec = layers_changed(sharer_conn, kind, sharing, before) + .into_iter() + .collect(); + broadcasts.push(Broadcast::media( + sharer_conn, + Media::Keyframe { kind, layer }, + )); + + Some(broadcasts) + } + + pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Vec { + let mut inner = self.0.lock().unwrap(); + let Some(sharer_conn) = inner.seat_conn(sharer_id) else { + return Vec::new(); + }; + let Some((_, room)) = inner.seat_mut(id) else { + return Vec::new(); + }; + let Some(viewer_id) = room.seats.get(&id).map(|seat| seat.user_id.clone()) else { + return Vec::new(); + }; + + room.seats + .get_mut(&sharer_conn) + .and_then(|seat| seat.shares.get_mut(&kind)) + .and_then(|sharing| remove_viewer(sharer_conn, kind, sharing, &viewer_id)) + .into_iter() + .collect() + } + + pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option { + let mut inner = self.0.lock().unwrap(); + let sharer_conn = inner.seat_conn(sharer_id)?; + let (_, room) = inner.seat_mut(id)?; + let viewer_id = room.seats.get(&id)?.user_id.clone(); + let viewer = room + .seats + .get(&sharer_conn)? + .shares + .get(&kind)? + .viewer(&viewer_id)?; + + Some(Broadcast::media( + sharer_conn, + Media::Keyframe { + kind, + layer: viewer.forward.target(), + }, + )) + } + + pub fn relay(&self, from: &Client, packet: &[u8]) -> Vec { + if from.me.is_none() { + return Vec::new(); + } + let Some(datagram) = Datagram::decode(packet) else { + return Vec::new(); + }; + let mut inner = self.0.lock().unwrap(); + let Some((_, room)) = inner.seat_mut(from.id) else { + return Vec::new(); + }; + match datagram { + Datagram::Voice { sequence, .. } => relay_voice(room, from.id, sequence, packet), + Datagram::ShareAudio { .. } => relay_share_audio(room, from.id, packet), + Datagram::Video(fragment) => relay_video(room, from.id, &fragment, packet), + } + } +} + +fn relay_voice(room: &Room, id: ConnId, sequence: u32, packet: &[u8]) -> Vec { + let Some(sender) = room.seats.get(&id) else { + return Vec::new(); + }; + if sender.muted { + return Vec::new(); + } + let (Some(relay), Some(echo)) = ( + encode_relay(&sender.user_id, packet), + encode_relay( + &sender.user_id, + &Datagram::Voice { + sequence, + payload: &[], + } + .encode(), + ), + ) else { + return Vec::new(); + }; + let _ = sender.connection.send_datagram(Bytes::from(echo)); + let bytes = Bytes::from(relay); + for (other_id, seat) in &room.seats { + if *other_id != id { + let _ = seat.connection.send_datagram(bytes.clone()); + } + } + + Vec::new() +} + +fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) -> Vec { + let Some(seat) = room.seats.get(&id) else { + return Vec::new(); + }; + let Some(sharing) = seat.shares.get(&Kind::Screen) else { + return Vec::new(); + }; + let Some(relay) = encode_relay(&seat.user_id, packet) else { + return Vec::new(); + }; + let bytes = Bytes::from(relay); + for viewer in &sharing.viewers { + let _ = viewer.connection.send_datagram(bytes.clone()); + } + + Vec::new() +} + +fn relay_video(room: &mut Room, id: ConnId, fragment: &Fragment, packet: &[u8]) -> Vec { + let Some(seat) = room.seats.get_mut(&id) else { + return Vec::new(); + }; + let Some(sharing) = seat.shares.get_mut(&fragment.kind) else { + return Vec::new(); + }; + let Some(relay) = encode_relay(&seat.user_id, packet) else { + return Vec::new(); + }; + let bytes = Bytes::from(relay); + let before = sharing.layers(); + for viewer in &mut sharing.viewers { + if fragment.keyframe { + viewer.forward = viewer.forward.on_keyframe(fragment.layer); + } + if viewer.forward.live() == Some(fragment.layer) { + let _ = viewer.connection.send_datagram(bytes.clone()); + } + } + + layers_changed(id, fragment.kind, sharing, before) + .into_iter() + .collect() +} diff --git a/crates/server/src/share.rs b/crates/server/src/share.rs deleted file mode 100644 index da92eb1..0000000 --- a/crates/server/src/share.rs +++ /dev/null @@ -1,347 +0,0 @@ -use std::{ - collections::{BTreeMap, BTreeSet}, - sync::{Arc, Mutex}, -}; - -use bytes::Bytes; -use common::{ - datagram::{Datagram, encode_relay}, - event::Event, - share::{Codec, Kind, Layer, Quality, Share, Source, choose}, -}; -use quinn::Connection; - -use crate::request::Broadcast; - -#[derive(Clone, Copy)] -enum Forward { - Waiting(Layer), - Live(Layer), - Switching { live: Layer, next: Layer }, -} - -impl Forward { - fn target(self) -> Layer { - match self { - Self::Waiting(layer) | Self::Live(layer) => layer, - Self::Switching { next, .. } => next, - } - } - - fn layers(self) -> Vec { - match self { - Self::Waiting(layer) | Self::Live(layer) => vec![layer], - Self::Switching { live, next } => vec![live, next], - } - } - - fn live(self) -> Option { - match self { - Self::Waiting(_) => None, - Self::Live(layer) | Self::Switching { live: layer, .. } => Some(layer), - } - } - - fn retarget(self, next: Layer) -> Self { - match self { - Self::Waiting(_) => Self::Waiting(next), - Self::Live(live) | Self::Switching { live, .. } if live == next => Self::Live(live), - Self::Live(live) | Self::Switching { live, .. } => Self::Switching { live, next }, - } - } - - fn on_keyframe(self, layer: Layer) -> Self { - match self { - Self::Waiting(next) | Self::Switching { next, .. } if next == layer => { - Self::Live(layer) - } - _ => self, - } - } -} - -struct Viewer { - user_id: String, - connection: Connection, - quality: Quality, - decode: Vec, - forward: Forward, -} - -struct Sharing { - community_id: String, - connection: Connection, - source: Source, - viewers: Vec, -} - -impl Sharing { - fn layers(&self) -> BTreeSet { - self.viewers - .iter() - .flat_map(|viewer| viewer.forward.layers()) - .collect() - } - - fn viewer(&self, user_id: &str) -> Option<&Viewer> { - self.viewers.iter().find(|viewer| viewer.user_id == user_id) - } -} - -fn to(user_id: &str, event: Event) -> Broadcast { - Broadcast { - event, - user_ids: vec![user_id.to_string()], - } -} - -fn slot(user_id: &str, kind: Kind) -> (String, Kind) { - (user_id.to_string(), kind) -} - -fn layers_changed( - sharer_id: &str, - kind: Kind, - sharing: &Sharing, - before: BTreeSet, -) -> Option { - let after = sharing.layers(); - - (after != before).then(|| { - to( - sharer_id, - Event::ShareLayers { - kind, - layers: after.into_iter().collect(), - }, - ) - }) -} - -fn reroute(sharer_id: &str, kind: Kind, sharing: &mut Sharing) -> Vec { - let before = sharing.layers(); - let community_id = sharing.community_id.clone(); - let Sharing { - source, viewers, .. - } = sharing; - let mut used: Vec = Vec::new(); - let mut keyframes = Vec::new(); - let mut stopped = Vec::new(); - viewers.retain_mut(|viewer| { - let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { - stopped.push(to( - &viewer.user_id, - Event::ShareStopped { - community_id: community_id.clone(), - user_id: sharer_id.to_string(), - kind, - }, - )); - return false; - }; - if !used.contains(&layer) { - used.push(layer); - } - if viewer.forward.target() != layer { - keyframes.push(to(sharer_id, Event::KeyframeWanted { kind, layer })); - } - viewer.forward = viewer.forward.retarget(layer); - - true - }); - - let mut broadcasts: Vec = layers_changed(sharer_id, kind, sharing, before) - .into_iter() - .collect(); - broadcasts.extend(keyframes); - broadcasts.extend(stopped); - - broadcasts -} - -fn remove_viewer( - sharer_id: &str, - kind: Kind, - sharing: &mut Sharing, - viewer_id: &str, -) -> Option { - let before = sharing.layers(); - sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); - - layers_changed(sharer_id, kind, sharing, before) -} - -#[derive(Clone, Default)] -pub struct Shares(Arc>>); - -impl Shares { - pub fn start( - &self, - community_id: &str, - user_id: &str, - kind: Kind, - connection: Connection, - source: Source, - ) -> Vec { - let mut sharings = self.0.lock().unwrap(); - let key = slot(user_id, kind); - if let Some(sharing) = sharings - .get_mut(&key) - .filter(|sharing| sharing.community_id == community_id) - { - sharing.connection = connection; - sharing.source = source; - return reroute(user_id, kind, sharing); - } - sharings.insert( - key, - Sharing { - community_id: community_id.to_string(), - connection, - source, - viewers: Vec::new(), - }, - ); - - Vec::new() - } - - pub fn stop(&self, user_id: &str, kind: Kind) -> Option { - self.0 - .lock() - .unwrap() - .remove(&slot(user_id, kind)) - .map(|sharing| sharing.community_id) - } - - pub fn stop_all(&self, user_id: &str) -> Vec<(String, Kind)> { - Kind::ALL - .into_iter() - .filter_map(|kind| { - self.stop(user_id, kind) - .map(|community_id| (community_id, kind)) - }) - .collect() - } - - pub fn list(&self, community_id: &str) -> Vec { - self.0 - .lock() - .unwrap() - .iter() - .filter(|(_, sharing)| sharing.community_id == community_id) - .map(|((user_id, kind), sharing)| Share { - user_id: user_id.clone(), - kind: *kind, - source: sharing.source.clone(), - }) - .collect() - } - - pub fn watch( - &self, - sharer_id: &str, - kind: Kind, - viewer_id: &str, - connection: Connection, - quality: Quality, - decode: &[Codec], - ) -> Option> { - let mut sharings = self.0.lock().unwrap(); - let sharing = sharings.get_mut(&slot(sharer_id, kind))?; - let before = sharing.layers(); - let used: Vec = before.iter().copied().collect(); - let layer = choose(&sharing.source, quality, decode, &used)?; - let forward = sharing - .viewer(viewer_id) - .map_or(Forward::Waiting(layer), |viewer| { - viewer.forward.retarget(layer) - }); - sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); - sharing.viewers.push(Viewer { - user_id: viewer_id.to_string(), - connection, - quality, - decode: decode.to_vec(), - forward, - }); - let mut broadcasts: Vec = layers_changed(sharer_id, kind, sharing, before) - .into_iter() - .collect(); - broadcasts.push(to(sharer_id, Event::KeyframeWanted { kind, layer })); - - Some(broadcasts) - } - - pub fn unwatch(&self, sharer_id: &str, kind: Kind, viewer_id: &str) -> Vec { - self.0 - .lock() - .unwrap() - .get_mut(&slot(sharer_id, kind)) - .and_then(|sharing| remove_viewer(sharer_id, kind, sharing, viewer_id)) - .into_iter() - .collect() - } - - pub fn leave_viewer(&self, viewer_id: &str) -> Vec { - self.0 - .lock() - .unwrap() - .iter_mut() - .filter_map(|((sharer_id, kind), sharing)| { - remove_viewer(sharer_id, *kind, sharing, viewer_id) - }) - .collect() - } - - pub fn keyframe(&self, sharer_id: &str, kind: Kind, viewer_id: &str) -> Option { - let sharings = self.0.lock().unwrap(); - let viewer = sharings.get(&slot(sharer_id, kind))?.viewer(viewer_id)?; - - Some(to( - sharer_id, - Event::KeyframeWanted { - kind, - layer: viewer.forward.target(), - }, - )) - } - - pub fn relay(&self, connection_id: usize, packet: &[u8]) -> Vec { - let (kind, fragment) = match Datagram::decode(packet) { - Some(Datagram::Video(fragment)) => (fragment.kind, Some(fragment)), - Some(Datagram::ShareAudio { .. }) => (Kind::Screen, None), - _ => return Vec::new(), - }; - let mut sharings = self.0.lock().unwrap(); - let Some((key, sharing)) = sharings.iter_mut().find(|(key, sharing)| { - key.1 == kind && sharing.connection.stable_id() == connection_id - }) else { - return Vec::new(); - }; - let sharer_id = &key.0; - let Some(relay) = encode_relay(sharer_id, packet) else { - return Vec::new(); - }; - let bytes = Bytes::from(relay); - let Some(fragment) = fragment else { - for viewer in &sharing.viewers { - let _ = viewer.connection.send_datagram(bytes.clone()); - } - return Vec::new(); - }; - let before = sharing.layers(); - for viewer in &mut sharing.viewers { - if fragment.keyframe { - viewer.forward = viewer.forward.on_keyframe(fragment.layer); - } - if viewer.forward.live() == Some(fragment.layer) { - let _ = viewer.connection.send_datagram(bytes.clone()); - } - } - - layers_changed(sharer_id, kind, sharing, before) - .into_iter() - .collect() - } -} diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index b164d7e..2bf0309 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -141,6 +141,15 @@ pub async fn unreads( Ok(unreads) } +pub async fn member_ids(community_id: &str, conn: &Connection) -> Result, ServerError> { + database::ids( + conn, + "SELECT user_id FROM user_community WHERE community_id = ?1", + (community_id,), + ) + .await +} + pub async fn members(community_id: &str, conn: &Connection) -> Result, ServerError> { let mut rows = conn .query( diff --git a/crates/server/src/voice.rs b/crates/server/src/voice.rs deleted file mode 100644 index 92ae013..0000000 --- a/crates/server/src/voice.rs +++ /dev/null @@ -1,323 +0,0 @@ -use std::{ - collections::HashMap, - sync::{Arc, Mutex}, - time::Instant, -}; - -use bytes::Bytes; -use common::{ - datagram::{Datagram, encode_relay}, - time, -}; -use quinn::Connection; - -struct Participant { - user_id: String, - connection: Connection, - muted: bool, - ghost: bool, - joined_at: Instant, -} - -pub enum CallEnd { - Answered { seconds: u64 }, - Unanswered, - Declined, -} - -pub struct Left { - pub community_id: String, - pub user_id: String, - pub ghost_seconds: Option, - pub call: Option, -} - -enum Outcome { - Ringing, - Declined, - Answered, -} - -struct Room { - participants: Vec, - started_ms: u64, - outcome: Outcome, -} - -impl Room { - fn new() -> Self { - Self { - participants: Vec::new(), - started_ms: time::now_ms(), - outcome: Outcome::Ringing, - } - } - - fn occupied(&self) -> bool { - self.participants - .iter() - .any(|participant| !participant.ghost) - } - - fn user_ids(&self, keep: impl Fn(&Participant) -> bool) -> Vec { - self.participants - .iter() - .filter(|participant| keep(participant)) - .map(|participant| participant.user_id.clone()) - .collect() - } - - fn admit(&mut self) { - if self.occupied() { - self.outcome = Outcome::Answered; - } else { - self.started_ms = time::now_ms(); - self.outcome = Outcome::Ringing; - } - } - - fn end(&self) -> CallEnd { - match self.outcome { - Outcome::Answered => CallEnd::Answered { - seconds: time::now_ms().saturating_sub(self.started_ms) / 1000, - }, - Outcome::Declined => CallEnd::Declined, - Outcome::Ringing => CallEnd::Unanswered, - } - } -} - -type Rooms = HashMap; - -#[derive(Clone, Default)] -pub struct Voice(Arc>); - -impl Voice { - pub fn join( - &self, - community_id: &str, - user_id: &str, - connection: Connection, - muted: bool, - ghost: bool, - ) -> Option { - let mut rooms = self.0.lock().unwrap(); - let previous = leave_locked(&mut rooms, user_id); - let room = rooms - .entry(community_id.to_string()) - .or_insert_with(Room::new); - if !ghost { - room.admit(); - } - room.participants.push(Participant { - user_id: user_id.to_string(), - connection, - muted, - ghost, - joined_at: Instant::now(), - }); - - previous - } - - pub fn decline(&self, community_id: &str) { - if let Some(room) = self.0.lock().unwrap().get_mut(community_id) - && matches!(room.outcome, Outcome::Ringing) - { - room.outcome = Outcome::Declined; - } - } - - pub fn set_muted(&self, user_id: &str, muted: bool) -> Option { - let mut rooms = self.0.lock().unwrap(); - let (community_id, index) = locate(&rooms, user_id)?; - rooms.get_mut(&community_id)?.participants[index].muted = muted; - - Some(community_id) - } - - pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { - let mut rooms = self.0.lock().unwrap(); - let (community_id, index) = locate(&rooms, user_id)?; - let room = rooms.get_mut(&community_id)?; - if room.participants[index].ghost == ghost { - return None; - } - if !ghost { - room.admit(); - } - let participant = &mut room.participants[index]; - let seconds = participant - .ghost - .then(|| participant.joined_at.elapsed().as_secs()); - participant.ghost = ghost; - participant.joined_at = Instant::now(); - let call = (ghost && !room.occupied()).then(|| room.end()); - - Some(Left { - community_id, - user_id: user_id.to_string(), - ghost_seconds: seconds, - call, - }) - } - - pub fn room_users(&self, community_id: &str) -> Vec { - self.0 - .lock() - .unwrap() - .get(community_id) - .map(|room| room.user_ids(|_| true)) - .unwrap_or_default() - } - - pub fn room_of(&self, user_id: &str) -> Option { - locate(&self.0.lock().unwrap(), user_id).map(|(community_id, _)| community_id) - } - - pub fn leave(&self, user_id: &str) -> Option { - leave_locked(&mut self.0.lock().unwrap(), user_id) - } - - pub fn leave_connection(&self, connection_id: usize) -> Option { - let mut rooms = self.0.lock().unwrap(); - let user_id = find(&rooms, connection_id)?.1.user_id.clone(); - - leave_locked(&mut rooms, &user_id) - } - - pub fn leave_room(&self, community_id: &str, user_id: &str) -> Option { - remove(&mut self.0.lock().unwrap(), community_id, user_id) - } - - pub fn count(&self) -> usize { - self.0 - .lock() - .unwrap() - .values() - .map(|room| room.participants.len()) - .sum() - } - - pub fn participants(&self, community_id: &str) -> Vec { - self.0 - .lock() - .unwrap() - .get(community_id) - .map(|room| room.user_ids(|participant| !participant.ghost)) - .unwrap_or_default() - } - - pub fn rooms(&self) -> Vec<(String, Vec, Vec)> { - self.0 - .lock() - .unwrap() - .iter() - .map(|(community_id, room)| { - ( - community_id.clone(), - room.user_ids(|_| true), - room.user_ids(|participant| participant.ghost), - ) - }) - .collect() - } - - pub fn remove_room(&self, community_id: &str) -> Vec { - self.0 - .lock() - .unwrap() - .remove(community_id) - .map(|room| room.participants) - .unwrap_or_default() - .into_iter() - .map(|participant| left(community_id, participant, None)) - .collect() - } - - pub fn relay(&self, connection_id: usize, packet: &[u8]) { - let Some(Datagram::Voice { sequence, .. }) = Datagram::decode(packet) else { - return; - }; - let rooms = self.0.lock().unwrap(); - let Some((room, sender)) = find(&rooms, connection_id) else { - return; - }; - if sender.muted { - return; - } - let (Some(relay), Some(echo)) = ( - encode_relay(&sender.user_id, packet), - encode_relay( - &sender.user_id, - &Datagram::Voice { - sequence, - payload: &[], - } - .encode(), - ), - ) else { - return; - }; - let _ = sender.connection.send_datagram(Bytes::from(echo)); - let bytes = Bytes::from(relay); - - for participant in room - .participants - .iter() - .filter(|participant| participant.user_id != sender.user_id) - { - let _ = participant.connection.send_datagram(bytes.clone()); - } - } -} - -fn find(rooms: &Rooms, connection_id: usize) -> Option<(&Room, &Participant)> { - rooms.values().find_map(|room| { - room.participants - .iter() - .find(|participant| participant.connection.stable_id() == connection_id) - .map(|sender| (room, sender)) - }) -} - -fn left(community_id: &str, participant: Participant, call: Option) -> Left { - Left { - community_id: community_id.to_string(), - user_id: participant.user_id, - ghost_seconds: participant - .ghost - .then(|| participant.joined_at.elapsed().as_secs()), - call, - } -} - -fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option { - let room = rooms.get_mut(community_id)?; - let index = room - .participants - .iter() - .position(|participant| participant.user_id == user_id)?; - let participant = room.participants.remove(index); - let call = (!participant.ghost && !room.occupied()).then(|| room.end()); - if room.participants.is_empty() { - rooms.remove(community_id); - } - - Some(left(community_id, participant, call)) -} - -fn locate(rooms: &Rooms, user_id: &str) -> Option<(String, usize)> { - rooms.iter().find_map(|(community_id, room)| { - room.participants - .iter() - .position(|participant| participant.user_id == user_id) - .map(|index| (community_id.clone(), index)) - }) -} - -fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option { - let (community_id, _) = locate(rooms, user_id)?; - - remove(rooms, &community_id, user_id) -}