diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index 440ced0..cd789f1 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -1,14 +1,12 @@ use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration}; use common::{ - call::{Call, Legacy}, + call::Call, constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, error::Error, frame::{self, DOWN_MAX, Sending, UP_MAX}, model::{Attachment, User}, open::{Blob, Open, Upload}, - request::LegacyRequest, - response::Response, session::{Hello, Welcome}, transport::{Close, alpn, transport}, validate::{validate_attachment_name, validate_attachment_size}, @@ -265,13 +263,6 @@ pub(super) async fn call( Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) } -pub(super) async fn send( - connection: &quinn::Connection, - request: &LegacyRequest, -) -> Result { - call(connection, Legacy(request.clone())).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); @@ -285,16 +276,6 @@ async fn hello(connection: &quinn::Connection, token: Option) -> Result< Ok(frame::read::>(&mut receive_stream, DOWN_MAX).await??) } -pub(super) async fn done( - connection: &quinn::Connection, - request: LegacyRequest, -) -> Result<(), Fail> { - match send(connection, &request).await? { - Response::Done => Ok(()), - _ => Err(Fail::Protocol), - } -} - pub(super) async fn send_body( send_stream: &mut quinn::SendStream, file: &mut tokio::fs::File, diff --git a/crates/client/src/net/media.rs b/crates/client/src/net/media.rs index d2552fd..13ab0dc 100644 --- a/crates/client/src/net/media.rs +++ b/crates/client/src/net/media.rs @@ -6,10 +6,12 @@ use std::{ use bytes::Bytes; use common::{ + call::{ + Call, JoinVoice, LeaveVoice, ListShares, RequestKeyframe, StartShare, StopShare, + UnwatchShare, WatchShare, + }, datagram::{Packet, RELAY_PREFIX}, event::{Event, Media as Down}, - request::LegacyRequest, - response::Response, share::{Fps, Kind, Quality, Resolution, Source}, }; use quinn::Connection; @@ -28,10 +30,7 @@ use crate::{ voice::{self, Voice, VoiceSample, audio::Choice}, }; -use super::{ - link::{done, send}, - *, -}; +use super::{link::call, *}; const TICK: Duration = Duration::from_secs(1); const WAIT_STEP: Duration = Duration::from_millis(100); @@ -187,7 +186,7 @@ impl Media { Ok(_) if ours => Rejoin::Install, Ok(_) => { if inner.want_voice.is_none() && inner.joining == 0 { - tokio::spawn(send_quietly(connection.clone(), LegacyRequest::LeaveVoice)); + tokio::spawn(send_quietly(connection.clone(), LeaveVoice)); } Rejoin::Skip } @@ -228,7 +227,7 @@ impl Media { let media = self.clone(); let connection = connection.clone(); tokio::spawn(async move { - if send(&connection, &request).await.is_err() { + if call(&connection, request).await.is_err() { media.lock().watching.remove(&key); } }); @@ -332,7 +331,7 @@ impl Media { inner.connection.clone().ok_or(Fail::Offline)? }; - done(&connection, LegacyRequest::LeaveVoice).await + call(&connection, LeaveVoice).await } async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> { @@ -359,7 +358,7 @@ impl Media { inner.sharing.insert(kind, sharing); } - let result = done(&connection, LegacyRequest::StartShare { kind, source }).await; + let result = call(&connection, StartShare { kind, source }).await; if result.is_err() { self.lock().sharing.remove(&kind); } @@ -384,9 +383,9 @@ impl Media { .map_err(Fail::Io)? }; - done( + call( &connection, - LegacyRequest::StartShare { + StartShare { kind: Kind::Screen, source, }, @@ -398,16 +397,16 @@ impl Media { self.lock().sharing.remove(&kind); let (connection, _) = self.current_wait().await?; - done(&connection, LegacyRequest::StopShare { kind }).await + call(&connection, StopShare { kind }).await } } impl Inner { - fn watch_requests(&self) -> Vec<((String, Kind), LegacyRequest)> { + fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> { self.watching .iter() .map(|((user_id, kind), watching)| { - let request = LegacyRequest::WatchShare { + let request = WatchShare { user_id: user_id.clone(), kind: *kind, quality: watching.wanted(), @@ -426,17 +425,15 @@ enum Rejoin { } async fn join(connection: &Connection, community_id: &str) -> Result, Fail> { - let request = LegacyRequest::JoinVoice { + let request = JoinVoice { community_id: community_id.to_string(), }; - match send(connection, &request).await? { - Response::Voice(participants) => Ok(participants), - _ => Err(Fail::Protocol), - } + + call(connection, request).await } -async fn send_quietly(connection: Connection, request: LegacyRequest) { - if let Err(error) = send(&connection, &request).await { +async fn send_quietly(connection: Connection, request: C) { + if let Err(error) = call(&connection, request).await { warn!("media request failed: {error}"); } } @@ -453,12 +450,20 @@ async fn tick_loop(media: Arc) { continue; }; for request in requests { - tokio::spawn(send_quietly(connection.clone(), request)); + match request { + Ping::Watch(request) => tokio::spawn(send_quietly(connection.clone(), request)), + Ping::Keyframe(request) => tokio::spawn(send_quietly(connection.clone(), request)), + }; } } } -fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec { +enum Ping { + Watch(WatchShare), + Keyframe(RequestKeyframe), +} + +fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec { watching .iter_mut() .flat_map(|((user_id, kind), watching)| { @@ -467,16 +472,16 @@ fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec LegacyRequest::WatchShare { + Tick::Quality(quality) => Ping::Watch(WatchShare { user_id: user_id.clone(), kind, quality, decode: capabilities().decode.clone(), - }, - Tick::Keyframe => LegacyRequest::RequestKeyframe { + }), + Tick::Keyframe => Ping::Keyframe(RequestKeyframe { user_id: user_id.clone(), kind, - }, + }), }) .collect::>() }) @@ -663,13 +668,10 @@ impl NetworkHandle { } pub async fn shares(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Shares { - community_id: community_id.to_string(), - }) - .await?, - Response::Shares - ) + self.call(ListShares { + community_id: community_id.to_string(), + }) + .await } pub async fn watch_share( @@ -695,9 +697,9 @@ impl NetworkHandle { } inner.watching.insert(key.clone(), watching); } - let result = done( + let result = call( &connection, - LegacyRequest::WatchShare { + WatchShare { user_id: key.0.clone(), kind, quality, @@ -720,7 +722,7 @@ impl NetworkHandle { .watching .remove(&(user_id.to_string(), kind)); - self.done(LegacyRequest::UnwatchShare { + self.call(UnwatchShare { user_id: user_id.to_string(), kind, }) diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index 17e4e0b..bb722ea 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -2,8 +2,22 @@ use std::{path::PathBuf, sync::Arc}; use common::{ call::{ - Call, GetAvatar, GetSettings, GetUser, Legacy, ListPresences, ListSessions, RemoveAvatar, - RevokeSession, UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser, + AcceptFriend, AcceptInvitation, AddFriend, BanMember, BanUser, Call, ClearProfile, + ClosePoll, CreateBackup, CreateCommunity, CreateInviteCode, CreateMessage, CreatePoll, + CreateUser, DeclineCall, DeclineInvitation, DeleteAttachment, DeleteBackup, + DeleteCommunity, DeleteInviteCode, DeleteMessage, DeleteUser, FindUser, ForwardMessages, + GetAvatar, GetCommunity, GetDailyStats, GetOverview, GetSettings, GetStorageUsage, GetUser, + HandleReport, Invite, Kick, KickFromVoice, LeaveCommunity, ListAdminLogs, + ListAllCommunities, ListAttachments, ListBackups, ListBans, ListCommunities, ListFriends, + ListInvitations, ListInviteCodes, ListLogs, ListMembers, ListMessages, ListPins, + ListPresences, ListReports, ListServerBans, ListSessions, ListUnreads, ListUsers, + ListVoiceParticipants, ListVoiceRooms, Login, Logout, MarkRead, OpenDirect, OpenNotes, Pin, + PurgeUser, React, Register, RemoveAvatar, RemoveFriend, RemoveServerBan, RenameUser, + ReportMessage, ReportUser, ResetPassword, RevokeSession, RevokeSessions, SearchCommunity, + SearchMessages, ServerMute, Session, SetCommunityVoice, SetGhost, SetRank, SetRole, + SuspendUser, TimeoutUser, TransferOwnership, Typing, Unban, UpdateAvatar, UpdateCommunity, + UpdateCommunityAvatar, UpdateMessage, UpdatePresence, UpdateServerSettings, UpdateStatus, + UpdateUser, Vote, WatchCommunity, }, constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, event::Event, @@ -14,8 +28,6 @@ use common::{ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, open::Blob, - request::LegacyRequest, - response::Response, validate::{ validate_avatar_size, validate_community_name, validate_forward, validate_new_message, validate_password, validate_poll, validate_reason, validate_server_settings, @@ -24,15 +36,6 @@ use common::{ }; use tokio::sync::{mpsc, oneshot}; -macro_rules! expect { - ($response:expr, $variant:path) => { - match $response { - $variant(value) => Ok(value), - _ => Err(Fail::Protocol), - } - }; -} - mod datagram; mod events; mod fail; @@ -134,22 +137,14 @@ impl NetworkHandle { .await } - async fn request(&self, request: LegacyRequest) -> Result { - self.call(Legacy(request)).await - } - async fn switch(&self, token: Option) -> Result, Fail> { self.ask(|reply| Command::SignIn { token, reply }).await } - async fn sign_in(&self, request: LegacyRequest) -> Result<(User, String), Fail> { - let (user, token) = match self.request(request).await? { - Response::Session { user, token } => (user, token), - _ => return Err(Fail::Protocol), - }; - self.switch(Some(token.clone())).await?; + async fn sign_in(&self, session: Session) -> Result<(User, String), Fail> { + self.switch(Some(session.token.clone())).await?; - Ok((user, token)) + Ok((session.user, session.token)) } pub async fn sessions(&self, user_id: &str) -> Result, Fail> { @@ -170,14 +165,11 @@ impl NetworkHandle { pub async fn rename_user(&self, user_id: &str, username: &str) -> Result { validate_username(username)?; - expect!( - self.request(LegacyRequest::RenameUser { - user_id: user_id.to_string(), - username: username.to_string(), - }) - .await?, - Response::User - ) + self.call(RenameUser { + user_id: user_id.to_string(), + username: username.to_string(), + }) + .await } pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { @@ -202,26 +194,32 @@ impl NetworkHandle { validate_username(username)?; validate_password(password)?; - self.sign_in(LegacyRequest::Register { - username: username.to_string(), - password: password.to_string(), - invite: invite.map(str::to_string), - }) - .await + let session = self + .call(Register { + username: username.to_string(), + password: password.to_string(), + invite: invite.map(str::to_string), + }) + .await?; + + self.sign_in(session).await } pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> { validate_password(password)?; - self.sign_in(LegacyRequest::Login { - username: username.to_string(), - password: password.to_string(), - }) - .await + let session = self + .call(Login { + username: username.to_string(), + password: password.to_string(), + }) + .await?; + + self.sign_in(session).await } pub async fn logout(&self) -> Result<(), Fail> { - let result = self.done(LegacyRequest::Logout).await; + let result = self.call(Logout).await; self.detach().await?; result } @@ -236,22 +234,18 @@ impl NetworkHandle { } pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> { - expect!( - self.request(LegacyRequest::DeleteUser { - user_id: user_id.to_string(), - }) - .await?, - Response::User - ) - .map(|_| ()) + self.call(DeleteUser { + user_id: user_id.to_string(), + }) + .await } pub async fn users(&self) -> Result, Fail> { - expect!(self.request(LegacyRequest::Users).await?, Response::Users) + self.call(ListUsers).await } pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> { - self.done(LegacyRequest::SuspendUser { + self.call(SuspendUser { user_id: user_id.to_string(), suspended, }) @@ -259,7 +253,7 @@ impl NetworkHandle { } pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> { - self.done(LegacyRequest::TimeoutUser { + self.call(TimeoutUser { user_id: user_id.to_string(), minutes, }) @@ -274,7 +268,7 @@ impl NetworkHandle { ) -> Result<(), Fail> { validate_reason(reason)?; - self.done(LegacyRequest::BanUser { + self.call(BanUser { user_id: user_id.to_string(), reason: reason.map(str::to_string), scope, @@ -283,15 +277,11 @@ impl NetworkHandle { } pub async fn server_bans(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::ServerBans).await?, - Response::ServerBans - ) + self.call(ListServerBans).await } pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::RemoveServerBan { id: id.to_string() }) - .await + self.call(RemoveServerBan { id: id.to_string() }).await } pub async fn create_invite_code( @@ -299,29 +289,22 @@ impl NetworkHandle { uses: u32, hours: Option, ) -> Result { - expect!( - self.request(LegacyRequest::CreateInviteCode { uses, hours }) - .await?, - Response::InviteCode - ) + self.call(CreateInviteCode { uses, hours }).await } pub async fn invite_codes(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::InviteCodes).await?, - Response::InviteCodes - ) + self.call(ListInviteCodes).await } pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> { - self.done(LegacyRequest::DeleteInviteCode { + self.call(DeleteInviteCode { code: code.to_string(), }) .await } pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::RevokeSessions { + self.call(RevokeSessions { user_id: user_id.to_string(), }) .await @@ -330,7 +313,7 @@ impl NetworkHandle { pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> { validate_password(password)?; - self.done(LegacyRequest::ResetPassword { + self.call(ResetPassword { user_id: user_id.to_string(), password: password.to_string(), }) @@ -338,24 +321,18 @@ impl NetworkHandle { } pub async fn clear_profile(&self, user_id: &str) -> Result { - expect!( - self.request(LegacyRequest::ClearProfile { - user_id: user_id.to_string(), - }) - .await?, - Response::User - ) + self.call(ClearProfile { + user_id: user_id.to_string(), + }) + .await } pub async fn set_role(&self, user_id: &str, role: Role) -> Result { - expect!( - self.request(LegacyRequest::SetRole { - user_id: user_id.to_string(), - role, - }) - .await?, - Response::User - ) + self.call(SetRole { + user_id: user_id.to_string(), + role, + }) + .await } pub async fn admin_logs( @@ -366,21 +343,18 @@ impl NetworkHandle { after_ms: Option, before_ms: Option, ) -> Result, Fail> { - let request = LegacyRequest::AdminLogs { + self.call(ListAdminLogs { actor_id, target_id, action, after_ms, before_ms, - }; - expect!(self.request(request).await?, Response::AdminLogs) + }) + .await } pub async fn daily_stats(&self, days: u32) -> Result, Fail> { - expect!( - self.request(LegacyRequest::DailyStats { days }).await?, - Response::DailyStats - ) + self.call(GetDailyStats { days }).await } pub async fn server_settings(&self) -> Result { @@ -393,43 +367,30 @@ impl NetworkHandle { ) -> Result { validate_server_settings(&settings)?; - expect!( - self.request(LegacyRequest::UpdateServerSettings { settings }) - .await?, - Response::ServerSettings - ) + self.call(UpdateServerSettings { settings }).await } pub async fn create_user(&self, username: &str, password: &str) -> Result { validate_username(username)?; validate_password(password)?; - expect!( - self.request(LegacyRequest::CreateUser { - username: username.to_string(), - password: password.to_string(), - }) - .await?, - Response::User - ) + self.call(CreateUser { + username: username.to_string(), + password: password.to_string(), + }) + .await } pub async fn overview(&self) -> Result { - expect!( - self.request(LegacyRequest::Overview).await?, - Response::Overview - ) + self.call(GetOverview).await } pub async fn all_communities(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::AllCommunities).await?, - Response::AllCommunities - ) + self.call(ListAllCommunities).await } pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::TransferOwnership { + self.call(TransferOwnership { community_id: community_id.to_string(), user_id: user_id.to_string(), }) @@ -446,13 +407,10 @@ impl NetworkHandle { pub async fn create_community(&self, name: &str) -> Result { validate_community_name(name)?; - expect!( - self.request(LegacyRequest::CreateCommunity { - name: name.to_string(), - }) - .await?, - Response::Community - ) + self.call(CreateCommunity { + name: name.to_string(), + }) + .await } pub async fn update_community( @@ -462,49 +420,36 @@ impl NetworkHandle { ) -> Result { validate_community_name(name)?; - expect!( - self.request(LegacyRequest::UpdateCommunity { - community_id: community_id.to_string(), - name: name.to_string(), - }) - .await?, - Response::Community - ) + self.call(UpdateCommunity { + community_id: community_id.to_string(), + name: name.to_string(), + }) + .await } pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> { - expect!( - self.request(LegacyRequest::DeleteCommunity { - community_id: community_id.to_string(), - }) - .await?, - Response::Community - ) - .map(|_| ()) + self.call(DeleteCommunity { + community_id: community_id.to_string(), + }) + .await } pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::LeaveCommunity { + self.call(LeaveCommunity { community_id: community_id.to_string(), }) .await } pub async fn communities(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Communities).await?, - Response::Communities - ) + self.call(ListCommunities).await } pub async fn members(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Members { - community_id: community_id.to_string(), - }) - .await?, - Response::Members - ) + self.call(ListMembers { + community_id: community_id.to_string(), + }) + .await } pub async fn kick( @@ -514,7 +459,7 @@ impl NetworkHandle { reason: Option<&str>, ) -> Result<(), Fail> { validate_reason(reason)?; - self.done(LegacyRequest::Kick { + self.call(Kick { community_id: community_id.to_string(), user_id: user_id.to_string(), reason: reason.map(str::to_string), @@ -529,7 +474,7 @@ impl NetworkHandle { reason: Option<&str>, ) -> Result<(), Fail> { validate_reason(reason)?; - self.done(LegacyRequest::Ban { + self.call(BanMember { community_id: community_id.to_string(), user_id: user_id.to_string(), reason: reason.map(str::to_string), @@ -538,7 +483,7 @@ impl NetworkHandle { } pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::Unban { + self.call(Unban { community_id: community_id.to_string(), user_id: user_id.to_string(), }) @@ -546,23 +491,17 @@ impl NetworkHandle { } pub async fn bans(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Bans { - community_id: community_id.to_string(), - }) - .await?, - Response::Bans - ) + self.call(ListBans { + community_id: community_id.to_string(), + }) + .await } pub async fn logs(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Logs { - community_id: community_id.to_string(), - }) - .await?, - Response::Logs - ) + self.call(ListLogs { + community_id: community_id.to_string(), + }) + .await } pub async fn set_rank( @@ -571,7 +510,7 @@ impl NetworkHandle { user_id: &str, rank: Rank, ) -> Result<(), Fail> { - self.done(LegacyRequest::SetRank { + self.call(SetRank { community_id: community_id.to_string(), user_id: user_id.to_string(), rank, @@ -580,14 +519,10 @@ impl NetworkHandle { } pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> { - expect!( - self.request(LegacyRequest::DeleteMessage { - message_id: message_id.to_string(), - }) - .await?, - Response::Message - ) - .map(|_| ()) + self.call(DeleteMessage { + message_id: message_id.to_string(), + }) + .await } pub async fn create_message( @@ -599,29 +534,23 @@ impl NetworkHandle { ) -> Result { validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; - expect!( - self.request(LegacyRequest::CreateMessage { - community_id: community_id.to_string(), - body: body.to_string(), - attachments, - reply_to, - }) - .await?, - Response::Message - ) + self.call(CreateMessage { + community_id: community_id.to_string(), + body: body.to_string(), + attachments, + reply_to, + }) + .await } pub async fn update_message(&self, message_id: &str, body: &str) -> Result { validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; - expect!( - self.request(LegacyRequest::UpdateMessage { - message_id: message_id.to_string(), - body: body.to_string(), - }) - .await?, - Response::Message - ) + self.call(UpdateMessage { + message_id: message_id.to_string(), + body: body.to_string(), + }) + .await } pub async fn forward_messages( @@ -632,49 +561,34 @@ impl NetworkHandle { ) -> Result, Fail> { validate_forward(message_ids.len())?; - expect!( - self.request(LegacyRequest::ForwardMessages { - message_ids, - community_id: community_id.to_string(), - snippet, - }) - .await?, - Response::Messages - ) + self.call(ForwardMessages { + message_ids, + community_id: community_id.to_string(), + snippet, + }) + .await } pub async fn find_user(&self, username: &str) -> Result { - expect!( - self.request(LegacyRequest::FindUser { - username: username.to_string(), - }) - .await?, - Response::User - ) + self.call(FindUser { + username: username.to_string(), + }) + .await } pub async fn open_notes(&self) -> Result { - expect!( - self.request(LegacyRequest::OpenNotes).await?, - Response::Community - ) + self.call(OpenNotes).await } pub async fn open_direct(&self, user_id: &str) -> Result { - expect!( - self.request(LegacyRequest::OpenDirect { - user_id: user_id.to_string(), - }) - .await?, - Response::Community - ) + self.call(OpenDirect { + user_id: user_id.to_string(), + }) + .await } pub async fn friends(&self) -> Result { - expect!( - self.request(LegacyRequest::Friends).await?, - Response::Friends - ) + self.call(ListFriends).await } pub async fn read_presences(&self) -> Result, Fail> { @@ -686,28 +600,28 @@ impl NetworkHandle { } pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::AddFriend { + self.call(AddFriend { user_id: user_id.to_string(), }) .await } pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::AcceptFriend { + self.call(AcceptFriend { user_id: user_id.to_string(), }) .await } pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::RemoveFriend { + self.call(RemoveFriend { user_id: user_id.to_string(), }) .await } pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::Invite { + self.call(Invite { community_id: community_id.to_string(), user_id: user_id.to_string(), }) @@ -715,38 +629,32 @@ impl NetworkHandle { } pub async fn invitations(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Invitations).await?, - Response::Invitations - ) + self.call(ListInvitations).await } pub async fn accept_invitation(&self, community_id: &str) -> Result { - expect!( - self.request(LegacyRequest::AcceptInvitation { - community_id: community_id.to_string(), - }) - .await?, - Response::Community - ) + self.call(AcceptInvitation { + community_id: community_id.to_string(), + }) + .await } pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::DeclineInvitation { + self.call(DeclineInvitation { community_id: community_id.to_string(), }) .await } pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::DeclineCall { + self.call(DeclineCall { community_id: community_id.to_string(), }) .await } pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> { - self.done(LegacyRequest::React { + self.call(React { message_id: message_id.to_string(), emoji: emoji.to_string(), }) @@ -754,7 +662,7 @@ impl NetworkHandle { } pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> { - self.done(LegacyRequest::Pin { + self.call(Pin { message_id: message_id.to_string(), pinned, }) @@ -762,13 +670,10 @@ impl NetworkHandle { } pub async fn pins(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Pins { - community_id: community_id.to_string(), - }) - .await?, - Response::Messages - ) + self.call(ListPins { + community_id: community_id.to_string(), + }) + .await } pub async fn create_poll( @@ -780,20 +685,17 @@ impl NetworkHandle { ) -> Result { validate_poll(question, &options)?; - expect!( - self.request(LegacyRequest::CreatePoll { - community_id: community_id.to_string(), - question: question.to_string(), - options, - multiple, - }) - .await?, - Response::Message - ) + self.call(CreatePoll { + community_id: community_id.to_string(), + question: question.to_string(), + options, + multiple, + }) + .await } pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Fail> { - self.done(LegacyRequest::Vote { + self.call(Vote { message_id: message_id.to_string(), positions, }) @@ -801,7 +703,7 @@ impl NetworkHandle { } pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::ClosePoll { + self.call(ClosePoll { message_id: message_id.to_string(), }) .await @@ -810,7 +712,7 @@ impl NetworkHandle { pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> { validate_reason(Some(reason))?; - self.done(LegacyRequest::ReportMessage { + self.call(ReportMessage { message_id: message_id.to_string(), reason: reason.to_string(), }) @@ -820,7 +722,7 @@ impl NetworkHandle { pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> { validate_reason(Some(reason))?; - self.done(LegacyRequest::ReportUser { + self.call(ReportUser { user_id: user_id.to_string(), reason: reason.to_string(), }) @@ -828,14 +730,11 @@ impl NetworkHandle { } pub async fn reports(&self, status: Option) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Reports { status }).await?, - Response::Reports - ) + self.call(ListReports { status }).await } pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> { - self.done(LegacyRequest::HandleReport { + self.call(HandleReport { report_id: report_id.to_string(), status, }) @@ -850,17 +749,14 @@ impl NetworkHandle { after_ms: Option, before_ms: Option, ) -> Result, Fail> { - expect!( - self.request(LegacyRequest::SearchMessages { - text, - user_id, - community_id, - after_ms, - before_ms, - }) - .await?, - Response::MessageHits - ) + self.call(SearchMessages { + text, + user_id, + community_id, + after_ms, + before_ms, + }) + .await } pub async fn search_community( @@ -868,36 +764,25 @@ impl NetworkHandle { community_id: String, text: String, ) -> Result, Fail> { - expect!( - self.request(LegacyRequest::SearchCommunity { community_id, text }) - .await?, - Response::MessageHits - ) + self.call(SearchCommunity { community_id, text }).await } pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { - match self.request(LegacyRequest::StorageUsage).await? { - Response::StorageUsage { users, communities } => Ok((users, communities)), - _ => Err(Fail::Protocol), - } + let usage = self.call(GetStorageUsage).await?; + + Ok((usage.users, usage.communities)) } pub async fn create_backup(&self) -> Result { - expect!( - self.request(LegacyRequest::CreateBackup).await?, - Response::Backup - ) + self.call(CreateBackup).await } pub async fn backups(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Backups).await?, - Response::Backups - ) + self.call(ListBackups).await } pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> { - self.done(LegacyRequest::DeleteBackup { + self.call(DeleteBackup { name: name.to_string(), }) .await @@ -908,37 +793,27 @@ impl NetworkHandle { user_id: Option, community_id: Option, ) -> Result, Fail> { - expect!( - self.request(LegacyRequest::AllAttachments { - user_id, - community_id, - }) - .await?, - Response::AttachmentInfos - ) + self.call(ListAttachments { + user_id, + community_id, + }) + .await } pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::DeleteAttachment { + self.call(DeleteAttachment { attachment_id: attachment_id.to_string(), }) .await } pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::PurgeUser { + self.call(PurgeUser { user_id: user_id.to_string(), }) .await } - async fn done(&self, request: LegacyRequest) -> Result<(), Fail> { - match self.request(request).await? { - Response::Done => Ok(()), - _ => Err(Fail::Protocol), - } - } - pub async fn upload_attachment( &self, community_id: &str, @@ -978,7 +853,7 @@ impl NetworkHandle { } pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> { - self.done(LegacyRequest::WatchCommunity { + self.call(WatchCommunity { community_id: community_id.map(str::to_string), }) .await @@ -989,25 +864,19 @@ impl NetworkHandle { community_id: &str, before: Option<&str>, ) -> Result, Fail> { - expect!( - self.request(LegacyRequest::ReadMessages { - community_id: community_id.to_string(), - before: before.map(str::to_string), - }) - .await?, - Response::Messages - ) + self.call(ListMessages { + community_id: community_id.to_string(), + before: before.map(str::to_string), + }) + .await } pub async fn unreads(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::Unreads).await?, - Response::Unreads - ) + self.call(ListUnreads).await } pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::MarkRead { + self.call(MarkRead { community_id: community_id.to_string(), message_id: message_id.to_string(), }) @@ -1038,14 +907,11 @@ impl NetworkHandle { validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; } - expect!( - self.request(LegacyRequest::UpdateCommunityAvatar { - community_id: community_id.to_string(), - image, - }) - .await?, - Response::Community - ) + self.call(UpdateCommunityAvatar { + community_id: community_id.to_string(), + image, + }) + .await } pub async fn remove_avatar(&self) -> Result { @@ -1060,52 +926,43 @@ impl NetworkHandle { } pub async fn typing(&self, community_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::Typing { + self.call(Typing { community_id: community_id.to_string(), }) .await } pub async fn read_community(&self, community_id: &str) -> Result { - expect!( - self.request(LegacyRequest::ReadCommunity { - community_id: community_id.to_string(), - }) - .await?, - Response::Community - ) + self.call(GetCommunity { + community_id: community_id.to_string(), + }) + .await } pub async fn voice_participants(&self, community_id: &str) -> Result, Fail> { - expect!( - self.request(LegacyRequest::VoiceParticipants { - community_id: community_id.to_string(), - }) - .await?, - Response::Voice - ) + self.call(ListVoiceParticipants { + community_id: community_id.to_string(), + }) + .await } pub async fn voice_rooms(&self) -> Result, Fail> { - expect!( - self.request(LegacyRequest::VoiceRooms).await?, - Response::VoiceRooms - ) + self.call(ListVoiceRooms).await } pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> { - self.done(LegacyRequest::SetGhost { enabled }).await + self.call(SetGhost { enabled }).await } pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> { - self.done(LegacyRequest::KickFromVoice { + self.call(KickFromVoice { user_id: user_id.to_string(), }) .await } pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> { - self.done(LegacyRequest::ServerMute { + self.call(ServerMute { user_id: user_id.to_string(), muted, }) @@ -1117,13 +974,10 @@ impl NetworkHandle { community_id: &str, enabled: bool, ) -> Result { - expect!( - self.request(LegacyRequest::SetCommunityVoice { - community_id: community_id.to_string(), - enabled, - }) - .await?, - Response::Community - ) + self.call(SetCommunityVoice { + community_id: community_id.to_string(), + enabled, + }) + .await } } diff --git a/crates/common/src/call.rs b/crates/common/src/call.rs index ef5258d..6c5cb31 100644 --- a/crates/common/src/call.rs +++ b/crates/common/src/call.rs @@ -1,9 +1,13 @@ use bitcode::{Decode, DecodeOwned, Encode}; use crate::{ - model::{Presence, ServerSettings, SessionInfo, User}, - request::LegacyRequest, - response::Response, + model::{ + Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community, + CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, + Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, + ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, + }, + share::{Codec, Kind, Quality, Share, Source}, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -40,9 +44,6 @@ macro_rules! calls { }; } -#[derive(Debug, Clone, Encode, Decode)] -pub struct Legacy(pub LegacyRequest); - #[derive(Debug, Clone, Encode, Decode)] pub struct GetSettings; @@ -93,8 +94,510 @@ pub struct RevokeSession { pub session_id: String, } +#[derive(Debug, Clone, Encode, Decode)] +pub struct CreateCommunity { + pub name: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct GetCommunity { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct UpdateCommunity { + pub community_id: String, + pub name: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct UpdateCommunityAvatar { + pub community_id: String, + pub image: Option>, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeleteCommunity { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct LeaveCommunity { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListCommunities; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListMembers { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Kick { + pub community_id: String, + pub user_id: String, + pub reason: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct BanMember { + pub community_id: String, + pub user_id: String, + pub reason: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Unban { + pub community_id: String, + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListBans { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SetRank { + pub community_id: String, + pub user_id: String, + pub rank: Rank, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListLogs { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct CreateMessage { + pub community_id: String, + pub body: String, + pub attachments: Vec, + pub reply_to: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ForwardMessages { + pub message_ids: Vec, + pub community_id: String, + pub snippet: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct UpdateMessage { + pub message_id: String, + pub body: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeleteMessage { + pub message_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct CreatePoll { + pub community_id: String, + pub question: String, + pub options: Vec, + pub multiple: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Vote { + pub message_id: String, + pub positions: Vec, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ClosePoll { + pub message_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct React { + pub message_id: String, + pub emoji: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Pin { + pub message_id: String, + pub pinned: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListPins { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListMessages { + pub community_id: String, + pub before: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListUnreads; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct MarkRead { + pub community_id: String, + pub message_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Typing { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct FindUser { + pub username: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct OpenDirect { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct OpenNotes; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListFriends; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct AddFriend { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct AcceptFriend { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct RemoveFriend { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Invite { + pub community_id: String, + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListInvitations; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct AcceptInvitation { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeclineInvitation { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ReportMessage { + pub message_id: String, + pub reason: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ReportUser { + pub user_id: String, + pub reason: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListReports { + pub status: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct HandleReport { + pub report_id: String, + pub status: ReportStatus, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct JoinVoice { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct LeaveVoice; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct StartShare { + pub kind: Kind, + pub source: Source, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct StopShare { + pub kind: Kind, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListShares { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct WatchShare { + pub user_id: String, + pub kind: Kind, + pub quality: Quality, + pub decode: Vec, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct UnwatchShare { + pub user_id: String, + pub kind: Kind, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct RequestKeyframe { + pub user_id: String, + pub kind: Kind, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeclineCall { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListVoiceParticipants { + pub community_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListVoiceRooms; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct KickFromVoice { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ServerMute { + pub user_id: String, + pub muted: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Register { + pub username: String, + pub password: String, + pub invite: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Login { + pub username: String, + pub password: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Logout; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeleteUser { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct WatchCommunity { + pub community_id: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListUsers; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SetRole { + pub user_id: String, + pub role: Role, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListAdminLogs { + pub actor_id: Option, + pub target_id: Option, + pub action: Option, + pub after_ms: Option, + pub before_ms: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct GetOverview; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SuspendUser { + pub user_id: String, + pub suspended: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct RevokeSessions { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ResetPassword { + pub user_id: String, + pub password: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ClearProfile { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListAllCommunities; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct TransferOwnership { + pub community_id: String, + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct UpdateServerSettings { + pub settings: ServerSettings, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct CreateUser { + pub username: String, + pub password: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct RenameUser { + pub user_id: String, + pub username: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct TimeoutUser { + pub user_id: String, + pub minutes: u32, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct BanUser { + pub user_id: String, + pub reason: Option, + pub scope: BanScope, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListServerBans; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct RemoveServerBan { + pub id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct CreateInviteCode { + pub uses: u32, + pub hours: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListInviteCodes; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeleteInviteCode { + pub code: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SearchMessages { + pub text: Option, + pub user_id: Option, + pub community_id: Option, + pub after_ms: Option, + pub before_ms: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SearchCommunity { + pub community_id: String, + pub text: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct PurgeUser { + pub user_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SetCommunityVoice { + pub community_id: String, + pub enabled: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListAttachments { + pub user_id: Option, + pub community_id: Option, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeleteAttachment { + pub attachment_id: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct GetStorageUsage; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct GetDailyStats { + pub days: u32, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct SetGhost { + pub enabled: bool, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct CreateBackup; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct ListBackups; + +#[derive(Debug, Clone, Encode, Decode)] +pub struct DeleteBackup { + pub name: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct Session { + pub user: User, + pub token: String, +} + +#[derive(Debug, Clone, Encode, Decode)] +pub struct StorageUsage { + pub users: Vec, + pub communities: Vec, +} + calls! { - Legacy: Guest -> Response; GetSettings: Guest -> ServerSettings; GetUser: User -> User; UpdateUser: User -> User; @@ -106,4 +609,97 @@ calls! { GetAvatar: User -> Vec; ListSessions: User -> Vec; RevokeSession: User -> (); + CreateCommunity: User -> Community; + GetCommunity: User -> Community; + UpdateCommunity: User -> Community; + UpdateCommunityAvatar: User -> Community; + DeleteCommunity: User -> (); + LeaveCommunity: User -> (); + ListCommunities: User -> Vec; + ListMembers: User -> Vec; + Kick: User -> (); + BanMember: User -> (); + Unban: User -> (); + ListBans: User -> Vec; + SetRank: User -> (); + ListLogs: User -> Vec; + CreateMessage: User -> Message; + ForwardMessages: User -> Vec; + UpdateMessage: User -> Message; + DeleteMessage: User -> (); + CreatePoll: User -> Message; + Vote: User -> (); + ClosePoll: User -> (); + React: User -> (); + Pin: User -> (); + ListPins: User -> Vec; + ListMessages: User -> Vec; + ListUnreads: User -> Vec; + MarkRead: User -> (); + Typing: User -> (); + FindUser: User -> User; + OpenDirect: User -> Community; + OpenNotes: User -> Community; + ListFriends: User -> Friends; + AddFriend: User -> (); + AcceptFriend: User -> (); + RemoveFriend: User -> (); + Invite: User -> (); + ListInvitations: User -> Vec; + AcceptInvitation: User -> Community; + DeclineInvitation: User -> (); + ReportMessage: User -> (); + ReportUser: User -> (); + ListReports: Builder -> Vec; + HandleReport: User -> (); + JoinVoice: User -> Vec; + LeaveVoice: User -> (); + StartShare: User -> (); + StopShare: User -> (); + ListShares: User -> Vec; + WatchShare: User -> (); + UnwatchShare: User -> (); + RequestKeyframe: User -> (); + DeclineCall: User -> (); + ListVoiceParticipants: User -> Vec; + ListVoiceRooms: Builder -> Vec; + KickFromVoice: User -> (); + ServerMute: User -> (); + Register: Guest -> Session; + Login: Guest -> Session; + Logout: User -> (); + DeleteUser: User -> (); + WatchCommunity: User -> (); + ListUsers: Builder -> Vec; + SetRole: User -> User; + ListAdminLogs: Builder -> Vec; + GetOverview: Builder -> Overview; + SuspendUser: User -> (); + RevokeSessions: User -> (); + ResetPassword: User -> (); + ClearProfile: User -> User; + ListAllCommunities: Builder -> Vec; + TransferOwnership: User -> (); + UpdateServerSettings: Builder -> ServerSettings; + CreateUser: Builder -> User; + RenameUser: User -> User; + TimeoutUser: User -> (); + BanUser: User -> (); + ListServerBans: Builder -> Vec; + RemoveServerBan: Builder -> (); + CreateInviteCode: User -> InviteCode; + ListInviteCodes: Builder -> Vec; + DeleteInviteCode: Builder -> (); + SearchMessages: Builder -> Vec; + SearchCommunity: User -> Vec; + PurgeUser: User -> (); + SetCommunityVoice: User -> Community; + ListAttachments: Builder -> Vec; + DeleteAttachment: Builder -> (); + GetStorageUsage: Builder -> StorageUsage; + GetDailyStats: Builder -> Vec; + SetGhost: Builder -> (); + CreateBackup: Builder -> BackupInfo; + ListBackups: Builder -> Vec; + DeleteBackup: Builder -> (); } diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 37525fc..b1eb1bd 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -8,8 +8,6 @@ pub mod frame; pub mod model; pub mod open; pub mod permission; -pub mod request; -pub mod response; pub mod session; pub mod share; pub mod time; diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs deleted file mode 100644 index d54052e..0000000 --- a/crates/common/src/request.rs +++ /dev/null @@ -1,315 +0,0 @@ -use bitcode::{Decode, Encode}; - -use crate::{ - model::{BanScope, Rank, ReportStatus, Role, ServerSettings}, - share::{Codec, Kind, Quality, Source}, -}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum LegacyRequest { - Register { - username: String, - password: String, - invite: Option, - }, - Login { - username: String, - password: String, - }, - Logout, - DeleteUser { - user_id: String, - }, - CreateCommunity { - name: String, - }, - ReadCommunity { - community_id: String, - }, - UpdateCommunity { - community_id: String, - name: String, - }, - UpdateCommunityAvatar { - community_id: String, - image: Option>, - }, - DeleteCommunity { - community_id: String, - }, - LeaveCommunity { - community_id: String, - }, - Communities, - Members { - community_id: String, - }, - Kick { - community_id: String, - user_id: String, - reason: Option, - }, - Ban { - community_id: String, - user_id: String, - reason: Option, - }, - Unban { - community_id: String, - user_id: String, - }, - Bans { - community_id: String, - }, - SetRank { - community_id: String, - user_id: String, - rank: Rank, - }, - CreateMessage { - community_id: String, - body: String, - attachments: Vec, - reply_to: Option, - }, - ForwardMessages { - message_ids: Vec, - community_id: String, - snippet: bool, - }, - UpdateMessage { - message_id: String, - body: String, - }, - DeleteMessage { - message_id: String, - }, - CreatePoll { - community_id: String, - question: String, - options: Vec, - multiple: bool, - }, - Vote { - message_id: String, - positions: Vec, - }, - ClosePoll { - message_id: String, - }, - React { - message_id: String, - emoji: String, - }, - Pin { - message_id: String, - pinned: bool, - }, - Pins { - community_id: String, - }, - WatchCommunity { - community_id: Option, - }, - ReadMessages { - community_id: String, - before: Option, - }, - Unreads, - MarkRead { - community_id: String, - message_id: String, - }, - Typing { - community_id: String, - }, - JoinVoice { - community_id: String, - }, - LeaveVoice, - StartShare { - kind: Kind, - source: Source, - }, - StopShare { - kind: Kind, - }, - Shares { - community_id: String, - }, - WatchShare { - user_id: String, - kind: Kind, - quality: Quality, - decode: Vec, - }, - UnwatchShare { - user_id: String, - kind: Kind, - }, - RequestKeyframe { - user_id: String, - kind: Kind, - }, - DeclineCall { - community_id: String, - }, - VoiceParticipants { - community_id: String, - }, - FindUser { - username: String, - }, - OpenDirect { - user_id: String, - }, - OpenNotes, - Friends, - AddFriend { - user_id: String, - }, - AcceptFriend { - user_id: String, - }, - RemoveFriend { - user_id: String, - }, - Invite { - community_id: String, - user_id: String, - }, - Invitations, - AcceptInvitation { - community_id: String, - }, - DeclineInvitation { - community_id: String, - }, - Logs { - community_id: String, - }, - Users, - SetRole { - user_id: String, - role: Role, - }, - AdminLogs { - actor_id: Option, - target_id: Option, - action: Option, - after_ms: Option, - before_ms: Option, - }, - Overview, - SuspendUser { - user_id: String, - suspended: bool, - }, - RevokeSessions { - user_id: String, - }, - ResetPassword { - user_id: String, - password: String, - }, - ClearProfile { - user_id: String, - }, - AllCommunities, - TransferOwnership { - community_id: String, - user_id: String, - }, - UpdateServerSettings { - settings: ServerSettings, - }, - CreateUser { - username: String, - password: String, - }, - RenameUser { - user_id: String, - username: String, - }, - TimeoutUser { - user_id: String, - minutes: u32, - }, - BanUser { - user_id: String, - reason: Option, - scope: BanScope, - }, - ServerBans, - RemoveServerBan { - id: String, - }, - CreateInviteCode { - uses: u32, - hours: Option, - }, - InviteCodes, - DeleteInviteCode { - code: String, - }, - ReportMessage { - message_id: String, - reason: String, - }, - ReportUser { - user_id: String, - reason: String, - }, - Reports { - status: Option, - }, - HandleReport { - report_id: String, - status: ReportStatus, - }, - SearchMessages { - text: Option, - user_id: Option, - community_id: Option, - after_ms: Option, - before_ms: Option, - }, - SearchCommunity { - community_id: String, - text: String, - }, - PurgeUser { - user_id: String, - }, - VoiceRooms, - KickFromVoice { - user_id: String, - }, - ServerMute { - user_id: String, - muted: bool, - }, - SetCommunityVoice { - community_id: String, - enabled: bool, - }, - AllAttachments { - user_id: Option, - community_id: Option, - }, - DeleteAttachment { - attachment_id: String, - }, - StorageUsage, - DailyStats { - days: u32, - }, - SetGhost { - enabled: bool, - }, - CreateBackup, - Backups, - DeleteBackup { - name: String, - }, -} diff --git a/crates/common/src/response.rs b/crates/common/src/response.rs deleted file mode 100644 index fabfc02..0000000 --- a/crates/common/src/response.rs +++ /dev/null @@ -1,56 +0,0 @@ -use bitcode::{Decode, Encode}; - -use crate::{ - model::{ - Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community, - CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, - Member, Message, MessageHit, Overview, Presence, Report, ServerBan, ServerSettings, - SessionInfo, Unread, Usage, User, VoiceRoom, - }, - share::Share, -}; - -#[derive(Debug, Clone, Encode, Decode)] -pub enum Response { - Session { - user: User, - token: String, - }, - User(User), - Avatar(Vec), - Community(Community), - Communities(Vec), - Members(Vec), - Bans(Vec), - Message(Message), - Messages(Vec), - Unreads(Vec), - Attachment(Attachment), - Voice(Vec), - Shares(Vec), - Friends(Friends), - Invitations(Vec), - Done, - Logs(Vec), - Users(Vec), - AdminLogs(Vec), - Overview(Overview), - AllCommunities(Vec), - ServerSettings(ServerSettings), - Sessions(Vec), - ServerBans(Vec), - InviteCode(InviteCode), - InviteCodes(Vec), - Reports(Vec), - MessageHits(Vec), - VoiceRooms(Vec), - AttachmentInfos(Vec), - StorageUsage { - users: Vec, - communities: Vec, - }, - DailyStats(Vec), - Backup(BackupInfo), - Backups(Vec), - Presences(Vec<(String, Presence)>), -} diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index fdb084d..e8d1b7e 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -671,19 +671,19 @@ mod tests { use std::io::Cursor; use common::{ + call::CreateMessage, model::{AttachmentKind, Rank}, open::Upload, - request::LegacyRequest, }; use image::{ImageFormat, RgbImage}; use crate::{ attachment::{store, thumb_path}, + call::{Cx, Handle, Me}, community, database, hub::{Client, Signed}, message, - network::Services, - request::handle, + network::{Services, Shared}, test, user, user_community, }; @@ -716,21 +716,22 @@ mod tests { user_id: user.id.clone(), token: "token".to_string(), })); - let (reply, _) = handle( - LegacyRequest::CreateMessage { - community_id: community.id.clone(), - body: String::new(), - attachments: vec![attachment.id.clone()], - reply_to: None, - }, - &client, - &db, - &Services::default(), - &test::directory(), - &test::directory(), - ) - .await; - reply.unwrap(); + let shared = Shared { + db: db.clone(), + services: Services::default(), + directory: test::directory(), + backups: test::directory(), + }; + let mut cx = Cx::new(&client, &shared, database::connect(&db).await.unwrap()); + CreateMessage { + community_id: community.id.clone(), + body: String::new(), + attachments: vec![attachment.id.clone()], + reply_to: None, + } + .handle(Me::User(user), &mut cx) + .await + .unwrap(); let messages = message::read_page(&community.id, None, &conn) .await diff --git a/crates/server/src/call/admin.rs b/crates/server/src/call/admin.rs new file mode 100644 index 0000000..f165a5b --- /dev/null +++ b/crates/server/src/call/admin.rs @@ -0,0 +1,814 @@ +use std::collections::BTreeMap; + +use common::{ + call::{ + BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment, + DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage, + ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes, + ListServerBans, ListUsers, Login, Logout, PurgeUser, Register, RemoveServerBan, RenameUser, + ResetPassword, RevokeSessions, SearchCommunity, SearchMessages, Session, SetCommunityVoice, + SetGhost, SetRole, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, + UpdateServerSettings, WatchCommunity, + }, + error::Error, + event::Event, + model::{ + Account, AdminAction, AdminLogEntry, AttachmentInfo, BackupInfo, BanScope, Community, + CommunitySummary, DayStat, InviteCode, LogAction, MessageHit, Overview, Rank, ServerBan, + ServerBanKind, ServerSettings, User, + }, + permission, + time::{self, MINUTE_MILLIS}, + transport::Close, + validate::{validate_reason, validate_server_settings}, +}; + +use crate::{ + admin_log, attachment, authentication, backup, + call::{Cx, Handle, Me}, + community, + error::ServerError, + invite, log, message, overview, + publish::{Broadcast, To}, + request::{ + allowed, call_ended, ensure, ensure_editable, is_outsider, leave_user_voice, limit_logins, + managed, message_event, record_ghost_voice, shares_ended, user_updated, voice_closed, + voice_joined, voice_silenced, voice_unmuted, + }, + server_ban, server_settings, stats, user, user_community, +}; + +impl Handle for Register { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?; + let (user, token) = authentication::register( + &self.username, + &self.password, + self.invite.as_deref(), + &mut cx.db, + ) + .await?; + + Ok(Session { user, token }) + } +} + +impl Handle for Login { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?; + let (user, token) = authentication::login(&self.username, &self.password, &cx.db).await?; + + Ok(Session { user, token }) + } +} + +impl Handle for Logout { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + me.user()?; + let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?; + authentication::logout(&signed.token, &cx.db).await?; + + Ok(()) + } +} + +impl Handle for UpdateServerSettings { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let settings = self.settings; + validate_server_settings(&settings)?; + server_settings::update(&settings, &cx.db).await?; + admin_log::record( + Some(&me.id), + None, + None, + &AdminAction::SettingsChanged, + &cx.db, + ) + .await?; + if settings.maintenance { + let builders = user::builder_ids(&cx.db).await?; + cx.sh + .services + .hub + .kick_all_except(&builders, Close::Maintenance); + } + cx.emit(To::Everyone, Event::SettingsUpdated(settings.clone())); + + Ok(settings) + } +} + +impl Handle for RenameUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let target = managed(&me, &self.user_id, &cx.db).await?; + let user = user::update(&self.user_id, &self.username, &cx.db).await?; + admin_log::record( + Some(&me.id), + Some(&self.user_id), + None, + &AdminAction::UserRenamed { + from: target.username, + }, + &cx.db, + ) + .await?; + cx.out.extend(user_updated(&user)); + + Ok(user) + } +} + +impl Handle for CreateUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let user = authentication::create_account(&self.username, &self.password, &cx.db).await?; + admin_log::record( + Some(&me.id), + Some(&user.id), + None, + &AdminAction::UserCreated, + &cx.db, + ) + .await?; + + Ok(user) + } +} + +impl Handle for ListUsers { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + user::all(&cx.db).await + } +} + +impl Handle for ListAdminLogs { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + admin_log::list( + self.actor_id.as_deref(), + self.target_id.as_deref(), + self.action.as_deref(), + self.after_ms, + self.before_ms, + &cx.db, + ) + .await + } +} + +impl Handle for GetDailyStats { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + stats::daily(self.days, &cx.db).await + } +} + +impl Handle for GetOverview { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + overview::read(&cx.sh.services.hub, &cx.sh.services.rooms, &cx.db).await + } +} + +impl Handle for SuspendUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + managed(&me, &self.user_id, &cx.db).await?; + user::set_suspended(&self.user_id, self.suspended, &cx.db).await?; + let action = if self.suspended { + AdminAction::UserSuspended + } else { + AdminAction::UserUnsuspended + }; + admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?; + if self.suspended { + authentication::revoke( + &cx.sh.services.hub, + authentication::Revoke::User(&self.user_id), + &cx.db, + ) + .await?; + } + + Ok(()) + } +} + +impl Handle for RevokeSessions { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + managed(&me, &self.user_id, &cx.db).await?; + authentication::revoke( + &cx.sh.services.hub, + authentication::Revoke::User(&self.user_id), + &cx.db, + ) + .await?; + admin_log::record( + Some(&me.id), + Some(&self.user_id), + None, + &AdminAction::SessionsRevoked, + &cx.db, + ) + .await?; + + Ok(()) + } +} + +impl Handle for ResetPassword { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + managed(&me, &self.user_id, &cx.db).await?; + authentication::reset_password(&self.user_id, &self.password, &cx.db).await?; + authentication::revoke( + &cx.sh.services.hub, + authentication::Revoke::User(&self.user_id), + &cx.db, + ) + .await?; + admin_log::record( + Some(&me.id), + Some(&self.user_id), + None, + &AdminAction::PasswordReset, + &cx.db, + ) + .await?; + + Ok(()) + } +} + +impl Handle for ClearProfile { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + managed(&me, &self.user_id, &cx.db).await?; + user::set_avatar(&self.user_id, None, &mut cx.db).await?; + let user = user::update_status(&self.user_id, "", &cx.db).await?; + admin_log::record( + Some(&me.id), + Some(&self.user_id), + None, + &AdminAction::ProfileCleared, + &cx.db, + ) + .await?; + cx.out.extend(user_updated(&user)); + + Ok(user) + } +} + +impl Handle for SetRole { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let Self { user_id, role } = self; + ensure(permission::can_set_role(me.role, me.id == user_id))?; + let user = user::set_role_by_id(&user_id, role, &cx.db).await?; + admin_log::record( + Some(&me.id), + Some(&user_id), + None, + &AdminAction::RoleChanged { role }, + &cx.db, + ) + .await?; + cx.out.extend(user_updated(&user)); + if permission::is_builder(role) { + let broadcasts = voice_unmuted(&cx.sh.services.rooms, &user_id, &cx.db).await?; + cx.out.extend(broadcasts); + } else { + user::set_ghost(&user_id, false, &cx.db).await?; + cx.sh.services.hub.kick_user(&user_id, Close::Revoked); + } + + Ok(user) + } +} + +impl Handle for DeleteUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let user_id = self.user_id; + let rooms = &cx.sh.services.rooms; + let target = user::read(&user_id, &cx.db).await?; + ensure(permission::can_delete_user( + me.role, + me.id == user_id, + target.role, + ))?; + let tx = cx.db.transaction().await?; + let mut broadcasts = Vec::new(); + if permission::is_builder(me.role) && me.id != user_id { + admin_log::record( + Some(&me.id), + Some(&user_id), + None, + &AdminAction::UserDeleted, + &tx, + ) + .await?; + } + for community_id in user_community::owned(&user_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::new(To::Users(member_ids), event)); + } + for community in community::communities_of(&user_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::new(To::Users(member_ids), event)); + } + broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?); + user::delete(&user_id, &tx).await?; + tx.commit().await?; + if me.id != user_id { + cx.sh.services.hub.kick_user(&user_id, Close::Revoked); + } + cx.out.extend(broadcasts); + + Ok(()) + } +} + +impl Handle for WatchCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let Some(community_id) = self.community_id else { + cx.client.watch(None); + return Ok(()); + }; + allowed(&me, &community_id, &cx.db, permission::can_read).await?; + let outsider = is_outsider(&me.id, &community_id, &cx.db).await?; + cx.client.watch(outsider.then_some(community_id.as_str())); + let visit = + permission::is_builder(me.role) && outsider && user::is_ghost(&me.id, &cx.db).await?; + if visit && cx.client.first_visit(&community_id) { + let community = community::label(&community_id, &cx.db).await?; + admin_log::record( + Some(&me.id), + None, + Some(&community), + &AdminAction::GhostVisit, + &cx.db, + ) + .await?; + } + + Ok(()) + } +} + +impl Handle for ListAllCommunities { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let mut summaries = Vec::new(); + for community in community::groups(&cx.db).await? { + let members = user_community::members(&community.id, &cx.db).await?; + let owner = members + .iter() + .find(|member| member.rank == Rank::Owner) + .map(|member| member.user.clone()); + summaries.push(CommunitySummary { + community, + owner, + members: members.len() as u64, + }); + } + + Ok(summaries) + } +} + +impl Handle for TransferOwnership { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let Self { + community_id, + user_id, + } = self; + ensure_editable(&community_id, &cx.db).await?; + allowed( + &me, + &community_id, + &cx.db, + permission::can_transfer_ownership, + ) + .await?; + let tx = cx.db.transaction().await?; + let members = user_community::members(&community_id, &tx).await?; + let target = members + .iter() + .find(|member| member.user.id == user_id) + .ok_or(Error::NotFound)?; + ensure(target.rank != Rank::Owner)?; + let mut changes = vec![(user_id.clone(), Rank::Owner)]; + if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) { + user_community::set_rank(&previous.user.id, &community_id, Rank::Admin, &tx).await?; + log::record( + &community_id, + Some(&me.id), + Some(&previous.user.id), + &LogAction::RankChanged { rank: Rank::Admin }, + &tx, + ) + .await?; + changes.push((previous.user.id.clone(), Rank::Admin)); + } + user_community::set_rank(&user_id, &community_id, Rank::Owner, &tx).await?; + log::record( + &community_id, + Some(&me.id), + Some(&user_id), + &LogAction::RankChanged { rank: Rank::Owner }, + &tx, + ) + .await?; + if permission::is_builder(me.role) { + let community = community::read(&community_id, &me.id, &tx).await?; + admin_log::record( + Some(&me.id), + Some(&user_id), + Some(&community.name), + &AdminAction::OwnershipTransferred, + &tx, + ) + .await?; + } + tx.commit().await?; + for (changed_id, rank) in changes { + cx.emit( + To::Community(community_id.clone()), + Event::RankChanged { + community_id: community_id.clone(), + user_id: changed_id, + rank, + }, + ); + } + + Ok(()) + } +} + +impl Handle for TimeoutUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let Self { user_id, minutes } = self; + managed(&me, &user_id, &cx.db).await?; + let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); + user::set_timeout(&user_id, until, &cx.db).await?; + if until.is_some() { + authentication::revoke( + &cx.sh.services.hub, + authentication::Revoke::User(&user_id), + &cx.db, + ) + .await?; + } + admin_log::record( + Some(&me.id), + Some(&user_id), + None, + &AdminAction::UserTimedOut { minutes }, + &cx.db, + ) + .await?; + + Ok(()) + } +} + +impl Handle for BanUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let Self { + user_id, + reason, + scope, + } = self; + let target = managed(&me, &user_id, &cx.db).await?; + validate_reason(reason.as_deref())?; + let tx = cx.db.transaction().await?; + user::set_suspended(&user_id, true, &tx).await?; + authentication::revoke_sessions(&user_id, &tx).await?; + server_ban::insert( + ServerBanKind::Username, + &target.username.to_ascii_lowercase(), + reason.as_deref(), + &me.id, + &tx, + ) + .await?; + if scope == BanScope::AccountAndIp + && let Some(address) = user::last_ip(&user_id, &tx).await? + { + server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx).await?; + } + admin_log::record( + Some(&me.id), + Some(&user_id), + None, + &AdminAction::UserBanned { reason }, + &tx, + ) + .await?; + tx.commit().await?; + cx.sh.services.hub.kick_user(&user_id, Close::Banned); + + Ok(()) + } +} + +impl Handle for ListServerBans { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + server_ban::list(&cx.db).await + } +} + +impl Handle for RemoveServerBan { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + server_ban::remove(&self.id, &cx.db).await?; + admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &cx.db).await?; + + Ok(()) + } +} + +impl Handle for CreateInviteCode { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + ensure(permission::is_builder(me.role) && self.uses > 0)?; + let code = invite::create(self.uses, self.hours, &me, &cx.db).await?; + admin_log::record( + Some(&me.id), + None, + None, + &AdminAction::InviteCreated, + &cx.db, + ) + .await?; + + Ok(code) + } +} + +impl Handle for ListInviteCodes { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + invite::list(&cx.db).await + } +} + +impl Handle for DeleteInviteCode { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + invite::delete(&self.code, &cx.db).await?; + admin_log::record( + Some(&me.id), + None, + None, + &AdminAction::InviteDeleted, + &cx.db, + ) + .await?; + + Ok(()) + } +} + +impl Handle for SearchMessages { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + message::search( + self.text.as_deref(), + self.user_id.as_deref(), + self.community_id.as_deref(), + self.after_ms, + self.before_ms, + &cx.db, + ) + .await + } +} + +impl Handle for SearchCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + message::search( + Some(&self.text), + None, + Some(&self.community_id), + None, + None, + &cx.db, + ) + .await + } +} + +impl Handle for PurgeUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let user_id = self.user_id; + managed(&me, &user_id, &cx.db).await?; + let tx = cx.db.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 deleted: BTreeMap> = BTreeMap::new(); + for message_id in &message_ids { + let message = message::delete(message_id, &tx).await?; + deleted + .entry(message.community_id) + .or_default() + .push(message.id); + } + attachment::delete_uploads(&user_id, &tx).await?; + admin_log::record( + Some(&me.id), + Some(&user_id), + None, + &AdminAction::UserPurged { + messages: message_ids.len() as u64, + }, + &tx, + ) + .await?; + tx.commit().await?; + attachment::remove_files(&upload_ids, &cx.sh.directory); + for (community_id, ids) in deleted { + cx.emit( + To::Community(community_id.clone()), + Event::MessagesDeleted { community_id, ids }, + ); + } + + Ok(()) + } +} + +impl Handle for ListAttachments { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + attachment::all( + self.user_id.as_deref(), + self.community_id.as_deref(), + &cx.db, + ) + .await + } +} + +impl Handle for DeleteAttachment { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let attachment_id = self.attachment_id; + let stored = attachment::read(&attachment_id, &cx.db).await?; + let community = community::label(&stored.community_id, &cx.db).await?; + let tx = cx.db.transaction().await?; + attachment::delete(&attachment_id, &tx).await?; + admin_log::record( + Some(&me.id), + Some(&stored.uploader_id), + Some(&community), + &AdminAction::AttachmentDeleted, + &tx, + ) + .await?; + let mut broadcast = None; + if let Some(message_id) = &stored.message_id { + let updated = message::read(message_id, &tx).await?; + broadcast = Some(message_event(&updated, Event::MessageUpdated)); + } + tx.commit().await?; + attachment::remove_files(&[attachment_id], &cx.sh.directory); + cx.out.extend(broadcast); + + Ok(()) + } +} + +impl Handle for GetStorageUsage { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + let (users, communities) = attachment::usage(&cx.db).await?; + + Ok(StorageUsage { users, communities }) + } +} + +impl Handle for CreateBackup { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let backup = backup::create(&cx.db, &cx.sh.backups).await?; + let action = AdminAction::BackupCreated { + name: backup.name.clone(), + }; + admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; + + Ok(backup) + } +} + +impl Handle for ListBackups { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + backup::list(&cx.sh.backups) + } +} + +impl Handle for DeleteBackup { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + backup::delete(&self.name, &cx.sh.backups)?; + let action = AdminAction::BackupDeleted { name: self.name }; + admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; + + Ok(()) + } +} + +impl Handle for SetCommunityVoice { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let Self { + community_id, + enabled, + } = self; + allowed(&me, &community_id, &cx.db, permission::can_manage_voice).await?; + let tx = cx.db.transaction().await?; + community::set_voice_enabled(&community_id, enabled, &tx).await?; + let updated = community::read(&community_id, &me.id, &tx).await?; + if permission::is_builder(me.role) { + admin_log::record( + Some(&me.id), + None, + Some(&updated.name), + &AdminAction::CommunityVoiceSet { enabled }, + &tx, + ) + .await?; + } + tx.commit().await?; + if !enabled { + let broadcasts = voice_silenced(&cx.sh.services.rooms, &community_id, &cx.db).await?; + cx.out.extend(broadcasts); + } + cx.emit( + To::Community(community_id), + Event::CommunityUpdated(updated.clone()), + ); + + Ok(updated) + } +} + +impl Handle for SetGhost { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let enabled = self.enabled; + let rooms = &cx.sh.services.rooms; + user::set_ghost(&me.id, enabled, &cx.db).await?; + let action = if enabled { + AdminAction::GhostEnabled + } else { + AdminAction::GhostDisabled + }; + admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; + let mut broadcasts = Vec::new(); + let outsider = match rooms.room_of(&me.id) { + Some(community_id) => is_outsider(&me.id, &community_id, &cx.db).await?, + None => false, + }; + if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) { + let community_id = departure.community_id.clone(); + if enabled { + broadcasts.extend(shares_ended(&mut departure)); + broadcasts + .extend(call_ended(&community_id, &me.id, departure.call_log, &cx.db).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, &cx.db).await?; + broadcasts.extend(voice_joined(&community_id, &me.id, muted)); + if let Some(seconds) = departure.ghost_seconds { + record_ghost_voice(&me.id, &community_id, seconds, &cx.db).await?; + } + } + } + cx.out.extend(broadcasts); + + Ok(()) + } +} diff --git a/crates/server/src/call/community.rs b/crates/server/src/call/community.rs new file mode 100644 index 0000000..40c4fea --- /dev/null +++ b/crates/server/src/call/community.rs @@ -0,0 +1,363 @@ +use common::{ + call::{ + BanMember, CreateCommunity, DeleteCommunity, GetCommunity, Kick, LeaveCommunity, ListBans, + ListCommunities, ListLogs, ListMembers, SetRank, Unban, UpdateCommunity, + UpdateCommunityAvatar, + }, + error::Error, + event::Event, + model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User}, + permission, + validate::{validate_avatar_size, validate_reason}, +}; + +use crate::{ + admin_log, + call::{Cx, Handle, Me}, + community, + error::ServerError, + log, + publish::To, + request::{ + actor_rank, allowed, ensure, ensure_editable, ensure_with, leave_room_voice, voice_closed, + }, + server_settings, user, user_community, +}; + +struct Removal { + community_id: String, + user_id: String, + reason: Option, + sanction: Sanction, +} + +async fn remove_member(me: &User, removal: Removal, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let Removal { + community_id, + user_id, + reason, + sanction, + } = removal; + validate_reason(reason.as_deref())?; + ensure_editable(&community_id, &cx.db).await?; + let target = user::read(&user_id, &cx.db).await?; + ensure(permission::can_moderate( + actor_rank(me, &community_id, &cx.db).await?, + actor_rank(&target, &community_id, &cx.db).await?, + ))?; + let community = community::read(&community_id, &me.id, &cx.db).await?; + let tx = cx.db.transaction().await?; + user_community::leave(&user_id, &community_id, &tx).await?; + let action = match sanction { + Sanction::Ban => { + user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?; + LogAction::Banned { + reason: reason.clone(), + } + } + Sanction::Kick => LogAction::Kicked { + reason: reason.clone(), + }, + }; + log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; + tx.commit().await?; + let broadcasts = + leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?; + cx.out.extend(broadcasts); + cx.emit( + To::User(user_id.clone()), + Event::Removed { + community_id: community_id.clone(), + community_name: community.name, + sanction, + reason, + }, + ); + cx.emit( + To::Community(community_id.clone()), + Event::MemberLeft { + community_id, + user_id, + }, + ); + + Ok(()) +} + +impl Handle for CreateCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let limit = server_settings::read(&cx.db) + .await? + .max_communities_per_user; + let owned = user_community::owned_groups(&me.id, &cx.db).await?; + ensure_with(limit == 0 || owned < limit as usize, Error::LimitReached)?; + let tx = cx.db.transaction().await?; + let community = community::create(&self.name, &tx).await?; + user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?; + log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?; + tx.commit().await?; + + Ok(community) + } +} + +impl Handle for GetCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + community::read(&self.community_id, &me.id, &cx.db).await + } +} + +impl Handle for UpdateCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + ensure_editable(&self.community_id, &cx.db).await?; + allowed( + &me, + &self.community_id, + &cx.db, + permission::can_rename_community, + ) + .await?; + let updated = community::update(&self.community_id, &self.name, &me.id, &cx.db).await?; + let action = LogAction::Renamed { + name: updated.name.clone(), + }; + log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?; + cx.emit( + To::Community(self.community_id), + Event::CommunityUpdated(updated.clone()), + ); + + Ok(updated) + } +} + +impl Handle for UpdateCommunityAvatar { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + ensure_editable(&self.community_id, &cx.db).await?; + allowed( + &me, + &self.community_id, + &cx.db, + permission::can_rename_community, + ) + .await?; + if let Some(bytes) = &self.image { + validate_avatar_size(bytes, server_settings::read(&cx.db).await?.max_avatar_bytes)?; + } + let updated = community::set_avatar( + &self.community_id, + self.image.as_deref(), + &me.id, + &mut cx.db, + ) + .await?; + let action = if self.image.is_some() { + LogAction::AvatarChanged + } else { + LogAction::AvatarRemoved + }; + log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?; + cx.emit( + To::Community(self.community_id), + Event::CommunityUpdated(updated.clone()), + ); + + Ok(updated) + } +} + +impl Handle for DeleteCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + ensure_editable(&self.community_id, &cx.db).await?; + allowed( + &me, + &self.community_id, + &cx.db, + permission::can_delete_community, + ) + .await?; + let tx = cx.db.transaction().await?; + let member_ids = user_community::member_ids(&self.community_id, &tx).await?; + let owned = + user_community::rank(&me.id, &self.community_id, &tx).await? == Some(Rank::Owner); + let deleted = community::delete(&self.community_id, &me.id, &tx).await?; + if permission::is_builder(me.role) && !owned { + admin_log::record( + Some(&me.id), + None, + Some(&deleted.name), + &AdminAction::CommunityDeleted, + &tx, + ) + .await?; + } + tx.commit().await?; + let broadcasts = voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?; + cx.out.extend(broadcasts); + cx.emit( + To::Users(member_ids), + Event::CommunityDeleted { + community_id: deleted.id.clone(), + }, + ); + + Ok(()) + } +} + +impl Handle for LeaveCommunity { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + ensure_editable(&self.community_id, &cx.db).await?; + allowed(&me, &self.community_id, &cx.db, permission::can_leave).await?; + let tx = cx.db.transaction().await?; + user_community::leave(&me.id, &self.community_id, &tx).await?; + log::record( + &self.community_id, + Some(&me.id), + None, + &LogAction::Left, + &tx, + ) + .await?; + if user_community::member_ids(&self.community_id, &tx) + .await? + .is_empty() + { + community::delete(&self.community_id, &me.id, &tx).await?; + } + tx.commit().await?; + let broadcasts = + leave_room_voice(&cx.sh.services.rooms, &self.community_id, &me.id, &cx.db).await?; + cx.out.extend(broadcasts); + cx.emit( + To::Community(self.community_id.clone()), + Event::MemberLeft { + community_id: self.community_id, + user_id: me.id, + }, + ); + + Ok(()) + } +} + +impl Handle for ListCommunities { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + + community::communities_of(&me.id, &cx.db).await + } +} + +impl Handle for ListMembers { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + user_community::members(&self.community_id, &cx.db).await + } +} + +impl Handle for Kick { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let removal = Removal { + community_id: self.community_id, + user_id: self.user_id, + reason: self.reason, + sanction: Sanction::Kick, + }; + + remove_member(&me, removal, cx).await + } +} + +impl Handle for BanMember { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let removal = Removal { + community_id: self.community_id, + user_id: self.user_id, + reason: self.reason, + sanction: Sanction::Ban, + }; + + remove_member(&me, removal, cx).await + } +} + +impl Handle for Unban { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?; + user_community::unban(&self.user_id, &self.community_id, &cx.db).await?; + log::record( + &self.community_id, + Some(&me.id), + Some(&self.user_id), + &LogAction::Unbanned, + &cx.db, + ) + .await?; + + Ok(()) + } +} + +impl Handle for ListBans { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?; + + user_community::bans(&self.community_id, &cx.db).await + } +} + +impl Handle for SetRank { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + ensure_editable(&self.community_id, &cx.db).await?; + let target = user::read(&self.user_id, &cx.db).await?; + ensure(permission::can_set_rank( + actor_rank(&me, &self.community_id, &cx.db).await?, + actor_rank(&target, &self.community_id, &cx.db).await?, + self.rank, + ))?; + user_community::set_rank(&self.user_id, &self.community_id, self.rank, &cx.db).await?; + log::record( + &self.community_id, + Some(&me.id), + Some(&self.user_id), + &LogAction::RankChanged { rank: self.rank }, + &cx.db, + ) + .await?; + cx.emit( + To::Community(self.community_id.clone()), + Event::RankChanged { + community_id: self.community_id, + user_id: self.user_id, + rank: self.rank, + }, + ); + + Ok(()) + } +} + +impl Handle for ListLogs { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read_logs).await?; + + log::list(&self.community_id, &cx.db).await + } +} diff --git a/crates/server/src/call/message.rs b/crates/server/src/call/message.rs new file mode 100644 index 0000000..2d4199b --- /dev/null +++ b/crates/server/src/call/message.rs @@ -0,0 +1,322 @@ +use common::{ + call::{ + ClosePoll, CreateMessage, CreatePoll, DeleteMessage, ForwardMessages, ListMessages, + ListPins, ListUnreads, MarkRead, Pin, React, Typing, UpdateMessage, Vote, + }, + error::Error, + event::Event, + model::{AdminAction, LogAction, Message, ServerSettings, Unread, User}, + permission, + validate::{ + validate_forward, validate_new_message, validate_poll, validate_reaction, validate_vote, + }, +}; + +use crate::{ + admin_log, + call::{Cx, Handle, Me}, + community, + error::ServerError, + log, message, + publish::To, + request::{actor_rank, allowed, ensure, is_outsider}, + server_settings, stats, user, user_community, +}; + +fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(), ServerError> { + if permission::is_builder(me.role) { + return Ok(()); + } + + Ok(cx + .sh + .services + .rate_limit + .allow(&me.id, settings.messages_per_minute)?) +} + +fn emit_message(message: &Message, event: fn(Message) -> Event, cx: &mut Cx<'_>) { + cx.emit( + To::Community(message.community_id.clone()), + event(message.clone()), + ); +} + +impl Handle for CreateMessage { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let settings = server_settings::read(&cx.db).await?; + limit_messages(&me, &settings, cx)?; + validate_new_message( + &self.body, + self.attachments.len(), + settings.max_message_length as usize, + )?; + allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; + let tx = cx.db.transaction().await?; + let created = message::create( + &me.id, + &self.community_id, + &self.body, + &self.attachments, + self.reply_to.as_deref(), + &tx, + ) + .await?; + stats::mark_active(&me.id, &tx).await?; + tx.commit().await?; + emit_message(&created, Event::MessageCreated, cx); + + Ok(created) + } +} + +impl Handle for ForwardMessages { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?; + validate_forward(self.message_ids.len())?; + ensure(permission::can_post( + actor_rank(&me, &self.community_id, &cx.db).await?, + ))?; + let tx = cx.db.transaction().await?; + let mut sources = Vec::new(); + for message_id in &self.message_ids { + let source = message::read(message_id, &tx).await?; + ensure(permission::can_read( + actor_rank(&me, &source.community_id, &tx).await?, + ))?; + sources.push(source); + } + let mode = if self.snippet { + message::ForwardMode::Snippet + } else { + message::ForwardMode::Copy + }; + let created = message::forward( + &me, + &self.community_id, + &sources, + mode, + &cx.sh.directory, + &tx, + ) + .await?; + tx.commit().await?; + for message in &created { + emit_message(message, Event::MessageCreated, cx); + } + + Ok(created) + } +} + +impl Handle for UpdateMessage { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let existing = message::read(&self.message_id, &cx.db).await?; + allowed(&me, &existing.community_id, &cx.db, permission::can_post).await?; + ensure(existing.user_id == me.id)?; + validate_new_message( + &self.body, + 0, + server_settings::read(&cx.db).await?.max_message_length as usize, + )?; + let updated = message::update(&self.message_id, &self.body, &cx.db).await?; + emit_message(&updated, Event::MessageUpdated, cx); + + Ok(updated) + } +} + +impl Handle for DeleteMessage { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let existing = message::read(&self.message_id, &cx.db).await?; + let author = user::read(&existing.user_id, &cx.db).await?; + ensure(permission::can_delete_message( + actor_rank(&me, &existing.community_id, &cx.db).await?, + actor_rank(&author, &existing.community_id, &cx.db).await?, + existing.user_id == me.id, + ))?; + let deleted = message::delete(&self.message_id, &cx.db).await?; + if existing.user_id != me.id { + log::record( + &deleted.community_id, + Some(&me.id), + Some(&existing.user_id), + &LogAction::MessageDeleted, + &cx.db, + ) + .await?; + } + if permission::is_builder(me.role) && existing.user_id != me.id { + let community = community::label(&deleted.community_id, &cx.db).await?; + admin_log::record( + Some(&me.id), + Some(&existing.user_id), + Some(&community), + &AdminAction::MessageDeleted, + &cx.db, + ) + .await?; + } + cx.emit( + To::Community(deleted.community_id.clone()), + Event::MessagesDeleted { + community_id: deleted.community_id, + ids: vec![deleted.id], + }, + ); + + Ok(()) + } +} + +impl Handle for CreatePoll { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let settings = server_settings::read(&cx.db).await?; + limit_messages(&me, &settings, cx)?; + validate_poll(&self.question, &self.options)?; + allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; + let tx = cx.db.transaction().await?; + let created = message::create_poll( + &me.id, + &self.community_id, + &self.question, + &self.options, + self.multiple, + &tx, + ) + .await?; + stats::mark_active(&me.id, &tx).await?; + tx.commit().await?; + emit_message(&created, Event::MessageCreated, cx); + + Ok(created) + } +} + +impl Handle for Vote { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let existing = message::read(&self.message_id, &cx.db).await?; + ensure(permission::can_read( + actor_rank(&me, &existing.community_id, &cx.db).await?, + ))?; + let poll = existing.poll.as_ref().ok_or(Error::NotFound)?; + validate_vote(poll, &self.positions)?; + let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?; + emit_message(&updated, Event::MessageUpdated, cx); + + Ok(()) + } +} + +impl Handle for ClosePoll { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let existing = message::read(&self.message_id, &cx.db).await?; + ensure(permission::can_close_poll( + actor_rank(&me, &existing.community_id, &cx.db).await?, + existing.user_id == me.id, + ))?; + let updated = message::close_poll(&self.message_id, &cx.db).await?; + emit_message(&updated, Event::MessageUpdated, cx); + + Ok(()) + } +} + +impl Handle for React { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + validate_reaction(&self.emoji)?; + let existing = message::read(&self.message_id, &cx.db).await?; + ensure(permission::can_read( + actor_rank(&me, &existing.community_id, &cx.db).await?, + ))?; + let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?; + emit_message(&updated, Event::MessageUpdated, cx); + + Ok(()) + } +} + +impl Handle for Pin { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let existing = message::read(&self.message_id, &cx.db).await?; + let direct = community::is_direct(&existing.community_id, &cx.db).await?; + ensure(permission::can_pin( + actor_rank(&me, &existing.community_id, &cx.db).await?, + direct, + ))?; + let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?; + emit_message(&updated, Event::MessageUpdated, cx); + + Ok(()) + } +} + +impl Handle for ListPins { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + message::pinned(&self.community_id, &cx.db).await + } +} + +impl Handle for ListMessages { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + message::read_page(&self.community_id, self.before.as_deref(), &cx.db).await + } +} + +impl Handle for ListUnreads { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + + user_community::unreads(&me.id, &me.username, &cx.db).await + } +} + +impl Handle for MarkRead { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + ensure(!is_outsider(&me.id, &self.community_id, &cx.db).await?)?; + message::ensure_in_community(&self.message_id, &self.community_id, &cx.db).await?; + user_community::mark_read(&me.id, &self.community_id, &self.message_id, &cx.db).await?; + + Ok(()) + } +} + +impl Handle for Typing { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + if user::is_ghost(&me.id, &cx.db).await? { + return Ok(()); + } + let others: Vec = user_community::member_ids(&self.community_id, &cx.db) + .await? + .into_iter() + .filter(|user_id| *user_id != me.id) + .collect(); + cx.emit( + To::Users(others), + Event::Typing { + community_id: self.community_id, + user_id: me.id, + }, + ); + + Ok(()) + } +} diff --git a/crates/server/src/call/mod.rs b/crates/server/src/call/mod.rs index a74a861..5b1e31a 100644 --- a/crates/server/src/call/mod.rs +++ b/crates/server/src/call/mod.rs @@ -1,9 +1,14 @@ +mod admin; +mod community; +mod message; +mod social; mod user; +mod voice; use std::{future::Future, sync::Arc}; use common::{ - call::{Call, Gate, Legacy, Request}, + call::{Call, Gate, Request}, error::Error, event::Event, frame::{self, DOWN_MAX}, @@ -90,7 +95,6 @@ async fn serve(call: C, cx: &mut Cx<'_>) -> Vec { pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { match request { - Request::Legacy(call) => serve(call, cx).await, Request::GetSettings(call) => serve(call, cx).await, Request::GetUser(call) => serve(call, cx).await, Request::UpdateUser(call) => serve(call, cx).await, @@ -102,22 +106,98 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { Request::GetAvatar(call) => serve(call, cx).await, Request::ListSessions(call) => serve(call, cx).await, Request::RevokeSession(call) => serve(call, cx).await, - } -} - -impl Handle for Legacy { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - let (reply, broadcasts) = request::dispatch( - self.0, - cx.client, - &cx.sh.db, - &cx.sh.services, - &cx.sh.directory, - &cx.sh.backups, - ) - .await?; - cx.out.extend(broadcasts); - - Ok(reply) + Request::CreateCommunity(call) => serve(call, cx).await, + Request::GetCommunity(call) => serve(call, cx).await, + Request::UpdateCommunity(call) => serve(call, cx).await, + Request::UpdateCommunityAvatar(call) => serve(call, cx).await, + Request::DeleteCommunity(call) => serve(call, cx).await, + Request::LeaveCommunity(call) => serve(call, cx).await, + Request::ListCommunities(call) => serve(call, cx).await, + Request::ListMembers(call) => serve(call, cx).await, + Request::Kick(call) => serve(call, cx).await, + Request::BanMember(call) => serve(call, cx).await, + Request::Unban(call) => serve(call, cx).await, + Request::ListBans(call) => serve(call, cx).await, + Request::SetRank(call) => serve(call, cx).await, + Request::ListLogs(call) => serve(call, cx).await, + Request::CreateMessage(call) => serve(call, cx).await, + Request::ForwardMessages(call) => serve(call, cx).await, + Request::UpdateMessage(call) => serve(call, cx).await, + Request::DeleteMessage(call) => serve(call, cx).await, + Request::CreatePoll(call) => serve(call, cx).await, + Request::Vote(call) => serve(call, cx).await, + Request::ClosePoll(call) => serve(call, cx).await, + Request::React(call) => serve(call, cx).await, + Request::Pin(call) => serve(call, cx).await, + Request::ListPins(call) => serve(call, cx).await, + Request::ListMessages(call) => serve(call, cx).await, + Request::ListUnreads(call) => serve(call, cx).await, + Request::MarkRead(call) => serve(call, cx).await, + Request::Typing(call) => serve(call, cx).await, + Request::FindUser(call) => serve(call, cx).await, + Request::OpenDirect(call) => serve(call, cx).await, + Request::OpenNotes(call) => serve(call, cx).await, + Request::ListFriends(call) => serve(call, cx).await, + Request::AddFriend(call) => serve(call, cx).await, + Request::AcceptFriend(call) => serve(call, cx).await, + Request::RemoveFriend(call) => serve(call, cx).await, + Request::Invite(call) => serve(call, cx).await, + Request::ListInvitations(call) => serve(call, cx).await, + Request::AcceptInvitation(call) => serve(call, cx).await, + Request::DeclineInvitation(call) => serve(call, cx).await, + Request::ReportMessage(call) => serve(call, cx).await, + Request::ReportUser(call) => serve(call, cx).await, + Request::ListReports(call) => serve(call, cx).await, + Request::HandleReport(call) => serve(call, cx).await, + Request::JoinVoice(call) => serve(call, cx).await, + Request::LeaveVoice(call) => serve(call, cx).await, + Request::StartShare(call) => serve(call, cx).await, + Request::StopShare(call) => serve(call, cx).await, + Request::ListShares(call) => serve(call, cx).await, + Request::WatchShare(call) => serve(call, cx).await, + Request::UnwatchShare(call) => serve(call, cx).await, + Request::RequestKeyframe(call) => serve(call, cx).await, + Request::DeclineCall(call) => serve(call, cx).await, + Request::ListVoiceParticipants(call) => serve(call, cx).await, + Request::ListVoiceRooms(call) => serve(call, cx).await, + Request::KickFromVoice(call) => serve(call, cx).await, + Request::ServerMute(call) => serve(call, cx).await, + Request::Register(call) => serve(call, cx).await, + Request::Login(call) => serve(call, cx).await, + Request::Logout(call) => serve(call, cx).await, + Request::DeleteUser(call) => serve(call, cx).await, + Request::WatchCommunity(call) => serve(call, cx).await, + Request::ListUsers(call) => serve(call, cx).await, + Request::SetRole(call) => serve(call, cx).await, + Request::ListAdminLogs(call) => serve(call, cx).await, + Request::GetOverview(call) => serve(call, cx).await, + Request::SuspendUser(call) => serve(call, cx).await, + Request::RevokeSessions(call) => serve(call, cx).await, + Request::ResetPassword(call) => serve(call, cx).await, + Request::ClearProfile(call) => serve(call, cx).await, + Request::ListAllCommunities(call) => serve(call, cx).await, + Request::TransferOwnership(call) => serve(call, cx).await, + Request::UpdateServerSettings(call) => serve(call, cx).await, + Request::CreateUser(call) => serve(call, cx).await, + Request::RenameUser(call) => serve(call, cx).await, + Request::TimeoutUser(call) => serve(call, cx).await, + Request::BanUser(call) => serve(call, cx).await, + Request::ListServerBans(call) => serve(call, cx).await, + Request::RemoveServerBan(call) => serve(call, cx).await, + Request::CreateInviteCode(call) => serve(call, cx).await, + Request::ListInviteCodes(call) => serve(call, cx).await, + Request::DeleteInviteCode(call) => serve(call, cx).await, + Request::SearchMessages(call) => serve(call, cx).await, + Request::SearchCommunity(call) => serve(call, cx).await, + Request::PurgeUser(call) => serve(call, cx).await, + Request::SetCommunityVoice(call) => serve(call, cx).await, + Request::ListAttachments(call) => serve(call, cx).await, + Request::DeleteAttachment(call) => serve(call, cx).await, + Request::GetStorageUsage(call) => serve(call, cx).await, + Request::GetDailyStats(call) => serve(call, cx).await, + Request::SetGhost(call) => serve(call, cx).await, + Request::CreateBackup(call) => serve(call, cx).await, + Request::ListBackups(call) => serve(call, cx).await, + Request::DeleteBackup(call) => serve(call, cx).await, } } diff --git a/crates/server/src/call/social.rs b/crates/server/src/call/social.rs new file mode 100644 index 0000000..4420309 --- /dev/null +++ b/crates/server/src/call/social.rs @@ -0,0 +1,271 @@ +use common::{ + call::{ + AcceptFriend, AcceptInvitation, AddFriend, DeclineInvitation, FindUser, HandleReport, + Invite, ListFriends, ListInvitations, ListReports, OpenDirect, OpenNotes, RemoveFriend, + ReportMessage, ReportUser, + }, + error::Error, + event::Event, + model::{ + AdminAction, Community, Friends, Invitation, LogAction, Member, Rank, Report, ReportStatus, + User, + }, + permission, + validate::validate_reason, +}; + +use crate::{ + admin_log, + call::{Cx, Handle, Me}, + community, direct, + error::ServerError, + friend, invitation, log, message, notes, + publish::To, + report, + request::{actor_rank, allowed, ensure, ensure_editable, ensure_with}, + user, user_community, +}; + +async fn friends_updated(user_ids: [&str; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> { + for user_id in user_ids { + let event = Event::FriendsUpdated(friend::state(user_id, &cx.db).await?); + cx.emit(To::User(user_id.to_string()), event); + } + + Ok(()) +} + +async fn invitations_updated(user_id: &str, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let event = Event::InvitationsUpdated(invitation::of(user_id, &cx.db).await?); + cx.emit(To::User(user_id.to_string()), event); + + Ok(()) +} + +impl Handle for FindUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + + user::by_username(&self.username, &cx.db) + .await? + .filter(|found| found.id != me.id) + .ok_or(Error::NotFound.into()) + } +} + +impl Handle for OpenDirect { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + match direct::open(&me.id, &self.user_id, &mut cx.db).await? { + direct::Opening::Created(community) => { + let peer_view = community::read(&community.id, &self.user_id, &cx.db).await?; + cx.emit(To::User(self.user_id), Event::CommunityAdded(peer_view)); + + Ok(community) + } + direct::Opening::Existing(community) => Ok(community), + } + } +} + +impl Handle for OpenNotes { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + + notes::open(&me.id, &mut cx.db).await + } +} + +impl Handle for ListFriends { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + + friend::state(&me.id, &cx.db).await + } +} + +impl Handle for AddFriend { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + friend::add(&me.id, &self.user_id, &mut cx.db).await?; + + friends_updated([&me.id, &self.user_id], cx).await + } +} + +impl Handle for AcceptFriend { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + friend::accept(&me.id, &self.user_id, &mut cx.db).await?; + + friends_updated([&me.id, &self.user_id], cx).await + } +} + +impl Handle for RemoveFriend { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + friend::remove(&me.id, &self.user_id, &mut cx.db).await?; + + friends_updated([&me.id, &self.user_id], cx).await + } +} + +impl Handle for Invite { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + ensure_editable(&self.community_id, &cx.db).await?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + let target = user::read(&self.user_id, &cx.db).await?; + if user_community::rank(&self.user_id, &self.community_id, &cx.db) + .await? + .is_some() + { + return Err(Error::AlreadyMember.into()); + } + let banned = user_community::is_banned(&self.user_id, &self.community_id, &cx.db).await?; + ensure(permission::can_join(target.role, banned))?; + if invitation::exists(&self.community_id, &self.user_id, &cx.db).await? { + return Err(Error::AlreadyInvited.into()); + } + invitation::insert(&self.community_id, &self.user_id, &me.id, &cx.db).await?; + log::record( + &self.community_id, + Some(&me.id), + Some(&self.user_id), + &LogAction::Invited, + &cx.db, + ) + .await?; + + invitations_updated(&self.user_id, cx).await + } +} + +impl Handle for ListInvitations { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + + invitation::of(&me.id, &cx.db).await + } +} + +impl Handle for AcceptInvitation { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { + let me = me.user()?; + let tx = cx.db.transaction().await?; + invitation::take(&self.community_id, &me.id, &tx).await?; + let banned = user_community::is_banned(&me.id, &self.community_id, &tx).await?; + ensure(permission::can_join(me.role, banned))?; + user_community::join(&me.id, &self.community_id, Rank::Member, &tx).await?; + log::record( + &self.community_id, + Some(&me.id), + None, + &LogAction::Joined, + &tx, + ) + .await?; + let community = community::read(&self.community_id, &me.id, &tx).await?; + tx.commit().await?; + let event = Event::MemberJoined { + community_id: self.community_id.clone(), + member: Member { + user: me.clone(), + rank: Rank::Member, + }, + }; + cx.emit(To::Community(self.community_id), event); + invitations_updated(&me.id, cx).await?; + + Ok(community) + } +} + +impl Handle for DeclineInvitation { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + invitation::take(&self.community_id, &me.id, &cx.db).await?; + + invitations_updated(&me.id, cx).await + } +} + +impl Handle for ReportMessage { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let message = message::read(&self.message_id, &cx.db).await?; + let actor = actor_rank(&me, &message.community_id, &cx.db).await?; + ensure(permission::can_read(actor) && me.id != message.user_id)?; + validate_reason(Some(&self.reason))?; + ensure_with( + !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?, + Error::Taken, + )?; + report::insert( + &me.id, + &message.user_id, + Some(&self.message_id), + Some(&message.community_id), + Some(&message.body), + &self.reason, + &cx.db, + ) + .await?; + cx.emit(To::Builders, Event::ReportCreated); + + Ok(()) + } +} + +impl Handle for ReportUser { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + user::read(&self.user_id, &cx.db).await?; + ensure(me.id != self.user_id)?; + validate_reason(Some(&self.reason))?; + ensure_with( + !report::is_open(&me.id, &self.user_id, None, &cx.db).await?, + Error::Taken, + )?; + report::insert( + &me.id, + &self.user_id, + None, + None, + None, + &self.reason, + &cx.db, + ) + .await?; + cx.emit(To::Builders, Event::ReportCreated); + + Ok(()) + } +} + +impl Handle for ListReports { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + report::list(self.status, &cx.db).await + } +} + +impl Handle for HandleReport { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + ensure(permission::is_builder(me.role) && self.status != ReportStatus::Open)?; + let target = report::handle(&self.report_id, self.status, &me.id, &cx.db).await?; + admin_log::record( + Some(&me.id), + target.as_deref(), + None, + &AdminAction::ReportHandled { + status: self.status, + }, + &cx.db, + ) + .await?; + + Ok(()) + } +} diff --git a/crates/server/src/call/voice.rs b/crates/server/src/call/voice.rs new file mode 100644 index 0000000..712dc40 --- /dev/null +++ b/crates/server/src/call/voice.rs @@ -0,0 +1,249 @@ +use common::{ + call::{ + DeclineCall, JoinVoice, KickFromVoice, LeaveVoice, ListShares, ListVoiceParticipants, + ListVoiceRooms, RequestKeyframe, ServerMute, StartShare, StopShare, UnwatchShare, + WatchShare, + }, + error::Error, + event::Event, + model::{AdminAction, CallLog, VoiceRoom}, + permission, + share::Share, +}; + +use crate::{ + admin_log, + call::{Cx, Handle, Me}, + community, + error::ServerError, + message, + publish::{Broadcast, To}, + request::{ + allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event, + share_ended, voice_joined, voice_muted, voice_rooms, + }, + user, +}; + +impl Handle for JoinVoice { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + let community_id = self.community_id; + let rooms = &cx.sh.services.rooms; + allowed(&me, &community_id, &cx.db, permission::can_join_voice).await?; + ensure(community::kind(&community_id, &cx.db).await? != community::Kind::Notes)?; + ensure( + permission::is_builder(me.role) + || community::voice_enabled(&community_id, &cx.db).await?, + )?; + let muted = user::voice_muted(&me.id, &cx.db).await?; + let outsider = is_outsider(&me.id, &community_id, &cx.db).await?; + let ghost = outsider || user::is_ghost(&me.id, &cx.db).await?; + let starts_call = !ghost + && community::is_direct(&community_id, &cx.db).await? + && rooms.participants(&community_id).is_empty(); + let joined = rooms.join(cx.client, &community_id, muted, ghost)?; + let mut broadcasts = match joined.departure { + Some(departure) => departed(departure, &cx.db).await?, + None => Vec::new(), + }; + if starts_call { + let created = + message::create_call_log(&community_id, &me.id, CallLog::Started, &cx.db).await?; + broadcasts.push(message_event(&created, Event::MessageCreated)); + } + if !ghost && !joined.transferred { + broadcasts.extend(voice_joined(&community_id, &me.id, muted)); + } + cx.out.extend(broadcasts); + + Ok(rooms.participants(&community_id)) + } +} + +impl Handle for LeaveVoice { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + me.user()?; + if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) { + let broadcasts = departed(departure, &cx.db).await?; + cx.out.extend(broadcasts); + } + + Ok(()) + } +} + +impl Handle for StartShare { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let rooms = &cx.sh.services.rooms; + let Some(community_id) = rooms.room_of_conn(cx.client.id) else { + return Err(Error::NotFound.into()); + }; + allowed(&me, &community_id, &cx.db, permission::can_share).await?; + ensure(!self.source.encode.is_empty())?; + ensure(!user::is_ghost(&me.id, &cx.db).await?)?; + let event = Event::ShareStarted { + community_id: community_id.clone(), + share: Share { + user_id: me.id.clone(), + kind: self.kind, + source: self.source.clone(), + }, + }; + let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)]; + broadcasts.extend( + rooms + .start_share(cx.client.id, self.kind, self.source) + .ok_or(Error::NotFound)?, + ); + cx.out.extend(broadcasts); + + Ok(()) + } +} + +impl Handle for StopShare { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + if let Some(community_id) = cx.sh.services.rooms.stop_share(cx.client.id, self.kind) { + cx.out.push(share_ended(&community_id, &me.id, self.kind)); + } + + Ok(()) + } +} + +impl Handle for ListShares { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + Ok(cx.sh.services.rooms.shares(&self.community_id)) + } +} + +impl Handle for WatchShare { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + me.user()?; + let broadcasts = cx + .sh + .services + .rooms + .watch( + cx.client.id, + &self.user_id, + self.kind, + self.quality, + &self.decode, + ) + .ok_or(Error::NotFound)?; + cx.out.extend(broadcasts); + + Ok(()) + } +} + +impl Handle for UnwatchShare { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + me.user()?; + let broadcasts = cx + .sh + .services + .rooms + .unwatch(cx.client.id, &self.user_id, self.kind); + cx.out.extend(broadcasts); + + Ok(()) + } +} + +impl Handle for RequestKeyframe { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + me.user()?; + let keyframe = cx + .sh + .services + .rooms + .keyframe(cx.client.id, &self.user_id, self.kind) + .ok_or(Error::NotFound)?; + cx.out.push(keyframe); + + Ok(()) + } +} + +impl Handle for DeclineCall { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + let community_id = self.community_id; + let rooms = &cx.sh.services.rooms; + ensure(community::is_direct(&community_id, &cx.db).await?)?; + allowed(&me, &community_id, &cx.db, permission::can_read).await?; + let participants = rooms.participants(&community_id); + ensure(!participants.is_empty() && !participants.contains(&me.id))?; + rooms.decline(&community_id); + let created = + message::create_call_log(&community_id, &me.id, CallLog::Declined, &cx.db).await?; + cx.out.push(message_event(&created, Event::MessageCreated)); + + Ok(()) + } +} + +impl Handle for ListVoiceParticipants { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + let me = me.user()?; + allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + + Ok(cx.sh.services.rooms.participants(&self.community_id)) + } +} + +impl Handle for ListVoiceRooms { + async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + voice_rooms(&cx.sh.services.rooms, &cx.db).await + } +} + +impl Handle for KickFromVoice { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + managed(&me, &self.user_id, &cx.db).await?; + let broadcasts = leave_user_voice(&cx.sh.services.rooms, &self.user_id, &cx.db).await?; + if !broadcasts.is_empty() { + admin_log::record( + Some(&me.id), + Some(&self.user_id), + None, + &AdminAction::VoiceKicked, + &cx.db, + ) + .await?; + } + cx.out.extend(broadcasts); + + Ok(()) + } +} + +impl Handle for ServerMute { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let me = me.user()?; + managed(&me, &self.user_id, &cx.db).await?; + user::set_voice_muted(&self.user_id, self.muted, &cx.db).await?; + admin_log::record( + Some(&me.id), + Some(&self.user_id), + None, + &AdminAction::VoiceMuted { muted: self.muted }, + &cx.db, + ) + .await?; + let community_id = cx.sh.services.rooms.set_muted(&self.user_id, self.muted); + let broadcast = voice_muted(community_id, &self.user_id, self.muted, &cx.db).await?; + cx.out.push(broadcast); + + Ok(()) + } +} diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 1b1009e..044a334 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -1,1525 +1,27 @@ -use std::{collections::BTreeMap, path::Path}; - use common::{ error::Error as CommonError, event::Event, - model::{ - AdminAction, BanScope, CallLog, CommunitySummary, LogAction, Member, Message, Presence, - Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom, - }, + model::{AdminAction, CallLog, Message, Presence, Rank, User, VoiceRoom}, permission, - request::LegacyRequest, - response::Response, - share::{Kind, Share}, - time::{self, MINUTE_MILLIS}, - transport::Close, - validate::{ - validate_avatar_size, validate_forward, validate_new_message, validate_poll, - validate_reaction, validate_reason, validate_server_settings, validate_vote, - }, + share::Kind, }; use turso::Connection; use crate::{ - admin_log, attachment, authentication, backup, community, - database::{self, DB}, - direct, + admin_log, community, error::ServerError, - friend, hub::{Client, Hub}, - invitation, invite, log, message, - network::Services, - notes, overview, + message, publish::{Broadcast, To}, rate_limit::RateLimit, - report, rooms::{Departure, Rooms}, - server_ban, server_settings, stats, user, user_community, + server_settings, user, user_community, }; -pub(crate) type Outcome = (Response, Vec); - -#[cfg(test)] -pub async fn handle( - request: LegacyRequest, - client: &Client, - db: &DB, - services: &Services, - directory: &Path, - backups: &Path, -) -> (Result, Vec) { - match dispatch(request, client, db, services, directory, backups).await { - Ok((response, broadcasts)) => (Ok(response), broadcasts), - Err(error) => (Err(error.into()), Vec::new()), - } -} - -pub(crate) async fn dispatch( - request: LegacyRequest, - client: &Client, - db: &DB, - services: &Services, - directory: &Path, - backups: &Path, -) -> Result { - let Services { - rooms, - hub, - rate_limit, - } = services; - let connection = client.conn.as_ref(); - let mut conn = database::connect(db).await?; - - let outcome = match request { - LegacyRequest::Register { - username, - password, - invite, - } => { - limit_logins(rate_limit, connection, &conn).await?; - let (user, token) = - authentication::register(&username, &password, invite.as_deref(), &mut conn) - .await?; - (Response::Session { user, token }, Vec::new()) - } - LegacyRequest::Login { username, password } => { - limit_logins(rate_limit, connection, &conn).await?; - let (user, token) = authentication::login(&username, &password, &conn).await?; - (Response::Session { user, token }, Vec::new()) - } - LegacyRequest::Logout => { - authenticated(client, &conn).await?; - let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; - authentication::logout(&me.token, &conn).await?; - (Response::Done, Vec::new()) - } - LegacyRequest::UpdateServerSettings { settings } => { - let me = builder(client, &conn).await?; - validate_server_settings(&settings)?; - server_settings::update(&settings, &conn).await?; - admin_log::record( - Some(&me.id), - None, - None, - &AdminAction::SettingsChanged, - &conn, - ) - .await?; - if settings.maintenance { - let builders = user::builder_ids(&conn).await?; - hub.kick_all_except(&builders, Close::Maintenance); - } - let broadcasts = vec![Broadcast::new( - To::Everyone, - Event::SettingsUpdated(settings.clone()), - )]; - (Response::ServerSettings(settings), broadcasts) - } - LegacyRequest::RenameUser { user_id, username } => { - 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( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::UserRenamed { - from: target.username, - }, - &conn, - ) - .await?; - let broadcasts = user_updated(&user); - (Response::User(user), broadcasts) - } - LegacyRequest::CreateUser { username, password } => { - let me = builder(client, &conn).await?; - let user = authentication::create_account(&username, &password, &conn).await?; - admin_log::record( - Some(&me.id), - Some(&user.id), - None, - &AdminAction::UserCreated, - &conn, - ) - .await?; - (Response::User(user), Vec::new()) - } - LegacyRequest::Users => { - builder(client, &conn).await?; - (Response::Users(user::all(&conn).await?), Vec::new()) - } - LegacyRequest::AdminLogs { - actor_id, - target_id, - action, - after_ms, - before_ms, - } => { - builder(client, &conn).await?; - ( - Response::AdminLogs( - admin_log::list( - actor_id.as_deref(), - target_id.as_deref(), - action.as_deref(), - after_ms, - before_ms, - &conn, - ) - .await?, - ), - Vec::new(), - ) - } - LegacyRequest::DailyStats { days } => { - builder(client, &conn).await?; - ( - Response::DailyStats(stats::daily(days, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::Overview => { - builder(client, &conn).await?; - ( - Response::Overview(overview::read(hub, rooms, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::SuspendUser { user_id, suspended } => { - let me = authenticated(client, &conn).await?; - managed(&me, &user_id, &conn).await?; - user::set_suspended(&user_id, suspended, &conn).await?; - let action = if suspended { - AdminAction::UserSuspended - } else { - AdminAction::UserUnsuspended - }; - admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?; - if suspended { - authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; - } - (Response::Done, Vec::new()) - } - LegacyRequest::RevokeSessions { user_id } => { - let me = authenticated(client, &conn).await?; - managed(&me, &user_id, &conn).await?; - authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::SessionsRevoked, - &conn, - ) - .await?; - (Response::Done, Vec::new()) - } - LegacyRequest::ResetPassword { user_id, password } => { - let me = authenticated(client, &conn).await?; - managed(&me, &user_id, &conn).await?; - authentication::reset_password(&user_id, &password, &conn).await?; - authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::PasswordReset, - &conn, - ) - .await?; - (Response::Done, Vec::new()) - } - LegacyRequest::ClearProfile { user_id } => { - 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?; - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::ProfileCleared, - &conn, - ) - .await?; - let broadcasts = user_updated(&user); - (Response::User(user), broadcasts) - } - LegacyRequest::SetRole { user_id, role } => { - 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( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::RoleChanged { role }, - &conn, - ) - .await?; - let mut broadcasts = user_updated(&user); - if permission::is_builder(role) { - broadcasts.extend(voice_unmuted(rooms, &user_id, &conn).await?); - } else { - user::set_ghost(&user_id, false, &conn).await?; - hub.kick_user(&user_id, Close::Revoked); - } - (Response::User(user), broadcasts) - } - LegacyRequest::DeleteUser { user_id } => { - let me = authenticated(client, &conn).await?; - let target = user::read(&user_id, &conn).await?; - ensure(permission::can_delete_user( - me.role, - me.id == user_id, - target.role, - ))?; - let tx = conn.transaction().await?; - let mut broadcasts = Vec::new(); - if permission::is_builder(me.role) && me.id != user_id { - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::UserDeleted, - &tx, - ) - .await?; - } - for community_id in user_community::owned(&user_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::new(To::Users(member_ids), event)); - } - for community in community::communities_of(&user_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::new(To::Users(member_ids), event)); - } - 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 { - hub.kick_user(&user_id, Close::Revoked); - } - (Response::User(deleted), broadcasts) - } - LegacyRequest::CreateCommunity { name } => { - 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( - limit == 0 || owned < limit as usize, - CommonError::LimitReached, - )?; - let tx = conn.transaction().await?; - let community = community::create(&name, &tx).await?; - user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?; - log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?; - tx.commit().await?; - (Response::Community(community), Vec::new()) - } - LegacyRequest::ReadCommunity { community_id } => { - 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?), - Vec::new(), - ) - } - LegacyRequest::UpdateCommunity { community_id, name } => { - 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?; - let action = LogAction::Renamed { - name: updated.name.clone(), - }; - log::record(&community_id, Some(&me.id), None, &action, &conn).await?; - let event = Event::CommunityUpdated(updated.clone()); - ( - Response::Community(updated), - vec![Broadcast::new(To::Community(community_id), event)], - ) - } - LegacyRequest::UpdateCommunityAvatar { - community_id, - image, - } => { - 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 { - validate_avatar_size(bytes, server_settings::read(&conn).await?.max_avatar_bytes)?; - } - let updated = - community::set_avatar(&community_id, image.as_deref(), &me.id, &mut conn).await?; - let action = if image.is_some() { - LogAction::AvatarChanged - } else { - LogAction::AvatarRemoved - }; - log::record(&community_id, Some(&me.id), None, &action, &conn).await?; - let event = Event::CommunityUpdated(updated.clone()); - ( - Response::Community(updated), - vec![Broadcast::new(To::Community(community_id), event)], - ) - } - LegacyRequest::DeleteCommunity { community_id } => { - 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 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?; - if permission::is_builder(me.role) && !owned { - admin_log::record( - Some(&me.id), - None, - Some(&deleted.name), - &AdminAction::CommunityDeleted, - &tx, - ) - .await?; - } - tx.commit().await?; - let mut broadcasts = voice_closed(rooms, &community_id, &conn).await?; - let event = Event::CommunityDeleted { - community_id: deleted.id.clone(), - }; - broadcasts.push(Broadcast::new(To::Users(member_ids), event)); - (Response::Community(deleted), broadcasts) - } - LegacyRequest::LeaveCommunity { community_id } => { - 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?; - 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(rooms, &community_id, &me.id, &conn).await?; - let event = Event::MemberLeft { - community_id: community_id.clone(), - user_id: me.id, - }; - broadcasts.push(Broadcast::new(To::Community(community_id), event)); - (Response::Done, broadcasts) - } - LegacyRequest::Communities => { - let me = authenticated(client, &conn).await?; - ( - Response::Communities(community::communities_of(&me.id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::Members { community_id } => { - let me = authenticated(client, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_read).await?; - ( - Response::Members(user_community::members(&community_id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::Kick { - community_id, - user_id, - reason, - } => { - let me = authenticated(client, &conn).await?; - remove_member( - &me, - Removal { - community_id, - user_id, - reason, - sanction: Sanction::Kick, - }, - rooms, - &mut conn, - ) - .await? - } - LegacyRequest::Ban { - community_id, - user_id, - reason, - } => { - let me = authenticated(client, &conn).await?; - remove_member( - &me, - Removal { - community_id, - user_id, - reason, - sanction: Sanction::Ban, - }, - rooms, - &mut conn, - ) - .await? - } - LegacyRequest::Unban { - community_id, - user_id, - } => { - 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( - &community_id, - Some(&me.id), - Some(&user_id), - &LogAction::Unbanned, - &conn, - ) - .await?; - (Response::Done, Vec::new()) - } - LegacyRequest::Bans { community_id } => { - let me = authenticated(client, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_unban).await?; - ( - Response::Bans(user_community::bans(&community_id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::SetRank { - community_id, - user_id, - rank, - } => { - 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( - actor_rank(&me, &community_id, &conn).await?, - actor_rank(&target, &community_id, &conn).await?, - rank, - ))?; - user_community::set_rank(&user_id, &community_id, rank, &conn).await?; - log::record( - &community_id, - Some(&me.id), - Some(&user_id), - &LogAction::RankChanged { rank }, - &conn, - ) - .await?; - let event = Event::RankChanged { - community_id: community_id.clone(), - user_id, - rank, - }; - ( - Response::Done, - vec![Broadcast::new(To::Community(community_id), event)], - ) - } - LegacyRequest::CreateMessage { - community_id, - body, - attachments, - reply_to, - } => { - let me = authenticated(client, &conn).await?; - let settings = server_settings::read(&conn).await?; - limit_messages(&me, rate_limit, &settings)?; - validate_new_message( - &body, - attachments.len(), - settings.max_message_length as usize, - )?; - allowed(&me, &community_id, &conn, permission::can_post).await?; - let tx = conn.transaction().await?; - let created = message::create( - &me.id, - &community_id, - &body, - &attachments, - reply_to.as_deref(), - &tx, - ) - .await?; - stats::mark_active(&me.id, &tx).await?; - tx.commit().await?; - let broadcast = message_event(&created, Event::MessageCreated); - (Response::Message(created), vec![broadcast]) - } - LegacyRequest::ForwardMessages { - message_ids, - community_id, - snippet, - } => { - 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( - actor_rank(&me, &community_id, &conn).await?, - ))?; - let tx = conn.transaction().await?; - let mut sources = Vec::new(); - for message_id in &message_ids { - let source = message::read(message_id, &tx).await?; - ensure(permission::can_read( - actor_rank(&me, &source.community_id, &tx).await?, - ))?; - sources.push(source); - } - let mode = if snippet { - message::ForwardMode::Snippet - } else { - message::ForwardMode::Copy - }; - let created = - message::forward(&me, &community_id, &sources, mode, directory, &tx).await?; - tx.commit().await?; - let broadcasts = created - .iter() - .map(|message| message_event(message, Event::MessageCreated)) - .collect(); - (Response::Messages(created), broadcasts) - } - LegacyRequest::UpdateMessage { message_id, body } => { - 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)?; - validate_new_message( - &body, - 0, - server_settings::read(&conn).await?.max_message_length as usize, - )?; - let updated = message::update(&message_id, &body, &conn).await?; - let broadcast = message_event(&updated, Event::MessageUpdated); - (Response::Message(updated), vec![broadcast]) - } - LegacyRequest::CreatePoll { - community_id, - question, - options, - multiple, - } => { - let me = authenticated(client, &conn).await?; - let settings = server_settings::read(&conn).await?; - limit_messages(&me, rate_limit, &settings)?; - validate_poll(&question, &options)?; - allowed(&me, &community_id, &conn, permission::can_post).await?; - let tx = conn.transaction().await?; - let created = - message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx) - .await?; - stats::mark_active(&me.id, &tx).await?; - tx.commit().await?; - let broadcast = message_event(&created, Event::MessageCreated); - (Response::Message(created), vec![broadcast]) - } - LegacyRequest::Vote { - message_id, - positions, - } => { - 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?, - ))?; - 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_event(&updated, Event::MessageUpdated); - (Response::Done, vec![broadcast]) - } - LegacyRequest::ClosePoll { message_id } => { - 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_event(&updated, Event::MessageUpdated); - (Response::Done, vec![broadcast]) - } - LegacyRequest::React { message_id, emoji } => { - 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_event(&updated, Event::MessageUpdated); - (Response::Done, vec![broadcast]) - } - LegacyRequest::Pin { message_id, pinned } => { - 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( - actor_rank(&me, &existing.community_id, &conn).await?, - direct, - ))?; - let updated = message::pin(&message_id, pinned, &conn).await?; - let broadcast = message_event(&updated, Event::MessageUpdated); - (Response::Done, vec![broadcast]) - } - LegacyRequest::Unreads => { - let me = authenticated(client, &conn).await?; - ( - Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::MarkRead { - community_id, - message_id, - } => { - 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()) - } - LegacyRequest::Pins { community_id } => { - let me = authenticated(client, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_read).await?; - ( - Response::Messages(message::pinned(&community_id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::DeleteMessage { message_id } => { - 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( - actor_rank(&me, &existing.community_id, &conn).await?, - actor_rank(&author, &existing.community_id, &conn).await?, - existing.user_id == me.id, - ))?; - let deleted = message::delete(&message_id, &conn).await?; - if existing.user_id != me.id { - log::record( - &deleted.community_id, - Some(&me.id), - Some(&existing.user_id), - &LogAction::MessageDeleted, - &conn, - ) - .await?; - } - if permission::is_builder(me.role) && existing.user_id != me.id { - let community = community::label(&deleted.community_id, &conn).await?; - admin_log::record( - Some(&me.id), - Some(&existing.user_id), - Some(&community), - &AdminAction::MessageDeleted, - &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]) - } - LegacyRequest::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?; - 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 && client.first_visit(&community_id) { - let community = community::label(&community_id, &conn).await?; - admin_log::record( - Some(&me.id), - None, - Some(&community), - &AdminAction::GhostVisit, - &conn, - ) - .await?; - } - (Response::Done, Vec::new()) - } - LegacyRequest::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()) - } - LegacyRequest::JoinVoice { community_id } => { - 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 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? - && 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(message_event(&created, Event::MessageCreated)); - } - if !ghost && !joined.transferred { - broadcasts.extend(voice_joined(&community_id, &me.id, muted)); - } - ( - Response::Voice(rooms.participants(&community_id)), - broadcasts, - ) - } - LegacyRequest::Typing { community_id } => { - 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 others: Vec = user_community::member_ids(&community_id, &conn) - .await? - .into_iter() - .filter(|user_id| *user_id != me.id) - .collect(); - let event = Event::Typing { - community_id, - user_id: me.id.clone(), - }; - vec![Broadcast::new(To::Users(others), event)] - }; - (Response::Done, broadcasts) - } - LegacyRequest::LeaveVoice => { - authenticated(client, &conn).await?; - let broadcasts = match rooms.leave(client.id) { - Some(departure) => departed(departure, &conn).await?, - None => Vec::new(), - }; - (Response::Done, broadcasts) - } - LegacyRequest::StartShare { kind, source } => { - 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 event = Event::ShareStarted { - community_id: community_id.clone(), - share: Share { - user_id: me.id.clone(), - kind, - source: source.clone(), - }, - }; - 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) - } - LegacyRequest::StopShare { kind } => { - 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) - } - LegacyRequest::Shares { community_id } => { - let me = authenticated(client, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_read).await?; - (Response::Shares(rooms.shares(&community_id)), Vec::new()) - } - LegacyRequest::WatchShare { - user_id, - kind, - quality, - decode, - } => { - authenticated(client, &conn).await?; - let broadcasts = rooms - .watch(client.id, &user_id, kind, quality, &decode) - .ok_or(CommonError::NotFound)?; - - (Response::Done, broadcasts) - } - LegacyRequest::UnwatchShare { user_id, kind } => { - authenticated(client, &conn).await?; - - (Response::Done, rooms.unwatch(client.id, &user_id, kind)) - } - LegacyRequest::RequestKeyframe { user_id, kind } => { - authenticated(client, &conn).await?; - let keyframe = rooms - .keyframe(client.id, &user_id, kind) - .ok_or(CommonError::NotFound)?; - - (Response::Done, vec![keyframe]) - } - LegacyRequest::DeclineCall { community_id } => { - 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 = rooms.participants(&community_id); - ensure(!participants.is_empty() && !participants.contains(&me.id))?; - rooms.decline(&community_id); - let created = - message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?; - ( - Response::Done, - vec![message_event(&created, Event::MessageCreated)], - ) - } - LegacyRequest::VoiceParticipants { community_id } => { - let me = authenticated(client, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_read).await?; - ( - Response::Voice(rooms.participants(&community_id)), - Vec::new(), - ) - } - LegacyRequest::FindUser { username } => { - let me = authenticated(client, &conn).await?; - let found = user::by_username(&username, &conn) - .await? - .filter(|found| found.id != me.id) - .ok_or(CommonError::NotFound)?; - (Response::User(found), Vec::new()) - } - LegacyRequest::OpenDirect { user_id } => { - 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::new( - To::User(user_id), - Event::CommunityAdded(peer_view), - )], - ) - } - direct::Opening::Existing(community) => { - (Response::Community(community), Vec::new()) - } - } - } - LegacyRequest::OpenNotes => { - let me = authenticated(client, &conn).await?; - ( - Response::Community(notes::open(&me.id, &mut conn).await?), - Vec::new(), - ) - } - LegacyRequest::Friends => { - let me = authenticated(client, &conn).await?; - ( - Response::Friends(friend::state(&me.id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::AddFriend { user_id } => { - 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) - } - LegacyRequest::AcceptFriend { user_id } => { - 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) - } - LegacyRequest::RemoveFriend { user_id } => { - 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) - } - LegacyRequest::Invite { - community_id, - user_id, - } => { - 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?; - if user_community::rank(&user_id, &community_id, &conn) - .await? - .is_some() - { - return Err(CommonError::AlreadyMember.into()); - } - let banned = user_community::is_banned(&user_id, &community_id, &conn).await?; - ensure(permission::can_join(target.role, banned))?; - if invitation::exists(&community_id, &user_id, &conn).await? { - return Err(CommonError::AlreadyInvited.into()); - } - invitation::insert(&community_id, &user_id, &me.id, &conn).await?; - log::record( - &community_id, - Some(&me.id), - Some(&user_id), - &LogAction::Invited, - &conn, - ) - .await?; - let broadcast = invitations_updated(&user_id, &conn).await?; - (Response::Done, vec![broadcast]) - } - LegacyRequest::Invitations => { - let me = authenticated(client, &conn).await?; - ( - Response::Invitations(invitation::of(&me.id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::AcceptInvitation { community_id } => { - 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?; - ensure(permission::can_join(me.role, banned))?; - 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?; - tx.commit().await?; - let event = Event::MemberJoined { - community_id: community_id.clone(), - member: Member { - user: me.clone(), - rank: Rank::Member, - }, - }; - let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)]; - broadcasts.push(invitations_updated(&me.id, &conn).await?); - (Response::Community(community), broadcasts) - } - LegacyRequest::DeclineInvitation { community_id } => { - let me = authenticated(client, &conn).await?; - invitation::take(&community_id, &me.id, &conn).await?; - ( - Response::Done, - vec![invitations_updated(&me.id, &conn).await?], - ) - } - LegacyRequest::Logs { community_id } => { - let me = authenticated(client, &conn).await?; - allowed(&me, &community_id, &conn, permission::can_read_logs).await?; - ( - Response::Logs(log::list(&community_id, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::AllCommunities => { - 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?; - let owner = members - .iter() - .find(|member| member.rank == Rank::Owner) - .map(|member| member.user.clone()); - summaries.push(CommunitySummary { - community, - owner, - members: members.len() as u64, - }); - } - (Response::AllCommunities(summaries), Vec::new()) - } - LegacyRequest::TransferOwnership { - community_id, - user_id, - } => { - let me = authenticated(client, &conn).await?; - ensure_editable(&community_id, &conn).await?; - allowed( - &me, - &community_id, - &conn, - permission::can_transfer_ownership, - ) - .await?; - let tx = conn.transaction().await?; - let members = user_community::members(&community_id, &tx).await?; - let target = members - .iter() - .find(|member| member.user.id == user_id) - .ok_or(CommonError::NotFound)?; - ensure(target.rank != Rank::Owner)?; - let mut changes = vec![(user_id.clone(), Rank::Owner)]; - if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) { - user_community::set_rank(&previous.user.id, &community_id, Rank::Admin, &tx) - .await?; - log::record( - &community_id, - Some(&me.id), - Some(&previous.user.id), - &LogAction::RankChanged { rank: Rank::Admin }, - &tx, - ) - .await?; - changes.push((previous.user.id.clone(), Rank::Admin)); - } - user_community::set_rank(&user_id, &community_id, Rank::Owner, &tx).await?; - log::record( - &community_id, - Some(&me.id), - Some(&user_id), - &LogAction::RankChanged { rank: Rank::Owner }, - &tx, - ) - .await?; - if permission::is_builder(me.role) { - let community = community::read(&community_id, &me.id, &tx).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), - Some(&community.name), - &AdminAction::OwnershipTransferred, - &tx, - ) - .await?; - } - tx.commit().await?; - let mut broadcasts = Vec::new(); - for (changed_id, rank) in changes { - let event = Event::RankChanged { - community_id: community_id.clone(), - user_id: changed_id, - rank, - }; - broadcasts.push(Broadcast::new(To::Community(community_id.clone()), event)); - } - (Response::Done, broadcasts) - } - LegacyRequest::TimeoutUser { user_id, minutes } => { - 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(hub, authentication::Revoke::User(&user_id), &conn).await?; - } - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::UserTimedOut { minutes }, - &conn, - ) - .await?; - (Response::Done, Vec::new()) - } - LegacyRequest::BanUser { - user_id, - reason, - scope, - } => { - let me = authenticated(client, &conn).await?; - let target = managed(&me, &user_id, &conn).await?; - validate_reason(reason.as_deref())?; - let tx = conn.transaction().await?; - user::set_suspended(&user_id, true, &tx).await?; - authentication::revoke_sessions(&user_id, &tx).await?; - server_ban::insert( - ServerBanKind::Username, - &target.username.to_ascii_lowercase(), - reason.as_deref(), - &me.id, - &tx, - ) - .await?; - if scope == BanScope::AccountAndIp - && let Some(address) = user::last_ip(&user_id, &tx).await? - { - server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx) - .await?; - } - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::UserBanned { reason }, - &tx, - ) - .await?; - tx.commit().await?; - hub.kick_user(&user_id, Close::Banned); - (Response::Done, Vec::new()) - } - LegacyRequest::ServerBans => { - builder(client, &conn).await?; - ( - Response::ServerBans(server_ban::list(&conn).await?), - Vec::new(), - ) - } - LegacyRequest::RemoveServerBan { id } => { - 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()) - } - LegacyRequest::CreateInviteCode { uses, hours } => { - 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()) - } - LegacyRequest::InviteCodes => { - builder(client, &conn).await?; - ( - Response::InviteCodes(invite::list(&conn).await?), - Vec::new(), - ) - } - LegacyRequest::DeleteInviteCode { code } => { - 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()) - } - LegacyRequest::ReportMessage { message_id, reason } => { - 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)?; - validate_reason(Some(&reason))?; - ensure_with( - !report::is_open(&me.id, &message.user_id, Some(&message_id), &conn).await?, - CommonError::Taken, - )?; - report::insert( - &me.id, - &message.user_id, - Some(&message_id), - Some(&message.community_id), - Some(&message.body), - &reason, - &conn, - ) - .await?; - (Response::Done, vec![report_created()]) - } - LegacyRequest::ReportUser { user_id, reason } => { - let me = authenticated(client, &conn).await?; - user::read(&user_id, &conn).await?; - ensure(me.id != user_id)?; - validate_reason(Some(&reason))?; - ensure_with( - !report::is_open(&me.id, &user_id, None, &conn).await?, - CommonError::Taken, - )?; - report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?; - (Response::Done, vec![report_created()]) - } - LegacyRequest::Reports { status } => { - builder(client, &conn).await?; - ( - Response::Reports(report::list(status, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::HandleReport { report_id, status } => { - 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( - Some(&me.id), - target.as_deref(), - None, - &AdminAction::ReportHandled { status }, - &conn, - ) - .await?; - (Response::Done, Vec::new()) - } - LegacyRequest::SearchMessages { - text, - user_id, - community_id, - after_ms, - before_ms, - } => { - builder(client, &conn).await?; - let hits = message::search( - text.as_deref(), - user_id.as_deref(), - community_id.as_deref(), - after_ms, - before_ms, - &conn, - ) - .await?; - (Response::MessageHits(hits), Vec::new()) - } - LegacyRequest::SearchCommunity { community_id, text } => { - 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()) - } - LegacyRequest::PurgeUser { user_id } => { - 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 deleted: BTreeMap> = BTreeMap::new(); - for message_id in &message_ids { - 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), - Some(&user_id), - None, - &AdminAction::UserPurged { - messages: message_ids.len() as u64, - }, - &tx, - ) - .await?; - tx.commit().await?; - attachment::remove_files(&upload_ids, directory); - (Response::Done, broadcasts) - } - LegacyRequest::AllAttachments { - user_id, - community_id, - } => { - builder(client, &conn).await?; - ( - Response::AttachmentInfos( - attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?, - ), - Vec::new(), - ) - } - LegacyRequest::DeleteAttachment { attachment_id } => { - 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?; - attachment::delete(&attachment_id, &tx).await?; - admin_log::record( - Some(&me.id), - Some(&stored.uploader_id), - Some(&community), - &AdminAction::AttachmentDeleted, - &tx, - ) - .await?; - let mut broadcasts = Vec::new(); - if let Some(message_id) = &stored.message_id { - let updated = message::read(message_id, &tx).await?; - broadcasts = vec![message_event(&updated, Event::MessageUpdated)]; - } - tx.commit().await?; - attachment::remove_files(&[attachment_id], directory); - (Response::Done, broadcasts) - } - LegacyRequest::StorageUsage => { - builder(client, &conn).await?; - let (users, communities) = attachment::usage(&conn).await?; - (Response::StorageUsage { users, communities }, Vec::new()) - } - LegacyRequest::CreateBackup => { - let me = builder(client, &conn).await?; - let backup = backup::create(&conn, backups).await?; - let action = AdminAction::BackupCreated { - name: backup.name.clone(), - }; - admin_log::record(Some(&me.id), None, None, &action, &conn).await?; - (Response::Backup(backup), Vec::new()) - } - LegacyRequest::Backups => { - builder(client, &conn).await?; - (Response::Backups(backup::list(backups)?), Vec::new()) - } - LegacyRequest::DeleteBackup { name } => { - 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()) - } - LegacyRequest::VoiceRooms => { - builder(client, &conn).await?; - ( - Response::VoiceRooms(voice_rooms(rooms, &conn).await?), - Vec::new(), - ) - } - LegacyRequest::KickFromVoice { user_id } => { - let me = authenticated(client, &conn).await?; - managed(&me, &user_id, &conn).await?; - let broadcasts = leave_user_voice(rooms, &user_id, &conn).await?; - if !broadcasts.is_empty() { - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::VoiceKicked, - &conn, - ) - .await?; - } - (Response::Done, broadcasts) - } - LegacyRequest::ServerMute { user_id, muted } => { - let me = authenticated(client, &conn).await?; - managed(&me, &user_id, &conn).await?; - user::set_voice_muted(&user_id, muted, &conn).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), - None, - &AdminAction::VoiceMuted { muted }, - &conn, - ) - .await?; - let community_id = rooms.set_muted(&user_id, muted); - let broadcast = voice_muted(community_id, &user_id, muted, &conn).await?; - (Response::Done, vec![broadcast]) - } - LegacyRequest::SetCommunityVoice { - community_id, - enabled, - } => { - 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?; - let updated = community::read(&community_id, &me.id, &tx).await?; - if permission::is_builder(me.role) { - admin_log::record( - Some(&me.id), - None, - Some(&updated.name), - &AdminAction::CommunityVoiceSet { enabled }, - &tx, - ) - .await?; - } - tx.commit().await?; - let mut broadcasts = Vec::new(); - if !enabled { - broadcasts.extend(voice_silenced(rooms, &community_id, &conn).await?); - } - let event = Event::CommunityUpdated(updated.clone()); - broadcasts.push(Broadcast::new(To::Community(community_id), event)); - - (Response::Community(updated), broadcasts) - } - LegacyRequest::SetGhost { enabled } => { - let me = builder(client, &conn).await?; - user::set_ghost(&me.id, enabled, &conn).await?; - let action = if enabled { - AdminAction::GhostEnabled - } else { - AdminAction::GhostDisabled - }; - admin_log::record(Some(&me.id), None, None, &action, &conn).await?; - let mut broadcasts = Vec::new(); - 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(mut departure) = rooms.set_ghost(&me.id, enabled) { - let community_id = departure.community_id.clone(); - if enabled { - 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(voice_joined(&community_id, &me.id, muted)); - if let Some(seconds) = departure.ghost_seconds { - record_ghost_voice(&me.id, &community_id, seconds, &conn).await?; - } - } - } - (Response::Done, broadcasts) - } - }; - - Ok(outcome) -} - -async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result, ServerError> { +pub(crate) async fn voice_rooms( + occupied: &Rooms, + conn: &Connection, +) -> Result, ServerError> { let mut rooms = Vec::new(); for (community_id, user_ids, ghosts) in occupied.list() { let community = community::label(&community_id, conn).await?; @@ -1545,15 +47,11 @@ async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result Broadcast { - Broadcast::new(To::Builders, Event::ReportCreated) -} - fn ip_of(connection: Option<&quinn::Connection>) -> Option { connection.map(|connection| connection.remote_address().ip().to_string()) } -async fn limit_logins( +pub(crate) async fn limit_logins( rate_limit: &RateLimit, connection: Option<&quinn::Connection>, conn: &Connection, @@ -1563,18 +61,6 @@ async fn limit_logins( Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?) } -fn limit_messages( - me: &User, - rate_limit: &RateLimit, - settings: &ServerSettings, -) -> Result<(), ServerError> { - if permission::is_builder(me.role) { - return Ok(()); - } - - Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?) -} - pub(crate) async fn record_address( user: &User, connection: Option<&quinn::Connection>, @@ -1587,65 +73,6 @@ pub(crate) async fn record_address( Ok(()) } -struct Removal { - community_id: String, - user_id: String, - reason: Option, - sanction: Sanction, -} - -async fn remove_member( - me: &User, - removal: Removal, - rooms: &Rooms, - conn: &mut Connection, -) -> Result { - let Removal { - community_id, - user_id, - reason, - sanction, - } = removal; - validate_reason(reason.as_deref())?; - ensure_editable(&community_id, conn).await?; - let target = user::read(&user_id, conn).await?; - ensure(permission::can_moderate( - actor_rank(me, &community_id, conn).await?, - actor_rank(&target, &community_id, conn).await?, - ))?; - let community = community::read(&community_id, &me.id, conn).await?; - let tx = conn.transaction().await?; - user_community::leave(&user_id, &community_id, &tx).await?; - let action = match sanction { - Sanction::Ban => { - user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?; - LogAction::Banned { - reason: reason.clone(), - } - } - Sanction::Kick => LogAction::Kicked { - reason: reason.clone(), - }, - }; - log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; - tx.commit().await?; - 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.clone(), - user_id, - }; - broadcasts.push(Broadcast::new(To::Community(community_id), event)); - - Ok((Response::Done, broadcasts)) -} - pub(crate) fn user_updated(user: &User) -> Vec { vec![Broadcast::new( To::Related(user.id.clone()), @@ -1683,26 +110,7 @@ pub async fn presence_changed( )]) } -async fn friends_updated( - user_ids: &[&str], - conn: &Connection, -) -> Result, ServerError> { - let mut broadcasts = Vec::new(); - for user_id in user_ids { - 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 { - 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( +pub(crate) async fn leave_user_voice( rooms: &Rooms, user_id: &str, conn: &Connection, @@ -1713,7 +121,7 @@ async fn leave_user_voice( } } -async fn leave_room_voice( +pub(crate) async fn leave_room_voice( rooms: &Rooms, community_id: &str, user_id: &str, @@ -1725,7 +133,7 @@ async fn leave_room_voice( } } -async fn voice_unmuted( +pub(crate) async fn voice_unmuted( rooms: &Rooms, user_id: &str, conn: &Connection, @@ -1739,7 +147,7 @@ async fn voice_unmuted( ]) } -async fn voice_muted( +pub(crate) async fn voice_muted( community_id: Option, user_id: &str, muted: bool, @@ -1760,7 +168,7 @@ async fn voice_muted( Ok(Broadcast::new(To::Users(user_ids), event)) } -async fn voice_silenced( +pub(crate) async fn voice_silenced( rooms: &Rooms, community_id: &str, conn: &Connection, @@ -1776,7 +184,7 @@ async fn voice_silenced( Ok(broadcasts) } -async fn voice_closed( +pub(crate) async fn voice_closed( rooms: &Rooms, community_id: &str, conn: &Connection, @@ -1789,7 +197,7 @@ async fn voice_closed( Ok(broadcasts) } -async fn call_ended( +pub(crate) async fn call_ended( community_id: &str, user_id: &str, call: Option, @@ -1836,7 +244,7 @@ pub async fn departed( Ok(broadcasts) } -fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast { +pub(crate) 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(), @@ -1846,7 +254,7 @@ fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast { Broadcast::new(To::Community(community_id.to_string()), event) } -fn shares_ended(departure: &mut Departure) -> Vec { +pub(crate) fn shares_ended(departure: &mut Departure) -> Vec { let mut broadcasts: Vec = departure .shares .iter() @@ -1907,7 +315,7 @@ pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError> Ok(()) } -async fn allowed( +pub(crate) async fn allowed( me: &User, community_id: &str, conn: &Connection, @@ -1916,7 +324,7 @@ async fn allowed( ensure(check(actor_rank(me, community_id, conn).await?)) } -async fn is_outsider( +pub(crate) async fn is_outsider( user_id: &str, community_id: &str, conn: &Connection, @@ -1926,18 +334,21 @@ async fn is_outsider( .is_none()) } -async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), ServerError> { +pub(crate) async fn ensure_editable( + community_id: &str, + conn: &Connection, +) -> Result<(), ServerError> { ensure(!community::is_fixed(community_id, conn).await?) } -fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { +pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { Broadcast::new( To::Community(message.community_id.clone()), event(message.clone()), ) } -fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec { +pub(crate) 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(), @@ -1960,7 +371,7 @@ fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec Response { - send_result(request, client, db, services) - .await - .expect("request failed") + fn shared(db: &DB, services: &Services) -> Shared { + Shared { + db: db.clone(), + services: services.clone(), + directory: test::directory(), + backups: test::directory(), + } } - async fn send_result( - request: LegacyRequest, - client: &Client, + async fn call( + call: C, + client: &Arc, db: &DB, services: &Services, - ) -> Result { - handle( - request, - client, - db, - services, - &test::directory(), - &test::directory(), - ) - .await - .0 + ) -> Result { + let shared = shared(db, services); + let conn = database::connect(db).await.unwrap(); + let me = authenticated(client, &conn).await?; + let mut cx = Cx::new(client, &shared, conn); + + Ok(call.handle(Me::User(me), &mut cx).await?) } async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc { let guest = Client::detached(None); - let Response::Session { user, token } = send( - LegacyRequest::Register { - username: username.to_string(), - password: "password".to_string(), - invite: None, - }, - &guest, - db, - services, - ) + let shared = shared(db, services); + let conn = database::connect(db).await.unwrap(); + let mut cx = Cx::new(&guest, &shared, conn); + let session = Register { + username: username.to_string(), + password: "password".to_string(), + invite: None, + } + .handle(Me::Guest, &mut cx) .await - else { - panic!("register failed"); - }; + .unwrap(); Client::detached(Some(Signed { - user_id: user.id, - token, + user_id: session.user.id, + token: session.token, })) } async fn invite_and_accept( community_id: &str, - owner: &Client, - member: &Client, + owner: &Arc, + member: &Arc, username: &str, db: &DB, services: &Services, ) { - let Response::User(member_user) = send( - LegacyRequest::FindUser { + let member_user = call( + FindUser { username: username.to_string(), }, owner, @@ -2063,11 +473,9 @@ mod tests { services, ) .await - else { - panic!("user not found"); - }; - send( - LegacyRequest::Invite { + .unwrap(); + call( + Invite { community_id: community_id.to_string(), user_id: member_user.id, }, @@ -2075,16 +483,18 @@ mod tests { db, services, ) - .await; - send( - LegacyRequest::AcceptInvitation { + .await + .unwrap(); + call( + AcceptInvitation { community_id: community_id.to_string(), }, member, db, services, ) - .await; + .await + .unwrap(); } #[tokio::test] @@ -2093,8 +503,8 @@ mod tests { let services = Services::default(); let owner = signed_in("Owner", &db, &services).await; let member = signed_in("Member", &db, &services).await; - let Response::Community(community) = send( - LegacyRequest::CreateCommunity { + let community = call( + CreateCommunity { name: "The Community".to_string(), }, &owner, @@ -2102,13 +512,11 @@ mod tests { &services, ) .await - else { - panic!("community not created"); - }; + .unwrap(); invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; - let response = send_result( - LegacyRequest::UpdateCommunity { + let response = call( + UpdateCommunity { community_id: community.id, name: "Renamed".to_string(), }, @@ -2127,8 +535,8 @@ mod tests { let services = Services::default(); let first = signed_in("First", &db, &services).await; let second = signed_in("Second", &db, &services).await; - let Response::User(first_user) = send( - LegacyRequest::FindUser { + let first_user = call( + FindUser { username: "First".to_string(), }, &second, @@ -2136,11 +544,9 @@ mod tests { &services, ) .await - else { - panic!("user not found"); - }; - let Response::User(second_user) = send( - LegacyRequest::FindUser { + .unwrap(); + let second_user = call( + FindUser { username: "Second".to_string(), }, &first, @@ -2148,38 +554,30 @@ mod tests { &services, ) .await - else { - panic!("user not found"); - }; - send( - LegacyRequest::AddFriend { + .unwrap(); + call( + AddFriend { user_id: second_user.id.clone(), }, &first, &db, &services, ) - .await; - send( - LegacyRequest::AcceptFriend { + .await + .unwrap(); + call( + AcceptFriend { user_id: first_user.id.clone(), }, &second, &db, &services, ) - .await; + .await + .unwrap(); - let Response::Friends(first_friends) = - send(LegacyRequest::Friends, &first, &db, &services).await - else { - panic!("friends not read"); - }; - let Response::Friends(second_friends) = - send(LegacyRequest::Friends, &second, &db, &services).await - else { - panic!("friends not read"); - }; + let first_friends = call(ListFriends, &first, &db, &services).await.unwrap(); + let second_friends = call(ListFriends, &second, &db, &services).await.unwrap(); assert_eq!(vec![second_user], first_friends.friends); assert_eq!(vec![first_user], second_friends.friends); @@ -2191,8 +589,8 @@ mod tests { let services = Services::default(); let owner = signed_in("Owner", &db, &services).await; let member = signed_in("Member", &db, &services).await; - let Response::Community(community) = send( - LegacyRequest::CreateCommunity { + let community = call( + CreateCommunity { name: "The Community".to_string(), }, &owner, @@ -2200,17 +598,13 @@ mod tests { &services, ) .await - else { - panic!("community not created"); - }; + .unwrap(); invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; - let Response::Communities(communities) = - send(LegacyRequest::Communities, &member, &db, &services).await - else { - panic!("communities not read"); - }; + let communities = call(ListCommunities, &member, &db, &services) + .await + .unwrap(); assert_eq!(vec![community], communities); } @@ -2219,8 +613,8 @@ mod tests { let db = test::get_database().await; let services = Services::default(); let owner = signed_in("Owner", &db, &services).await; - let Response::Community(community) = send( - LegacyRequest::CreateCommunity { + let community = call( + CreateCommunity { name: "The Community".to_string(), }, &owner, @@ -2228,11 +622,9 @@ mod tests { &services, ) .await - else { - panic!("community not created"); - }; - send( - LegacyRequest::CreateMessage { + .unwrap(); + call( + CreateMessage { community_id: community.id.clone(), body: "Tahinli".to_string(), attachments: Vec::new(), @@ -2242,17 +634,19 @@ mod tests { &db, &services, ) - .await; + .await + .unwrap(); - send( - LegacyRequest::DeleteCommunity { + call( + DeleteCommunity { community_id: community.id.clone(), }, &owner, &db, &services, ) - .await; + .await + .unwrap(); let conn = database::connect(&db).await.unwrap(); let remaining = message::read_page(&community.id, None, &conn)