forge
Explore
Log in

Don't you dare go Hollow

Every call is a typed struct and the legacy request path is gone

Browse files at this commit

c0a7e2d1da6e06f02af58daaf2924b6f80dbad66Ahmet Kaan GümüşParent: c69c3ca
  • refactor
    • every call is a typed struct and the legacy request path is gone
Show full message
♻️ refactor: every call is a typed struct and the legacy request path is gone

Communities, messages, social, voice and builder calls move to typed Call
structs with their reply type and gate fixed by the type, dispatched by
one exhaustive match into per domain handlers. The old Request and
Response enums, expect!, done, the wrapper layer and the 1600 line server
match are deleted.

15 changed files +3125 -2571

crates/client/src/net/link.rsmodified+1 -20
@@ -1,14 +1,12 @@
1 use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration};1 use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration};
2 2
3 use common::{3 use common::{
4- call::{Call, Legacy},4+ call::Call,
5 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},5 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},
6 error::Error,6 error::Error,
7 frame::{self, DOWN_MAX, Sending, UP_MAX},7 frame::{self, DOWN_MAX, Sending, UP_MAX},
8 model::{Attachment, User},8 model::{Attachment, User},
9 open::{Blob, Open, Upload},9 open::{Blob, Open, Upload},
10- request::LegacyRequest,
11- response::Response,
12 session::{Hello, Welcome},10 session::{Hello, Welcome},
13 transport::{Close, alpn, transport},11 transport::{Close, alpn, transport},
14 validate::{validate_attachment_name, validate_attachment_size},12 validate::{validate_attachment_name, validate_attachment_size},
@@ -265,13 +263,6 @@ pub(super) async fn call<C: Call>(
265 Ok(frame::read::<Result<C::Reply, Error>>(&mut receive_stream, DOWN_MAX).await??)263 Ok(frame::read::<Result<C::Reply, Error>>(&mut receive_stream, DOWN_MAX).await??)
266 }264 }
267 265
268-pub(super) async fn send(
269- connection: &quinn::Connection,
270- request: &LegacyRequest,
271-) -> Result<Response, Fail> {
272- call(connection, Legacy(request.clone())).await
273-}
274-
275 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {266 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {
276 let (send_stream, mut receive_stream) = connection.open_bi().await?;267 let (send_stream, mut receive_stream) = connection.open_bi().await?;
277 let mut send_stream = Sending::new(send_stream);268 let mut send_stream = Sending::new(send_stream);
@@ -285,16 +276,6 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<
285 Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??)276 Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??)
286 }277 }
287 278
288-pub(super) async fn done(
289- connection: &quinn::Connection,
290- request: LegacyRequest,
291-) -> Result<(), Fail> {
292- match send(connection, &request).await? {
293- Response::Done => Ok(()),
294- _ => Err(Fail::Protocol),
295- }
296-}
297-
298 pub(super) async fn send_body(279 pub(super) async fn send_body(
299 send_stream: &mut quinn::SendStream,280 send_stream: &mut quinn::SendStream,
300 file: &mut tokio::fs::File,281 file: &mut tokio::fs::File,
crates/client/src/net/media.rsmodified+40 -38
@@ -6,10 +6,12 @@ use std::{
6 6
7 use bytes::Bytes;7 use bytes::Bytes;
8 use common::{8 use common::{
9+ call::{
10+ Call, JoinVoice, LeaveVoice, ListShares, RequestKeyframe, StartShare, StopShare,
11+ UnwatchShare, WatchShare,
12+ },
9 datagram::{Packet, RELAY_PREFIX},13 datagram::{Packet, RELAY_PREFIX},
10 event::{Event, Media as Down},14 event::{Event, Media as Down},
11- request::LegacyRequest,
12- response::Response,
13 share::{Fps, Kind, Quality, Resolution, Source},15 share::{Fps, Kind, Quality, Resolution, Source},
14 };16 };
15 use quinn::Connection;17 use quinn::Connection;
@@ -28,10 +30,7 @@ use crate::{
28 voice::{self, Voice, VoiceSample, audio::Choice},30 voice::{self, Voice, VoiceSample, audio::Choice},
29 };31 };
30 32
31-use super::{33+use super::{link::call, *};
32- link::{done, send},
33- *,
34-};
35 34
36 const TICK: Duration = Duration::from_secs(1);35 const TICK: Duration = Duration::from_secs(1);
37 const WAIT_STEP: Duration = Duration::from_millis(100);36 const WAIT_STEP: Duration = Duration::from_millis(100);
@@ -187,7 +186,7 @@ impl Media {
187 Ok(_) if ours => Rejoin::Install,186 Ok(_) if ours => Rejoin::Install,
188 Ok(_) => {187 Ok(_) => {
189 if inner.want_voice.is_none() && inner.joining == 0 {188 if inner.want_voice.is_none() && inner.joining == 0 {
190- tokio::spawn(send_quietly(connection.clone(), LegacyRequest::LeaveVoice));189+ tokio::spawn(send_quietly(connection.clone(), LeaveVoice));
191 }190 }
192 Rejoin::Skip191 Rejoin::Skip
193 }192 }
@@ -228,7 +227,7 @@ impl Media {
228 let media = self.clone();227 let media = self.clone();
229 let connection = connection.clone();228 let connection = connection.clone();
230 tokio::spawn(async move {229 tokio::spawn(async move {
231- if send(&connection, &request).await.is_err() {230+ if call(&connection, request).await.is_err() {
232 media.lock().watching.remove(&key);231 media.lock().watching.remove(&key);
233 }232 }
234 });233 });
@@ -332,7 +331,7 @@ impl Media {
332 inner.connection.clone().ok_or(Fail::Offline)?331 inner.connection.clone().ok_or(Fail::Offline)?
333 };332 };
334 333
335- done(&connection, LegacyRequest::LeaveVoice).await334+ call(&connection, LeaveVoice).await
336 }335 }
337 336
338 async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> {337 async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> {
@@ -359,7 +358,7 @@ impl Media {
359 inner.sharing.insert(kind, sharing);358 inner.sharing.insert(kind, sharing);
360 }359 }
361 360
362- let result = done(&connection, LegacyRequest::StartShare { kind, source }).await;361+ let result = call(&connection, StartShare { kind, source }).await;
363 if result.is_err() {362 if result.is_err() {
364 self.lock().sharing.remove(&kind);363 self.lock().sharing.remove(&kind);
365 }364 }
@@ -384,9 +383,9 @@ impl Media {
384 .map_err(Fail::Io)?383 .map_err(Fail::Io)?
385 };384 };
386 385
387- done(386+ call(
388 &connection,387 &connection,
389- LegacyRequest::StartShare {388+ StartShare {
390 kind: Kind::Screen,389 kind: Kind::Screen,
391 source,390 source,
392 },391 },
@@ -398,16 +397,16 @@ impl Media {
398 self.lock().sharing.remove(&kind);397 self.lock().sharing.remove(&kind);
399 let (connection, _) = self.current_wait().await?;398 let (connection, _) = self.current_wait().await?;
400 399
401- done(&connection, LegacyRequest::StopShare { kind }).await400+ call(&connection, StopShare { kind }).await
402 }401 }
403 }402 }
404 403
405 impl Inner {404 impl Inner {
406- fn watch_requests(&self) -> Vec<((String, Kind), LegacyRequest)> {405+ fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> {
407 self.watching406 self.watching
408 .iter()407 .iter()
409 .map(|((user_id, kind), watching)| {408 .map(|((user_id, kind), watching)| {
410- let request = LegacyRequest::WatchShare {409+ let request = WatchShare {
411 user_id: user_id.clone(),410 user_id: user_id.clone(),
412 kind: *kind,411 kind: *kind,
413 quality: watching.wanted(),412 quality: watching.wanted(),
@@ -426,17 +425,15 @@ enum Rejoin {
426 }425 }
427 426
428 async fn join(connection: &Connection, community_id: &str) -> Result<Vec<String>, Fail> {427 async fn join(connection: &Connection, community_id: &str) -> Result<Vec<String>, Fail> {
429- let request = LegacyRequest::JoinVoice {428+ let request = JoinVoice {
430 community_id: community_id.to_string(),429 community_id: community_id.to_string(),
431 };430 };
432- match send(connection, &request).await? {431+
433- Response::Voice(participants) => Ok(participants),432+ call(connection, request).await
434- _ => Err(Fail::Protocol),
435- }
436 }433 }
437 434
438-async fn send_quietly(connection: Connection, request: LegacyRequest) {435+async fn send_quietly<C: Call>(connection: Connection, request: C) {
439- if let Err(error) = send(&connection, &request).await {436+ if let Err(error) = call(&connection, request).await {
440 warn!("media request failed: {error}");437 warn!("media request failed: {error}");
441 }438 }
442 }439 }
@@ -453,12 +450,20 @@ async fn tick_loop(media: Arc<Media>) {
453 continue;450 continue;
454 };451 };
455 for request in requests {452 for request in requests {
456- tokio::spawn(send_quietly(connection.clone(), request));453+ match request {
454+ Ping::Watch(request) => tokio::spawn(send_quietly(connection.clone(), request)),
455+ Ping::Keyframe(request) => tokio::spawn(send_quietly(connection.clone(), request)),
456+ };
457 }457 }
458 }458 }
459 }459 }
460 460
461-fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec<LegacyRequest> {461+enum Ping {
462+ Watch(WatchShare),
463+ Keyframe(RequestKeyframe),
464+}
465+
466+fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec<Ping> {
462 watching467 watching
463 .iter_mut()468 .iter_mut()
464 .flat_map(|((user_id, kind), watching)| {469 .flat_map(|((user_id, kind), watching)| {
@@ -467,16 +472,16 @@ fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec<LegacyRe
467 .tick()472 .tick()
468 .into_iter()473 .into_iter()
469 .map(|tick| match tick {474 .map(|tick| match tick {
470- Tick::Quality(quality) => LegacyRequest::WatchShare {475+ Tick::Quality(quality) => Ping::Watch(WatchShare {
471 user_id: user_id.clone(),476 user_id: user_id.clone(),
472 kind,477 kind,
473 quality,478 quality,
474 decode: capabilities().decode.clone(),479 decode: capabilities().decode.clone(),
475- },480+ }),
476- Tick::Keyframe => LegacyRequest::RequestKeyframe {481+ Tick::Keyframe => Ping::Keyframe(RequestKeyframe {
477 user_id: user_id.clone(),482 user_id: user_id.clone(),
478 kind,483 kind,
479- },484+ }),
480 })485 })
481 .collect::<Vec<_>>()486 .collect::<Vec<_>>()
482 })487 })
@@ -663,13 +668,10 @@ impl NetworkHandle {
663 }668 }
664 669
665 pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> {670 pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> {
666- expect!(671+ self.call(ListShares {
667- self.request(LegacyRequest::Shares {672+ community_id: community_id.to_string(),
668- community_id: community_id.to_string(),673+ })
669- })674+ .await
670- .await?,
671- Response::Shares
672- )
673 }675 }
674 676
675 pub async fn watch_share(677 pub async fn watch_share(
@@ -695,9 +697,9 @@ impl NetworkHandle {
695 }697 }
696 inner.watching.insert(key.clone(), watching);698 inner.watching.insert(key.clone(), watching);
697 }699 }
698- let result = done(700+ let result = call(
699 &connection,701 &connection,
700- LegacyRequest::WatchShare {702+ WatchShare {
701 user_id: key.0.clone(),703 user_id: key.0.clone(),
702 kind,704 kind,
703 quality,705 quality,
@@ -720,7 +722,7 @@ impl NetworkHandle {
720 .watching722 .watching
721 .remove(&(user_id.to_string(), kind));723 .remove(&(user_id.to_string(), kind));
722 724
723- self.done(LegacyRequest::UnwatchShare {725+ self.call(UnwatchShare {
724 user_id: user_id.to_string(),726 user_id: user_id.to_string(),
725 kind,727 kind,
726 })728 })
crates/client/src/net/mod.rsmodified+225 -371
@@ -2,8 +2,22 @@ use std::{path::PathBuf, sync::Arc};
2 2
3 use common::{3 use common::{
4 call::{4 call::{
5- Call, GetAvatar, GetSettings, GetUser, Legacy, ListPresences, ListSessions, RemoveAvatar,5+ AcceptFriend, AcceptInvitation, AddFriend, BanMember, BanUser, Call, ClearProfile,
6- RevokeSession, UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser,6+ ClosePoll, CreateBackup, CreateCommunity, CreateInviteCode, CreateMessage, CreatePoll,
7+ CreateUser, DeclineCall, DeclineInvitation, DeleteAttachment, DeleteBackup,
8+ DeleteCommunity, DeleteInviteCode, DeleteMessage, DeleteUser, FindUser, ForwardMessages,
9+ GetAvatar, GetCommunity, GetDailyStats, GetOverview, GetSettings, GetStorageUsage, GetUser,
10+ HandleReport, Invite, Kick, KickFromVoice, LeaveCommunity, ListAdminLogs,
11+ ListAllCommunities, ListAttachments, ListBackups, ListBans, ListCommunities, ListFriends,
12+ ListInvitations, ListInviteCodes, ListLogs, ListMembers, ListMessages, ListPins,
13+ ListPresences, ListReports, ListServerBans, ListSessions, ListUnreads, ListUsers,
14+ ListVoiceParticipants, ListVoiceRooms, Login, Logout, MarkRead, OpenDirect, OpenNotes, Pin,
15+ PurgeUser, React, Register, RemoveAvatar, RemoveFriend, RemoveServerBan, RenameUser,
16+ ReportMessage, ReportUser, ResetPassword, RevokeSession, RevokeSessions, SearchCommunity,
17+ SearchMessages, ServerMute, Session, SetCommunityVoice, SetGhost, SetRank, SetRole,
18+ SuspendUser, TimeoutUser, TransferOwnership, Typing, Unban, UpdateAvatar, UpdateCommunity,
19+ UpdateCommunityAvatar, UpdateMessage, UpdatePresence, UpdateServerSettings, UpdateStatus,
20+ UpdateUser, Vote, WatchCommunity,
7 },21 },
8 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},22 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
9 event::Event,23 event::Event,
@@ -14,8 +28,6 @@ use common::{
14 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,28 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
15 },29 },
16 open::Blob,30 open::Blob,
17- request::LegacyRequest,
18- response::Response,
19 validate::{31 validate::{
20 validate_avatar_size, validate_community_name, validate_forward, validate_new_message,32 validate_avatar_size, validate_community_name, validate_forward, validate_new_message,
21 validate_password, validate_poll, validate_reason, validate_server_settings,33 validate_password, validate_poll, validate_reason, validate_server_settings,
@@ -24,15 +36,6 @@ use common::{
24 };36 };
25 use tokio::sync::{mpsc, oneshot};37 use tokio::sync::{mpsc, oneshot};
26 38
27-macro_rules! expect {
28- ($response:expr, $variant:path) => {
29- match $response {
30- $variant(value) => Ok(value),
31- _ => Err(Fail::Protocol),
32- }
33- };
34-}
35-
36 mod datagram;39 mod datagram;
37 mod events;40 mod events;
38 mod fail;41 mod fail;
@@ -134,22 +137,14 @@ impl NetworkHandle {
134 .await137 .await
135 }138 }
136 139
137- async fn request(&self, request: LegacyRequest) -> Result<Response, Fail> {
138- self.call(Legacy(request)).await
139- }
140-
141 async fn switch(&self, token: Option<String>) -> Result<Option<User>, Fail> {140 async fn switch(&self, token: Option<String>) -> Result<Option<User>, Fail> {
142 self.ask(|reply| Command::SignIn { token, reply }).await141 self.ask(|reply| Command::SignIn { token, reply }).await
143 }142 }
144 143
145- async fn sign_in(&self, request: LegacyRequest) -> Result<(User, String), Fail> {144+ async fn sign_in(&self, session: Session) -> Result<(User, String), Fail> {
146- let (user, token) = match self.request(request).await? {145+ self.switch(Some(session.token.clone())).await?;
147- Response::Session { user, token } => (user, token),
148- _ => return Err(Fail::Protocol),
149- };
150- self.switch(Some(token.clone())).await?;
151 146
152- Ok((user, token))147+ Ok((session.user, session.token))
153 }148 }
154 149
155 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {150 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {
@@ -170,14 +165,11 @@ impl NetworkHandle {
170 pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Fail> {165 pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Fail> {
171 validate_username(username)?;166 validate_username(username)?;
172 167
173- expect!(168+ self.call(RenameUser {
174- self.request(LegacyRequest::RenameUser {169+ user_id: user_id.to_string(),
175- user_id: user_id.to_string(),170+ username: username.to_string(),
176- username: username.to_string(),171+ })
177- })172+ .await
178- .await?,
179- Response::User
180- )
181 }173 }
182 174
183 pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> {175 pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> {
@@ -202,26 +194,32 @@ impl NetworkHandle {
202 validate_username(username)?;194 validate_username(username)?;
203 validate_password(password)?;195 validate_password(password)?;
204 196
205- self.sign_in(LegacyRequest::Register {197+ let session = self
206- username: username.to_string(),198+ .call(Register {
207- password: password.to_string(),199+ username: username.to_string(),
208- invite: invite.map(str::to_string),200+ password: password.to_string(),
209- })201+ invite: invite.map(str::to_string),
210- .await202+ })
203+ .await?;
204+
205+ self.sign_in(session).await
211 }206 }
212 207
213 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {208 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {
214 validate_password(password)?;209 validate_password(password)?;
215 210
216- self.sign_in(LegacyRequest::Login {211+ let session = self
217- username: username.to_string(),212+ .call(Login {
218- password: password.to_string(),213+ username: username.to_string(),
219- })214+ password: password.to_string(),
220- .await215+ })
216+ .await?;
217+
218+ self.sign_in(session).await
221 }219 }
222 220
223 pub async fn logout(&self) -> Result<(), Fail> {221 pub async fn logout(&self) -> Result<(), Fail> {
224- let result = self.done(LegacyRequest::Logout).await;222+ let result = self.call(Logout).await;
225 self.detach().await?;223 self.detach().await?;
226 result224 result
227 }225 }
@@ -236,22 +234,18 @@ impl NetworkHandle {
236 }234 }
237 235
238 pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {236 pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {
239- expect!(237+ self.call(DeleteUser {
240- self.request(LegacyRequest::DeleteUser {238+ user_id: user_id.to_string(),
241- user_id: user_id.to_string(),239+ })
242- })240+ .await
243- .await?,
244- Response::User
245- )
246- .map(|_| ())
247 }241 }
248 242
249 pub async fn users(&self) -> Result<Vec<Account>, Fail> {243 pub async fn users(&self) -> Result<Vec<Account>, Fail> {
250- expect!(self.request(LegacyRequest::Users).await?, Response::Users)244+ self.call(ListUsers).await
251 }245 }
252 246
253 pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {247 pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {
254- self.done(LegacyRequest::SuspendUser {248+ self.call(SuspendUser {
255 user_id: user_id.to_string(),249 user_id: user_id.to_string(),
256 suspended,250 suspended,
257 })251 })
@@ -259,7 +253,7 @@ impl NetworkHandle {
259 }253 }
260 254
261 pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {255 pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {
262- self.done(LegacyRequest::TimeoutUser {256+ self.call(TimeoutUser {
263 user_id: user_id.to_string(),257 user_id: user_id.to_string(),
264 minutes,258 minutes,
265 })259 })
@@ -274,7 +268,7 @@ impl NetworkHandle {
274 ) -> Result<(), Fail> {268 ) -> Result<(), Fail> {
275 validate_reason(reason)?;269 validate_reason(reason)?;
276 270
277- self.done(LegacyRequest::BanUser {271+ self.call(BanUser {
278 user_id: user_id.to_string(),272 user_id: user_id.to_string(),
279 reason: reason.map(str::to_string),273 reason: reason.map(str::to_string),
280 scope,274 scope,
@@ -283,15 +277,11 @@ impl NetworkHandle {
283 }277 }
284 278
285 pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {279 pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {
286- expect!(280+ self.call(ListServerBans).await
287- self.request(LegacyRequest::ServerBans).await?,
288- Response::ServerBans
289- )
290 }281 }
291 282
292 pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {283 pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {
293- self.done(LegacyRequest::RemoveServerBan { id: id.to_string() })284+ self.call(RemoveServerBan { id: id.to_string() }).await
294- .await
295 }285 }
296 286
297 pub async fn create_invite_code(287 pub async fn create_invite_code(
@@ -299,29 +289,22 @@ impl NetworkHandle {
299 uses: u32,289 uses: u32,
300 hours: Option<u32>,290 hours: Option<u32>,
301 ) -> Result<InviteCode, Fail> {291 ) -> Result<InviteCode, Fail> {
302- expect!(292+ self.call(CreateInviteCode { uses, hours }).await
303- self.request(LegacyRequest::CreateInviteCode { uses, hours })
304- .await?,
305- Response::InviteCode
306- )
307 }293 }
308 294
309 pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {295 pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {
310- expect!(296+ self.call(ListInviteCodes).await
311- self.request(LegacyRequest::InviteCodes).await?,
312- Response::InviteCodes
313- )
314 }297 }
315 298
316 pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {299 pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {
317- self.done(LegacyRequest::DeleteInviteCode {300+ self.call(DeleteInviteCode {
318 code: code.to_string(),301 code: code.to_string(),
319 })302 })
320 .await303 .await
321 }304 }
322 305
323 pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {306 pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {
324- self.done(LegacyRequest::RevokeSessions {307+ self.call(RevokeSessions {
325 user_id: user_id.to_string(),308 user_id: user_id.to_string(),
326 })309 })
327 .await310 .await
@@ -330,7 +313,7 @@ impl NetworkHandle {
330 pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {313 pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {
331 validate_password(password)?;314 validate_password(password)?;
332 315
333- self.done(LegacyRequest::ResetPassword {316+ self.call(ResetPassword {
334 user_id: user_id.to_string(),317 user_id: user_id.to_string(),
335 password: password.to_string(),318 password: password.to_string(),
336 })319 })
@@ -338,24 +321,18 @@ impl NetworkHandle {
338 }321 }
339 322
340 pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {323 pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {
341- expect!(324+ self.call(ClearProfile {
342- self.request(LegacyRequest::ClearProfile {325+ user_id: user_id.to_string(),
343- user_id: user_id.to_string(),326+ })
344- })327+ .await
345- .await?,
346- Response::User
347- )
348 }328 }
349 329
350 pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {330 pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {
351- expect!(331+ self.call(SetRole {
352- self.request(LegacyRequest::SetRole {332+ user_id: user_id.to_string(),
353- user_id: user_id.to_string(),333+ role,
354- role,334+ })
355- })335+ .await
356- .await?,
357- Response::User
358- )
359 }336 }
360 337
361 pub async fn admin_logs(338 pub async fn admin_logs(
@@ -366,21 +343,18 @@ impl NetworkHandle {
366 after_ms: Option<u64>,343 after_ms: Option<u64>,
367 before_ms: Option<u64>,344 before_ms: Option<u64>,
368 ) -> Result<Vec<AdminLogEntry>, Fail> {345 ) -> Result<Vec<AdminLogEntry>, Fail> {
369- let request = LegacyRequest::AdminLogs {346+ self.call(ListAdminLogs {
370 actor_id,347 actor_id,
371 target_id,348 target_id,
372 action,349 action,
373 after_ms,350 after_ms,
374 before_ms,351 before_ms,
375- };352+ })
376- expect!(self.request(request).await?, Response::AdminLogs)353+ .await
377 }354 }
378 355
379 pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {356 pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {
380- expect!(357+ self.call(GetDailyStats { days }).await
381- self.request(LegacyRequest::DailyStats { days }).await?,
382- Response::DailyStats
383- )
384 }358 }
385 359
386 pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {360 pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {
@@ -393,43 +367,30 @@ impl NetworkHandle {
393 ) -> Result<ServerSettings, Fail> {367 ) -> Result<ServerSettings, Fail> {
394 validate_server_settings(&settings)?;368 validate_server_settings(&settings)?;
395 369
396- expect!(370+ self.call(UpdateServerSettings { settings }).await
397- self.request(LegacyRequest::UpdateServerSettings { settings })
398- .await?,
399- Response::ServerSettings
400- )
401 }371 }
402 372
403 pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Fail> {373 pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Fail> {
404 validate_username(username)?;374 validate_username(username)?;
405 validate_password(password)?;375 validate_password(password)?;
406 376
407- expect!(377+ self.call(CreateUser {
408- self.request(LegacyRequest::CreateUser {378+ username: username.to_string(),
409- username: username.to_string(),379+ password: password.to_string(),
410- password: password.to_string(),380+ })
411- })381+ .await
412- .await?,
413- Response::User
414- )
415 }382 }
416 383
417 pub async fn overview(&self) -> Result<Overview, Fail> {384 pub async fn overview(&self) -> Result<Overview, Fail> {
418- expect!(385+ self.call(GetOverview).await
419- self.request(LegacyRequest::Overview).await?,
420- Response::Overview
421- )
422 }386 }
423 387
424 pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {388 pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {
425- expect!(389+ self.call(ListAllCommunities).await
426- self.request(LegacyRequest::AllCommunities).await?,
427- Response::AllCommunities
428- )
429 }390 }
430 391
431 pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {392 pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
432- self.done(LegacyRequest::TransferOwnership {393+ self.call(TransferOwnership {
433 community_id: community_id.to_string(),394 community_id: community_id.to_string(),
434 user_id: user_id.to_string(),395 user_id: user_id.to_string(),
435 })396 })
@@ -446,13 +407,10 @@ impl NetworkHandle {
446 pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {407 pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {
447 validate_community_name(name)?;408 validate_community_name(name)?;
448 409
449- expect!(410+ self.call(CreateCommunity {
450- self.request(LegacyRequest::CreateCommunity {411+ name: name.to_string(),
451- name: name.to_string(),412+ })
452- })413+ .await
453- .await?,
454- Response::Community
455- )
456 }414 }
457 415
458 pub async fn update_community(416 pub async fn update_community(
@@ -462,49 +420,36 @@ impl NetworkHandle {
462 ) -> Result<Community, Fail> {420 ) -> Result<Community, Fail> {
463 validate_community_name(name)?;421 validate_community_name(name)?;
464 422
465- expect!(423+ self.call(UpdateCommunity {
466- self.request(LegacyRequest::UpdateCommunity {424+ community_id: community_id.to_string(),
467- community_id: community_id.to_string(),425+ name: name.to_string(),
468- name: name.to_string(),426+ })
469- })427+ .await
470- .await?,
471- Response::Community
472- )
473 }428 }
474 429
475 pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {430 pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {
476- expect!(431+ self.call(DeleteCommunity {
477- self.request(LegacyRequest::DeleteCommunity {432+ community_id: community_id.to_string(),
478- community_id: community_id.to_string(),433+ })
479- })434+ .await
480- .await?,
481- Response::Community
482- )
483- .map(|_| ())
484 }435 }
485 436
486 pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {437 pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {
487- self.done(LegacyRequest::LeaveCommunity {438+ self.call(LeaveCommunity {
488 community_id: community_id.to_string(),439 community_id: community_id.to_string(),
489 })440 })
490 .await441 .await
491 }442 }
492 443
493 pub async fn communities(&self) -> Result<Vec<Community>, Fail> {444 pub async fn communities(&self) -> Result<Vec<Community>, Fail> {
494- expect!(445+ self.call(ListCommunities).await
495- self.request(LegacyRequest::Communities).await?,
496- Response::Communities
497- )
498 }446 }
499 447
500 pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {448 pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {
501- expect!(449+ self.call(ListMembers {
502- self.request(LegacyRequest::Members {450+ community_id: community_id.to_string(),
503- community_id: community_id.to_string(),451+ })
504- })452+ .await
505- .await?,
506- Response::Members
507- )
508 }453 }
509 454
510 pub async fn kick(455 pub async fn kick(
@@ -514,7 +459,7 @@ impl NetworkHandle {
514 reason: Option<&str>,459 reason: Option<&str>,
515 ) -> Result<(), Fail> {460 ) -> Result<(), Fail> {
516 validate_reason(reason)?;461 validate_reason(reason)?;
517- self.done(LegacyRequest::Kick {462+ self.call(Kick {
518 community_id: community_id.to_string(),463 community_id: community_id.to_string(),
519 user_id: user_id.to_string(),464 user_id: user_id.to_string(),
520 reason: reason.map(str::to_string),465 reason: reason.map(str::to_string),
@@ -529,7 +474,7 @@ impl NetworkHandle {
529 reason: Option<&str>,474 reason: Option<&str>,
530 ) -> Result<(), Fail> {475 ) -> Result<(), Fail> {
531 validate_reason(reason)?;476 validate_reason(reason)?;
532- self.done(LegacyRequest::Ban {477+ self.call(BanMember {
533 community_id: community_id.to_string(),478 community_id: community_id.to_string(),
534 user_id: user_id.to_string(),479 user_id: user_id.to_string(),
535 reason: reason.map(str::to_string),480 reason: reason.map(str::to_string),
@@ -538,7 +483,7 @@ impl NetworkHandle {
538 }483 }
539 484
540 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {485 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
541- self.done(LegacyRequest::Unban {486+ self.call(Unban {
542 community_id: community_id.to_string(),487 community_id: community_id.to_string(),
543 user_id: user_id.to_string(),488 user_id: user_id.to_string(),
544 })489 })
@@ -546,23 +491,17 @@ impl NetworkHandle {
546 }491 }
547 492
548 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {493 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {
549- expect!(494+ self.call(ListBans {
550- self.request(LegacyRequest::Bans {495+ community_id: community_id.to_string(),
551- community_id: community_id.to_string(),496+ })
552- })497+ .await
553- .await?,
554- Response::Bans
555- )
556 }498 }
557 499
558 pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {500 pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {
559- expect!(501+ self.call(ListLogs {
560- self.request(LegacyRequest::Logs {502+ community_id: community_id.to_string(),
561- community_id: community_id.to_string(),503+ })
562- })504+ .await
563- .await?,
564- Response::Logs
565- )
566 }505 }
567 506
568 pub async fn set_rank(507 pub async fn set_rank(
@@ -571,7 +510,7 @@ impl NetworkHandle {
571 user_id: &str,510 user_id: &str,
572 rank: Rank,511 rank: Rank,
573 ) -> Result<(), Fail> {512 ) -> Result<(), Fail> {
574- self.done(LegacyRequest::SetRank {513+ self.call(SetRank {
575 community_id: community_id.to_string(),514 community_id: community_id.to_string(),
576 user_id: user_id.to_string(),515 user_id: user_id.to_string(),
577 rank,516 rank,
@@ -580,14 +519,10 @@ impl NetworkHandle {
580 }519 }
581 520
582 pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {521 pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {
583- expect!(522+ self.call(DeleteMessage {
584- self.request(LegacyRequest::DeleteMessage {523+ message_id: message_id.to_string(),
585- message_id: message_id.to_string(),524+ })
586- })525+ .await
587- .await?,
588- Response::Message
589- )
590- .map(|_| ())
591 }526 }
592 527
593 pub async fn create_message(528 pub async fn create_message(
@@ -599,29 +534,23 @@ impl NetworkHandle {
599 ) -> Result<Message, Fail> {534 ) -> Result<Message, Fail> {
600 validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;535 validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
601 536
602- expect!(537+ self.call(CreateMessage {
603- self.request(LegacyRequest::CreateMessage {538+ community_id: community_id.to_string(),
604- community_id: community_id.to_string(),539+ body: body.to_string(),
605- body: body.to_string(),540+ attachments,
606- attachments,541+ reply_to,
607- reply_to,542+ })
608- })543+ .await
609- .await?,
610- Response::Message
611- )
612 }544 }
613 545
614 pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Fail> {546 pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Fail> {
615 validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;547 validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;
616 548
617- expect!(549+ self.call(UpdateMessage {
618- self.request(LegacyRequest::UpdateMessage {550+ message_id: message_id.to_string(),
619- message_id: message_id.to_string(),551+ body: body.to_string(),
620- body: body.to_string(),552+ })
621- })553+ .await
622- .await?,
623- Response::Message
624- )
625 }554 }
626 555
627 pub async fn forward_messages(556 pub async fn forward_messages(
@@ -632,49 +561,34 @@ impl NetworkHandle {
632 ) -> Result<Vec<Message>, Fail> {561 ) -> Result<Vec<Message>, Fail> {
633 validate_forward(message_ids.len())?;562 validate_forward(message_ids.len())?;
634 563
635- expect!(564+ self.call(ForwardMessages {
636- self.request(LegacyRequest::ForwardMessages {565+ message_ids,
637- message_ids,566+ community_id: community_id.to_string(),
638- community_id: community_id.to_string(),567+ snippet,
639- snippet,568+ })
640- })569+ .await
641- .await?,
642- Response::Messages
643- )
644 }570 }
645 571
646 pub async fn find_user(&self, username: &str) -> Result<User, Fail> {572 pub async fn find_user(&self, username: &str) -> Result<User, Fail> {
647- expect!(573+ self.call(FindUser {
648- self.request(LegacyRequest::FindUser {574+ username: username.to_string(),
649- username: username.to_string(),575+ })
650- })576+ .await
651- .await?,
652- Response::User
653- )
654 }577 }
655 578
656 pub async fn open_notes(&self) -> Result<Community, Fail> {579 pub async fn open_notes(&self) -> Result<Community, Fail> {
657- expect!(580+ self.call(OpenNotes).await
658- self.request(LegacyRequest::OpenNotes).await?,
659- Response::Community
660- )
661 }581 }
662 582
663 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {583 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {
664- expect!(584+ self.call(OpenDirect {
665- self.request(LegacyRequest::OpenDirect {585+ user_id: user_id.to_string(),
666- user_id: user_id.to_string(),586+ })
667- })587+ .await
668- .await?,
669- Response::Community
670- )
671 }588 }
672 589
673 pub async fn friends(&self) -> Result<Friends, Fail> {590 pub async fn friends(&self) -> Result<Friends, Fail> {
674- expect!(591+ self.call(ListFriends).await
675- self.request(LegacyRequest::Friends).await?,
676- Response::Friends
677- )
678 }592 }
679 593
680 pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {594 pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {
@@ -686,28 +600,28 @@ impl NetworkHandle {
686 }600 }
687 601
688 pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {602 pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {
689- self.done(LegacyRequest::AddFriend {603+ self.call(AddFriend {
690 user_id: user_id.to_string(),604 user_id: user_id.to_string(),
691 })605 })
692 .await606 .await
693 }607 }
694 608
695 pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {609 pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {
696- self.done(LegacyRequest::AcceptFriend {610+ self.call(AcceptFriend {
697 user_id: user_id.to_string(),611 user_id: user_id.to_string(),
698 })612 })
699 .await613 .await
700 }614 }
701 615
702 pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {616 pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {
703- self.done(LegacyRequest::RemoveFriend {617+ self.call(RemoveFriend {
704 user_id: user_id.to_string(),618 user_id: user_id.to_string(),
705 })619 })
706 .await620 .await
707 }621 }
708 622
709 pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {623 pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
710- self.done(LegacyRequest::Invite {624+ self.call(Invite {
711 community_id: community_id.to_string(),625 community_id: community_id.to_string(),
712 user_id: user_id.to_string(),626 user_id: user_id.to_string(),
713 })627 })
@@ -715,38 +629,32 @@ impl NetworkHandle {
715 }629 }
716 630
717 pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {631 pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {
718- expect!(632+ self.call(ListInvitations).await
719- self.request(LegacyRequest::Invitations).await?,
720- Response::Invitations
721- )
722 }633 }
723 634
724 pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {635 pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {
725- expect!(636+ self.call(AcceptInvitation {
726- self.request(LegacyRequest::AcceptInvitation {637+ community_id: community_id.to_string(),
727- community_id: community_id.to_string(),638+ })
728- })639+ .await
729- .await?,
730- Response::Community
731- )
732 }640 }
733 641
734 pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {642 pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {
735- self.done(LegacyRequest::DeclineInvitation {643+ self.call(DeclineInvitation {
736 community_id: community_id.to_string(),644 community_id: community_id.to_string(),
737 })645 })
738 .await646 .await
739 }647 }
740 648
741 pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {649 pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {
742- self.done(LegacyRequest::DeclineCall {650+ self.call(DeclineCall {
743 community_id: community_id.to_string(),651 community_id: community_id.to_string(),
744 })652 })
745 .await653 .await
746 }654 }
747 655
748 pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {656 pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {
749- self.done(LegacyRequest::React {657+ self.call(React {
750 message_id: message_id.to_string(),658 message_id: message_id.to_string(),
751 emoji: emoji.to_string(),659 emoji: emoji.to_string(),
752 })660 })
@@ -754,7 +662,7 @@ impl NetworkHandle {
754 }662 }
755 663
756 pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {664 pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {
757- self.done(LegacyRequest::Pin {665+ self.call(Pin {
758 message_id: message_id.to_string(),666 message_id: message_id.to_string(),
759 pinned,667 pinned,
760 })668 })
@@ -762,13 +670,10 @@ impl NetworkHandle {
762 }670 }
763 671
764 pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {672 pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {
765- expect!(673+ self.call(ListPins {
766- self.request(LegacyRequest::Pins {674+ community_id: community_id.to_string(),
767- community_id: community_id.to_string(),675+ })
768- })676+ .await
769- .await?,
770- Response::Messages
771- )
772 }677 }
773 678
774 pub async fn create_poll(679 pub async fn create_poll(
@@ -780,20 +685,17 @@ impl NetworkHandle {
780 ) -> Result<Message, Fail> {685 ) -> Result<Message, Fail> {
781 validate_poll(question, &options)?;686 validate_poll(question, &options)?;
782 687
783- expect!(688+ self.call(CreatePoll {
784- self.request(LegacyRequest::CreatePoll {689+ community_id: community_id.to_string(),
785- community_id: community_id.to_string(),690+ question: question.to_string(),
786- question: question.to_string(),691+ options,
787- options,692+ multiple,
788- multiple,693+ })
789- })694+ .await
790- .await?,
791- Response::Message
792- )
793 }695 }
794 696
795 pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {697 pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {
796- self.done(LegacyRequest::Vote {698+ self.call(Vote {
797 message_id: message_id.to_string(),699 message_id: message_id.to_string(),
798 positions,700 positions,
799 })701 })
@@ -801,7 +703,7 @@ impl NetworkHandle {
801 }703 }
802 704
803 pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {705 pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {
804- self.done(LegacyRequest::ClosePoll {706+ self.call(ClosePoll {
805 message_id: message_id.to_string(),707 message_id: message_id.to_string(),
806 })708 })
807 .await709 .await
@@ -810,7 +712,7 @@ impl NetworkHandle {
810 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {712 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {
811 validate_reason(Some(reason))?;713 validate_reason(Some(reason))?;
812 714
813- self.done(LegacyRequest::ReportMessage {715+ self.call(ReportMessage {
814 message_id: message_id.to_string(),716 message_id: message_id.to_string(),
815 reason: reason.to_string(),717 reason: reason.to_string(),
816 })718 })
@@ -820,7 +722,7 @@ impl NetworkHandle {
820 pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {722 pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {
821 validate_reason(Some(reason))?;723 validate_reason(Some(reason))?;
822 724
823- self.done(LegacyRequest::ReportUser {725+ self.call(ReportUser {
824 user_id: user_id.to_string(),726 user_id: user_id.to_string(),
825 reason: reason.to_string(),727 reason: reason.to_string(),
826 })728 })
@@ -828,14 +730,11 @@ impl NetworkHandle {
828 }730 }
829 731
830 pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {732 pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {
831- expect!(733+ self.call(ListReports { status }).await
832- self.request(LegacyRequest::Reports { status }).await?,
833- Response::Reports
834- )
835 }734 }
836 735
837 pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {736 pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {
838- self.done(LegacyRequest::HandleReport {737+ self.call(HandleReport {
839 report_id: report_id.to_string(),738 report_id: report_id.to_string(),
840 status,739 status,
841 })740 })
@@ -850,17 +749,14 @@ impl NetworkHandle {
850 after_ms: Option<u64>,749 after_ms: Option<u64>,
851 before_ms: Option<u64>,750 before_ms: Option<u64>,
852 ) -> Result<Vec<MessageHit>, Fail> {751 ) -> Result<Vec<MessageHit>, Fail> {
853- expect!(752+ self.call(SearchMessages {
854- self.request(LegacyRequest::SearchMessages {753+ text,
855- text,754+ user_id,
856- user_id,755+ community_id,
857- community_id,756+ after_ms,
858- after_ms,757+ before_ms,
859- before_ms,758+ })
860- })759+ .await
861- .await?,
862- Response::MessageHits
863- )
864 }760 }
865 761
866 pub async fn search_community(762 pub async fn search_community(
@@ -868,36 +764,25 @@ impl NetworkHandle {
868 community_id: String,764 community_id: String,
869 text: String,765 text: String,
870 ) -> Result<Vec<MessageHit>, Fail> {766 ) -> Result<Vec<MessageHit>, Fail> {
871- expect!(767+ self.call(SearchCommunity { community_id, text }).await
872- self.request(LegacyRequest::SearchCommunity { community_id, text })
873- .await?,
874- Response::MessageHits
875- )
876 }768 }
877 769
878 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {770 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {
879- match self.request(LegacyRequest::StorageUsage).await? {771+ let usage = self.call(GetStorageUsage).await?;
880- Response::StorageUsage { users, communities } => Ok((users, communities)),772+
881- _ => Err(Fail::Protocol),773+ Ok((usage.users, usage.communities))
882- }
883 }774 }
884 775
885 pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {776 pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {
886- expect!(777+ self.call(CreateBackup).await
887- self.request(LegacyRequest::CreateBackup).await?,
888- Response::Backup
889- )
890 }778 }
891 779
892 pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {780 pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {
893- expect!(781+ self.call(ListBackups).await
894- self.request(LegacyRequest::Backups).await?,
895- Response::Backups
896- )
897 }782 }
898 783
899 pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {784 pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {
900- self.done(LegacyRequest::DeleteBackup {785+ self.call(DeleteBackup {
901 name: name.to_string(),786 name: name.to_string(),
902 })787 })
903 .await788 .await
@@ -908,37 +793,27 @@ impl NetworkHandle {
908 user_id: Option<String>,793 user_id: Option<String>,
909 community_id: Option<String>,794 community_id: Option<String>,
910 ) -> Result<Vec<AttachmentInfo>, Fail> {795 ) -> Result<Vec<AttachmentInfo>, Fail> {
911- expect!(796+ self.call(ListAttachments {
912- self.request(LegacyRequest::AllAttachments {797+ user_id,
913- user_id,798+ community_id,
914- community_id,799+ })
915- })800+ .await
916- .await?,
917- Response::AttachmentInfos
918- )
919 }801 }
920 802
921 pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {803 pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {
922- self.done(LegacyRequest::DeleteAttachment {804+ self.call(DeleteAttachment {
923 attachment_id: attachment_id.to_string(),805 attachment_id: attachment_id.to_string(),
924 })806 })
925 .await807 .await
926 }808 }
927 809
928 pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {810 pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {
929- self.done(LegacyRequest::PurgeUser {811+ self.call(PurgeUser {
930 user_id: user_id.to_string(),812 user_id: user_id.to_string(),
931 })813 })
932 .await814 .await
933 }815 }
934 816
935- async fn done(&self, request: LegacyRequest) -> Result<(), Fail> {
936- match self.request(request).await? {
937- Response::Done => Ok(()),
938- _ => Err(Fail::Protocol),
939- }
940- }
941-
942 pub async fn upload_attachment(817 pub async fn upload_attachment(
943 &self,818 &self,
944 community_id: &str,819 community_id: &str,
@@ -978,7 +853,7 @@ impl NetworkHandle {
978 }853 }
979 854
980 pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> {855 pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> {
981- self.done(LegacyRequest::WatchCommunity {856+ self.call(WatchCommunity {
982 community_id: community_id.map(str::to_string),857 community_id: community_id.map(str::to_string),
983 })858 })
984 .await859 .await
@@ -989,25 +864,19 @@ impl NetworkHandle {
989 community_id: &str,864 community_id: &str,
990 before: Option<&str>,865 before: Option<&str>,
991 ) -> Result<Vec<Message>, Fail> {866 ) -> Result<Vec<Message>, Fail> {
992- expect!(867+ self.call(ListMessages {
993- self.request(LegacyRequest::ReadMessages {868+ community_id: community_id.to_string(),
994- community_id: community_id.to_string(),869+ before: before.map(str::to_string),
995- before: before.map(str::to_string),870+ })
996- })871+ .await
997- .await?,
998- Response::Messages
999- )
1000 }872 }
1001 873
1002 pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {874 pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {
1003- expect!(875+ self.call(ListUnreads).await
1004- self.request(LegacyRequest::Unreads).await?,
1005- Response::Unreads
1006- )
1007 }876 }
1008 877
1009 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {878 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {
1010- self.done(LegacyRequest::MarkRead {879+ self.call(MarkRead {
1011 community_id: community_id.to_string(),880 community_id: community_id.to_string(),
1012 message_id: message_id.to_string(),881 message_id: message_id.to_string(),
1013 })882 })
@@ -1038,14 +907,11 @@ impl NetworkHandle {
1038 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;907 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1039 }908 }
1040 909
1041- expect!(910+ self.call(UpdateCommunityAvatar {
1042- self.request(LegacyRequest::UpdateCommunityAvatar {911+ community_id: community_id.to_string(),
1043- community_id: community_id.to_string(),912+ image,
1044- image,913+ })
1045- })914+ .await
1046- .await?,
1047- Response::Community
1048- )
1049 }915 }
1050 916
1051 pub async fn remove_avatar(&self) -> Result<User, Fail> {917 pub async fn remove_avatar(&self) -> Result<User, Fail> {
@@ -1060,52 +926,43 @@ impl NetworkHandle {
1060 }926 }
1061 927
1062 pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {928 pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {
1063- self.done(LegacyRequest::Typing {929+ self.call(Typing {
1064 community_id: community_id.to_string(),930 community_id: community_id.to_string(),
1065 })931 })
1066 .await932 .await
1067 }933 }
1068 934
1069 pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {935 pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {
1070- expect!(936+ self.call(GetCommunity {
1071- self.request(LegacyRequest::ReadCommunity {937+ community_id: community_id.to_string(),
1072- community_id: community_id.to_string(),938+ })
1073- })939+ .await
1074- .await?,
1075- Response::Community
1076- )
1077 }940 }
1078 941
1079 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {942 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {
1080- expect!(943+ self.call(ListVoiceParticipants {
1081- self.request(LegacyRequest::VoiceParticipants {944+ community_id: community_id.to_string(),
1082- community_id: community_id.to_string(),945+ })
1083- })946+ .await
1084- .await?,
1085- Response::Voice
1086- )
1087 }947 }
1088 948
1089 pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {949 pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {
1090- expect!(950+ self.call(ListVoiceRooms).await
1091- self.request(LegacyRequest::VoiceRooms).await?,
1092- Response::VoiceRooms
1093- )
1094 }951 }
1095 952
1096 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {953 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {
1097- self.done(LegacyRequest::SetGhost { enabled }).await954+ self.call(SetGhost { enabled }).await
1098 }955 }
1099 956
1100 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {957 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {
1101- self.done(LegacyRequest::KickFromVoice {958+ self.call(KickFromVoice {
1102 user_id: user_id.to_string(),959 user_id: user_id.to_string(),
1103 })960 })
1104 .await961 .await
1105 }962 }
1106 963
1107 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {964 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {
1108- self.done(LegacyRequest::ServerMute {965+ self.call(ServerMute {
1109 user_id: user_id.to_string(),966 user_id: user_id.to_string(),
1110 muted,967 muted,
1111 })968 })
@@ -1117,13 +974,10 @@ impl NetworkHandle {
1117 community_id: &str,974 community_id: &str,
1118 enabled: bool,975 enabled: bool,
1119 ) -> Result<Community, Fail> {976 ) -> Result<Community, Fail> {
1120- expect!(977+ self.call(SetCommunityVoice {
1121- self.request(LegacyRequest::SetCommunityVoice {978+ community_id: community_id.to_string(),
1122- community_id: community_id.to_string(),979+ enabled,
1123- enabled,980+ })
1124- })981+ .await
1125- .await?,
1126- Response::Community
1127- )
1128 }982 }
1129 }983 }
crates/common/src/call.rsmodified+603 -7
@@ -1,9 +1,13 @@
1 use bitcode::{Decode, DecodeOwned, Encode};1 use bitcode::{Decode, DecodeOwned, Encode};
2 2
3 use crate::{3 use crate::{
4- model::{Presence, ServerSettings, SessionInfo, User},4+ model::{
5- request::LegacyRequest,5+ Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
6- response::Response,6+ CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
7+ Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,
8+ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
9+ },
10+ share::{Codec, Kind, Quality, Share, Source},
7 };11 };
8 12
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]13 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -40,9 +44,6 @@ macro_rules! calls {
40 };44 };
41 }45 }
42 46
43-#[derive(Debug, Clone, Encode, Decode)]
44-pub struct Legacy(pub LegacyRequest);
45-
46 #[derive(Debug, Clone, Encode, Decode)]47 #[derive(Debug, Clone, Encode, Decode)]
47 pub struct GetSettings;48 pub struct GetSettings;
48 49
@@ -93,8 +94,510 @@ pub struct RevokeSession {
93 pub session_id: String,94 pub session_id: String,
94 }95 }
95 96
97+#[derive(Debug, Clone, Encode, Decode)]
98+pub struct CreateCommunity {
99+ pub name: String,
100+}
101+
102+#[derive(Debug, Clone, Encode, Decode)]
103+pub struct GetCommunity {
104+ pub community_id: String,
105+}
106+
107+#[derive(Debug, Clone, Encode, Decode)]
108+pub struct UpdateCommunity {
109+ pub community_id: String,
110+ pub name: String,
111+}
112+
113+#[derive(Debug, Clone, Encode, Decode)]
114+pub struct UpdateCommunityAvatar {
115+ pub community_id: String,
116+ pub image: Option<Vec<u8>>,
117+}
118+
119+#[derive(Debug, Clone, Encode, Decode)]
120+pub struct DeleteCommunity {
121+ pub community_id: String,
122+}
123+
124+#[derive(Debug, Clone, Encode, Decode)]
125+pub struct LeaveCommunity {
126+ pub community_id: String,
127+}
128+
129+#[derive(Debug, Clone, Encode, Decode)]
130+pub struct ListCommunities;
131+
132+#[derive(Debug, Clone, Encode, Decode)]
133+pub struct ListMembers {
134+ pub community_id: String,
135+}
136+
137+#[derive(Debug, Clone, Encode, Decode)]
138+pub struct Kick {
139+ pub community_id: String,
140+ pub user_id: String,
141+ pub reason: Option<String>,
142+}
143+
144+#[derive(Debug, Clone, Encode, Decode)]
145+pub struct BanMember {
146+ pub community_id: String,
147+ pub user_id: String,
148+ pub reason: Option<String>,
149+}
150+
151+#[derive(Debug, Clone, Encode, Decode)]
152+pub struct Unban {
153+ pub community_id: String,
154+ pub user_id: String,
155+}
156+
157+#[derive(Debug, Clone, Encode, Decode)]
158+pub struct ListBans {
159+ pub community_id: String,
160+}
161+
162+#[derive(Debug, Clone, Encode, Decode)]
163+pub struct SetRank {
164+ pub community_id: String,
165+ pub user_id: String,
166+ pub rank: Rank,
167+}
168+
169+#[derive(Debug, Clone, Encode, Decode)]
170+pub struct ListLogs {
171+ pub community_id: String,
172+}
173+
174+#[derive(Debug, Clone, Encode, Decode)]
175+pub struct CreateMessage {
176+ pub community_id: String,
177+ pub body: String,
178+ pub attachments: Vec<String>,
179+ pub reply_to: Option<String>,
180+}
181+
182+#[derive(Debug, Clone, Encode, Decode)]
183+pub struct ForwardMessages {
184+ pub message_ids: Vec<String>,
185+ pub community_id: String,
186+ pub snippet: bool,
187+}
188+
189+#[derive(Debug, Clone, Encode, Decode)]
190+pub struct UpdateMessage {
191+ pub message_id: String,
192+ pub body: String,
193+}
194+
195+#[derive(Debug, Clone, Encode, Decode)]
196+pub struct DeleteMessage {
197+ pub message_id: String,
198+}
199+
200+#[derive(Debug, Clone, Encode, Decode)]
201+pub struct CreatePoll {
202+ pub community_id: String,
203+ pub question: String,
204+ pub options: Vec<String>,
205+ pub multiple: bool,
206+}
207+
208+#[derive(Debug, Clone, Encode, Decode)]
209+pub struct Vote {
210+ pub message_id: String,
211+ pub positions: Vec<u32>,
212+}
213+
214+#[derive(Debug, Clone, Encode, Decode)]
215+pub struct ClosePoll {
216+ pub message_id: String,
217+}
218+
219+#[derive(Debug, Clone, Encode, Decode)]
220+pub struct React {
221+ pub message_id: String,
222+ pub emoji: String,
223+}
224+
225+#[derive(Debug, Clone, Encode, Decode)]
226+pub struct Pin {
227+ pub message_id: String,
228+ pub pinned: bool,
229+}
230+
231+#[derive(Debug, Clone, Encode, Decode)]
232+pub struct ListPins {
233+ pub community_id: String,
234+}
235+
236+#[derive(Debug, Clone, Encode, Decode)]
237+pub struct ListMessages {
238+ pub community_id: String,
239+ pub before: Option<String>,
240+}
241+
242+#[derive(Debug, Clone, Encode, Decode)]
243+pub struct ListUnreads;
244+
245+#[derive(Debug, Clone, Encode, Decode)]
246+pub struct MarkRead {
247+ pub community_id: String,
248+ pub message_id: String,
249+}
250+
251+#[derive(Debug, Clone, Encode, Decode)]
252+pub struct Typing {
253+ pub community_id: String,
254+}
255+
256+#[derive(Debug, Clone, Encode, Decode)]
257+pub struct FindUser {
258+ pub username: String,
259+}
260+
261+#[derive(Debug, Clone, Encode, Decode)]
262+pub struct OpenDirect {
263+ pub user_id: String,
264+}
265+
266+#[derive(Debug, Clone, Encode, Decode)]
267+pub struct OpenNotes;
268+
269+#[derive(Debug, Clone, Encode, Decode)]
270+pub struct ListFriends;
271+
272+#[derive(Debug, Clone, Encode, Decode)]
273+pub struct AddFriend {
274+ pub user_id: String,
275+}
276+
277+#[derive(Debug, Clone, Encode, Decode)]
278+pub struct AcceptFriend {
279+ pub user_id: String,
280+}
281+
282+#[derive(Debug, Clone, Encode, Decode)]
283+pub struct RemoveFriend {
284+ pub user_id: String,
285+}
286+
287+#[derive(Debug, Clone, Encode, Decode)]
288+pub struct Invite {
289+ pub community_id: String,
290+ pub user_id: String,
291+}
292+
293+#[derive(Debug, Clone, Encode, Decode)]
294+pub struct ListInvitations;
295+
296+#[derive(Debug, Clone, Encode, Decode)]
297+pub struct AcceptInvitation {
298+ pub community_id: String,
299+}
300+
301+#[derive(Debug, Clone, Encode, Decode)]
302+pub struct DeclineInvitation {
303+ pub community_id: String,
304+}
305+
306+#[derive(Debug, Clone, Encode, Decode)]
307+pub struct ReportMessage {
308+ pub message_id: String,
309+ pub reason: String,
310+}
311+
312+#[derive(Debug, Clone, Encode, Decode)]
313+pub struct ReportUser {
314+ pub user_id: String,
315+ pub reason: String,
316+}
317+
318+#[derive(Debug, Clone, Encode, Decode)]
319+pub struct ListReports {
320+ pub status: Option<ReportStatus>,
321+}
322+
323+#[derive(Debug, Clone, Encode, Decode)]
324+pub struct HandleReport {
325+ pub report_id: String,
326+ pub status: ReportStatus,
327+}
328+
329+#[derive(Debug, Clone, Encode, Decode)]
330+pub struct JoinVoice {
331+ pub community_id: String,
332+}
333+
334+#[derive(Debug, Clone, Encode, Decode)]
335+pub struct LeaveVoice;
336+
337+#[derive(Debug, Clone, Encode, Decode)]
338+pub struct StartShare {
339+ pub kind: Kind,
340+ pub source: Source,
341+}
342+
343+#[derive(Debug, Clone, Encode, Decode)]
344+pub struct StopShare {
345+ pub kind: Kind,
346+}
347+
348+#[derive(Debug, Clone, Encode, Decode)]
349+pub struct ListShares {
350+ pub community_id: String,
351+}
352+
353+#[derive(Debug, Clone, Encode, Decode)]
354+pub struct WatchShare {
355+ pub user_id: String,
356+ pub kind: Kind,
357+ pub quality: Quality,
358+ pub decode: Vec<Codec>,
359+}
360+
361+#[derive(Debug, Clone, Encode, Decode)]
362+pub struct UnwatchShare {
363+ pub user_id: String,
364+ pub kind: Kind,
365+}
366+
367+#[derive(Debug, Clone, Encode, Decode)]
368+pub struct RequestKeyframe {
369+ pub user_id: String,
370+ pub kind: Kind,
371+}
372+
373+#[derive(Debug, Clone, Encode, Decode)]
374+pub struct DeclineCall {
375+ pub community_id: String,
376+}
377+
378+#[derive(Debug, Clone, Encode, Decode)]
379+pub struct ListVoiceParticipants {
380+ pub community_id: String,
381+}
382+
383+#[derive(Debug, Clone, Encode, Decode)]
384+pub struct ListVoiceRooms;
385+
386+#[derive(Debug, Clone, Encode, Decode)]
387+pub struct KickFromVoice {
388+ pub user_id: String,
389+}
390+
391+#[derive(Debug, Clone, Encode, Decode)]
392+pub struct ServerMute {
393+ pub user_id: String,
394+ pub muted: bool,
395+}
396+
397+#[derive(Debug, Clone, Encode, Decode)]
398+pub struct Register {
399+ pub username: String,
400+ pub password: String,
401+ pub invite: Option<String>,
402+}
403+
404+#[derive(Debug, Clone, Encode, Decode)]
405+pub struct Login {
406+ pub username: String,
407+ pub password: String,
408+}
409+
410+#[derive(Debug, Clone, Encode, Decode)]
411+pub struct Logout;
412+
413+#[derive(Debug, Clone, Encode, Decode)]
414+pub struct DeleteUser {
415+ pub user_id: String,
416+}
417+
418+#[derive(Debug, Clone, Encode, Decode)]
419+pub struct WatchCommunity {
420+ pub community_id: Option<String>,
421+}
422+
423+#[derive(Debug, Clone, Encode, Decode)]
424+pub struct ListUsers;
425+
426+#[derive(Debug, Clone, Encode, Decode)]
427+pub struct SetRole {
428+ pub user_id: String,
429+ pub role: Role,
430+}
431+
432+#[derive(Debug, Clone, Encode, Decode)]
433+pub struct ListAdminLogs {
434+ pub actor_id: Option<String>,
435+ pub target_id: Option<String>,
436+ pub action: Option<String>,
437+ pub after_ms: Option<u64>,
438+ pub before_ms: Option<u64>,
439+}
440+
441+#[derive(Debug, Clone, Encode, Decode)]
442+pub struct GetOverview;
443+
444+#[derive(Debug, Clone, Encode, Decode)]
445+pub struct SuspendUser {
446+ pub user_id: String,
447+ pub suspended: bool,
448+}
449+
450+#[derive(Debug, Clone, Encode, Decode)]
451+pub struct RevokeSessions {
452+ pub user_id: String,
453+}
454+
455+#[derive(Debug, Clone, Encode, Decode)]
456+pub struct ResetPassword {
457+ pub user_id: String,
458+ pub password: String,
459+}
460+
461+#[derive(Debug, Clone, Encode, Decode)]
462+pub struct ClearProfile {
463+ pub user_id: String,
464+}
465+
466+#[derive(Debug, Clone, Encode, Decode)]
467+pub struct ListAllCommunities;
468+
469+#[derive(Debug, Clone, Encode, Decode)]
470+pub struct TransferOwnership {
471+ pub community_id: String,
472+ pub user_id: String,
473+}
474+
475+#[derive(Debug, Clone, Encode, Decode)]
476+pub struct UpdateServerSettings {
477+ pub settings: ServerSettings,
478+}
479+
480+#[derive(Debug, Clone, Encode, Decode)]
481+pub struct CreateUser {
482+ pub username: String,
483+ pub password: String,
484+}
485+
486+#[derive(Debug, Clone, Encode, Decode)]
487+pub struct RenameUser {
488+ pub user_id: String,
489+ pub username: String,
490+}
491+
492+#[derive(Debug, Clone, Encode, Decode)]
493+pub struct TimeoutUser {
494+ pub user_id: String,
495+ pub minutes: u32,
496+}
497+
498+#[derive(Debug, Clone, Encode, Decode)]
499+pub struct BanUser {
500+ pub user_id: String,
501+ pub reason: Option<String>,
502+ pub scope: BanScope,
503+}
504+
505+#[derive(Debug, Clone, Encode, Decode)]
506+pub struct ListServerBans;
507+
508+#[derive(Debug, Clone, Encode, Decode)]
509+pub struct RemoveServerBan {
510+ pub id: String,
511+}
512+
513+#[derive(Debug, Clone, Encode, Decode)]
514+pub struct CreateInviteCode {
515+ pub uses: u32,
516+ pub hours: Option<u32>,
517+}
518+
519+#[derive(Debug, Clone, Encode, Decode)]
520+pub struct ListInviteCodes;
521+
522+#[derive(Debug, Clone, Encode, Decode)]
523+pub struct DeleteInviteCode {
524+ pub code: String,
525+}
526+
527+#[derive(Debug, Clone, Encode, Decode)]
528+pub struct SearchMessages {
529+ pub text: Option<String>,
530+ pub user_id: Option<String>,
531+ pub community_id: Option<String>,
532+ pub after_ms: Option<u64>,
533+ pub before_ms: Option<u64>,
534+}
535+
536+#[derive(Debug, Clone, Encode, Decode)]
537+pub struct SearchCommunity {
538+ pub community_id: String,
539+ pub text: String,
540+}
541+
542+#[derive(Debug, Clone, Encode, Decode)]
543+pub struct PurgeUser {
544+ pub user_id: String,
545+}
546+
547+#[derive(Debug, Clone, Encode, Decode)]
548+pub struct SetCommunityVoice {
549+ pub community_id: String,
550+ pub enabled: bool,
551+}
552+
553+#[derive(Debug, Clone, Encode, Decode)]
554+pub struct ListAttachments {
555+ pub user_id: Option<String>,
556+ pub community_id: Option<String>,
557+}
558+
559+#[derive(Debug, Clone, Encode, Decode)]
560+pub struct DeleteAttachment {
561+ pub attachment_id: String,
562+}
563+
564+#[derive(Debug, Clone, Encode, Decode)]
565+pub struct GetStorageUsage;
566+
567+#[derive(Debug, Clone, Encode, Decode)]
568+pub struct GetDailyStats {
569+ pub days: u32,
570+}
571+
572+#[derive(Debug, Clone, Encode, Decode)]
573+pub struct SetGhost {
574+ pub enabled: bool,
575+}
576+
577+#[derive(Debug, Clone, Encode, Decode)]
578+pub struct CreateBackup;
579+
580+#[derive(Debug, Clone, Encode, Decode)]
581+pub struct ListBackups;
582+
583+#[derive(Debug, Clone, Encode, Decode)]
584+pub struct DeleteBackup {
585+ pub name: String,
586+}
587+
588+#[derive(Debug, Clone, Encode, Decode)]
589+pub struct Session {
590+ pub user: User,
591+ pub token: String,
592+}
593+
594+#[derive(Debug, Clone, Encode, Decode)]
595+pub struct StorageUsage {
596+ pub users: Vec<Usage>,
597+ pub communities: Vec<CommunityUsage>,
598+}
599+
96 calls! {600 calls! {
97- Legacy: Guest -> Response;
98 GetSettings: Guest -> ServerSettings;601 GetSettings: Guest -> ServerSettings;
99 GetUser: User -> User;602 GetUser: User -> User;
100 UpdateUser: User -> User;603 UpdateUser: User -> User;
@@ -106,4 +609,97 @@ calls! {
106 GetAvatar: User -> Vec<u8>;609 GetAvatar: User -> Vec<u8>;
107 ListSessions: User -> Vec<SessionInfo>;610 ListSessions: User -> Vec<SessionInfo>;
108 RevokeSession: User -> ();611 RevokeSession: User -> ();
612+ CreateCommunity: User -> Community;
613+ GetCommunity: User -> Community;
614+ UpdateCommunity: User -> Community;
615+ UpdateCommunityAvatar: User -> Community;
616+ DeleteCommunity: User -> ();
617+ LeaveCommunity: User -> ();
618+ ListCommunities: User -> Vec<Community>;
619+ ListMembers: User -> Vec<Member>;
620+ Kick: User -> ();
621+ BanMember: User -> ();
622+ Unban: User -> ();
623+ ListBans: User -> Vec<Ban>;
624+ SetRank: User -> ();
625+ ListLogs: User -> Vec<LogEntry>;
626+ CreateMessage: User -> Message;
627+ ForwardMessages: User -> Vec<Message>;
628+ UpdateMessage: User -> Message;
629+ DeleteMessage: User -> ();
630+ CreatePoll: User -> Message;
631+ Vote: User -> ();
632+ ClosePoll: User -> ();
633+ React: User -> ();
634+ Pin: User -> ();
635+ ListPins: User -> Vec<Message>;
636+ ListMessages: User -> Vec<Message>;
637+ ListUnreads: User -> Vec<Unread>;
638+ MarkRead: User -> ();
639+ Typing: User -> ();
640+ FindUser: User -> User;
641+ OpenDirect: User -> Community;
642+ OpenNotes: User -> Community;
643+ ListFriends: User -> Friends;
644+ AddFriend: User -> ();
645+ AcceptFriend: User -> ();
646+ RemoveFriend: User -> ();
647+ Invite: User -> ();
648+ ListInvitations: User -> Vec<Invitation>;
649+ AcceptInvitation: User -> Community;
650+ DeclineInvitation: User -> ();
651+ ReportMessage: User -> ();
652+ ReportUser: User -> ();
653+ ListReports: Builder -> Vec<Report>;
654+ HandleReport: User -> ();
655+ JoinVoice: User -> Vec<String>;
656+ LeaveVoice: User -> ();
657+ StartShare: User -> ();
658+ StopShare: User -> ();
659+ ListShares: User -> Vec<Share>;
660+ WatchShare: User -> ();
661+ UnwatchShare: User -> ();
662+ RequestKeyframe: User -> ();
663+ DeclineCall: User -> ();
664+ ListVoiceParticipants: User -> Vec<String>;
665+ ListVoiceRooms: Builder -> Vec<VoiceRoom>;
666+ KickFromVoice: User -> ();
667+ ServerMute: User -> ();
668+ Register: Guest -> Session;
669+ Login: Guest -> Session;
670+ Logout: User -> ();
671+ DeleteUser: User -> ();
672+ WatchCommunity: User -> ();
673+ ListUsers: Builder -> Vec<Account>;
674+ SetRole: User -> User;
675+ ListAdminLogs: Builder -> Vec<AdminLogEntry>;
676+ GetOverview: Builder -> Overview;
677+ SuspendUser: User -> ();
678+ RevokeSessions: User -> ();
679+ ResetPassword: User -> ();
680+ ClearProfile: User -> User;
681+ ListAllCommunities: Builder -> Vec<CommunitySummary>;
682+ TransferOwnership: User -> ();
683+ UpdateServerSettings: Builder -> ServerSettings;
684+ CreateUser: Builder -> User;
685+ RenameUser: User -> User;
686+ TimeoutUser: User -> ();
687+ BanUser: User -> ();
688+ ListServerBans: Builder -> Vec<ServerBan>;
689+ RemoveServerBan: Builder -> ();
690+ CreateInviteCode: User -> InviteCode;
691+ ListInviteCodes: Builder -> Vec<InviteCode>;
692+ DeleteInviteCode: Builder -> ();
693+ SearchMessages: Builder -> Vec<MessageHit>;
694+ SearchCommunity: User -> Vec<MessageHit>;
695+ PurgeUser: User -> ();
696+ SetCommunityVoice: User -> Community;
697+ ListAttachments: Builder -> Vec<AttachmentInfo>;
698+ DeleteAttachment: Builder -> ();
699+ GetStorageUsage: Builder -> StorageUsage;
700+ GetDailyStats: Builder -> Vec<DayStat>;
701+ SetGhost: Builder -> ();
702+ CreateBackup: Builder -> BackupInfo;
703+ ListBackups: Builder -> Vec<BackupInfo>;
704+ DeleteBackup: Builder -> ();
109 }705 }
crates/common/src/lib.rsmodified+0 -2
@@ -8,8 +8,6 @@ pub mod frame;
8 pub mod model;8 pub mod model;
9 pub mod open;9 pub mod open;
10 pub mod permission;10 pub mod permission;
11-pub mod request;
12-pub mod response;
13 pub mod session;11 pub mod session;
14 pub mod share;12 pub mod share;
15 pub mod time;13 pub mod time;
crates/common/src/request.rsdeleted+0 -315
@@ -1,315 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-use crate::{
4- model::{BanScope, Rank, ReportStatus, Role, ServerSettings},
5- share::{Codec, Kind, Quality, Source},
6-};
7-
8-#[derive(Debug, Clone, Encode, Decode)]
9-pub enum LegacyRequest {
10- Register {
11- username: String,
12- password: String,
13- invite: Option<String>,
14- },
15- Login {
16- username: String,
17- password: String,
18- },
19- Logout,
20- DeleteUser {
21- user_id: String,
22- },
23- CreateCommunity {
24- name: String,
25- },
26- ReadCommunity {
27- community_id: String,
28- },
29- UpdateCommunity {
30- community_id: String,
31- name: String,
32- },
33- UpdateCommunityAvatar {
34- community_id: String,
35- image: Option<Vec<u8>>,
36- },
37- DeleteCommunity {
38- community_id: String,
39- },
40- LeaveCommunity {
41- community_id: String,
42- },
43- Communities,
44- Members {
45- community_id: String,
46- },
47- Kick {
48- community_id: String,
49- user_id: String,
50- reason: Option<String>,
51- },
52- Ban {
53- community_id: String,
54- user_id: String,
55- reason: Option<String>,
56- },
57- Unban {
58- community_id: String,
59- user_id: String,
60- },
61- Bans {
62- community_id: String,
63- },
64- SetRank {
65- community_id: String,
66- user_id: String,
67- rank: Rank,
68- },
69- CreateMessage {
70- community_id: String,
71- body: String,
72- attachments: Vec<String>,
73- reply_to: Option<String>,
74- },
75- ForwardMessages {
76- message_ids: Vec<String>,
77- community_id: String,
78- snippet: bool,
79- },
80- UpdateMessage {
81- message_id: String,
82- body: String,
83- },
84- DeleteMessage {
85- message_id: String,
86- },
87- CreatePoll {
88- community_id: String,
89- question: String,
90- options: Vec<String>,
91- multiple: bool,
92- },
93- Vote {
94- message_id: String,
95- positions: Vec<u32>,
96- },
97- ClosePoll {
98- message_id: String,
99- },
100- React {
101- message_id: String,
102- emoji: String,
103- },
104- Pin {
105- message_id: String,
106- pinned: bool,
107- },
108- Pins {
109- community_id: String,
110- },
111- WatchCommunity {
112- community_id: Option<String>,
113- },
114- ReadMessages {
115- community_id: String,
116- before: Option<String>,
117- },
118- Unreads,
119- MarkRead {
120- community_id: String,
121- message_id: String,
122- },
123- Typing {
124- community_id: String,
125- },
126- JoinVoice {
127- community_id: String,
128- },
129- LeaveVoice,
130- StartShare {
131- kind: Kind,
132- source: Source,
133- },
134- StopShare {
135- kind: Kind,
136- },
137- Shares {
138- community_id: String,
139- },
140- WatchShare {
141- user_id: String,
142- kind: Kind,
143- quality: Quality,
144- decode: Vec<Codec>,
145- },
146- UnwatchShare {
147- user_id: String,
148- kind: Kind,
149- },
150- RequestKeyframe {
151- user_id: String,
152- kind: Kind,
153- },
154- DeclineCall {
155- community_id: String,
156- },
157- VoiceParticipants {
158- community_id: String,
159- },
160- FindUser {
161- username: String,
162- },
163- OpenDirect {
164- user_id: String,
165- },
166- OpenNotes,
167- Friends,
168- AddFriend {
169- user_id: String,
170- },
171- AcceptFriend {
172- user_id: String,
173- },
174- RemoveFriend {
175- user_id: String,
176- },
177- Invite {
178- community_id: String,
179- user_id: String,
180- },
181- Invitations,
182- AcceptInvitation {
183- community_id: String,
184- },
185- DeclineInvitation {
186- community_id: String,
187- },
188- Logs {
189- community_id: String,
190- },
191- Users,
192- SetRole {
193- user_id: String,
194- role: Role,
195- },
196- AdminLogs {
197- actor_id: Option<String>,
198- target_id: Option<String>,
199- action: Option<String>,
200- after_ms: Option<u64>,
201- before_ms: Option<u64>,
202- },
203- Overview,
204- SuspendUser {
205- user_id: String,
206- suspended: bool,
207- },
208- RevokeSessions {
209- user_id: String,
210- },
211- ResetPassword {
212- user_id: String,
213- password: String,
214- },
215- ClearProfile {
216- user_id: String,
217- },
218- AllCommunities,
219- TransferOwnership {
220- community_id: String,
221- user_id: String,
222- },
223- UpdateServerSettings {
224- settings: ServerSettings,
225- },
226- CreateUser {
227- username: String,
228- password: String,
229- },
230- RenameUser {
231- user_id: String,
232- username: String,
233- },
234- TimeoutUser {
235- user_id: String,
236- minutes: u32,
237- },
238- BanUser {
239- user_id: String,
240- reason: Option<String>,
241- scope: BanScope,
242- },
243- ServerBans,
244- RemoveServerBan {
245- id: String,
246- },
247- CreateInviteCode {
248- uses: u32,
249- hours: Option<u32>,
250- },
251- InviteCodes,
252- DeleteInviteCode {
253- code: String,
254- },
255- ReportMessage {
256- message_id: String,
257- reason: String,
258- },
259- ReportUser {
260- user_id: String,
261- reason: String,
262- },
263- Reports {
264- status: Option<ReportStatus>,
265- },
266- HandleReport {
267- report_id: String,
268- status: ReportStatus,
269- },
270- SearchMessages {
271- text: Option<String>,
272- user_id: Option<String>,
273- community_id: Option<String>,
274- after_ms: Option<u64>,
275- before_ms: Option<u64>,
276- },
277- SearchCommunity {
278- community_id: String,
279- text: String,
280- },
281- PurgeUser {
282- user_id: String,
283- },
284- VoiceRooms,
285- KickFromVoice {
286- user_id: String,
287- },
288- ServerMute {
289- user_id: String,
290- muted: bool,
291- },
292- SetCommunityVoice {
293- community_id: String,
294- enabled: bool,
295- },
296- AllAttachments {
297- user_id: Option<String>,
298- community_id: Option<String>,
299- },
300- DeleteAttachment {
301- attachment_id: String,
302- },
303- StorageUsage,
304- DailyStats {
305- days: u32,
306- },
307- SetGhost {
308- enabled: bool,
309- },
310- CreateBackup,
311- Backups,
312- DeleteBackup {
313- name: String,
314- },
315-}
crates/common/src/response.rsdeleted+0 -56
@@ -1,56 +0,0 @@
1-use bitcode::{Decode, Encode};
2-
3-use crate::{
4- model::{
5- Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community,
6- CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
7- Member, Message, MessageHit, Overview, Presence, Report, ServerBan, ServerSettings,
8- SessionInfo, Unread, Usage, User, VoiceRoom,
9- },
10- share::Share,
11-};
12-
13-#[derive(Debug, Clone, Encode, Decode)]
14-pub enum Response {
15- Session {
16- user: User,
17- token: String,
18- },
19- User(User),
20- Avatar(Vec<u8>),
21- Community(Community),
22- Communities(Vec<Community>),
23- Members(Vec<Member>),
24- Bans(Vec<Ban>),
25- Message(Message),
26- Messages(Vec<Message>),
27- Unreads(Vec<Unread>),
28- Attachment(Attachment),
29- Voice(Vec<String>),
30- Shares(Vec<Share>),
31- Friends(Friends),
32- Invitations(Vec<Invitation>),
33- Done,
34- Logs(Vec<LogEntry>),
35- Users(Vec<Account>),
36- AdminLogs(Vec<AdminLogEntry>),
37- Overview(Overview),
38- AllCommunities(Vec<CommunitySummary>),
39- ServerSettings(ServerSettings),
40- Sessions(Vec<SessionInfo>),
41- ServerBans(Vec<ServerBan>),
42- InviteCode(InviteCode),
43- InviteCodes(Vec<InviteCode>),
44- Reports(Vec<Report>),
45- MessageHits(Vec<MessageHit>),
46- VoiceRooms(Vec<VoiceRoom>),
47- AttachmentInfos(Vec<AttachmentInfo>),
48- StorageUsage {
49- users: Vec<Usage>,
50- communities: Vec<CommunityUsage>,
51- },
52- DailyStats(Vec<DayStat>),
53- Backup(BackupInfo),
54- Backups(Vec<BackupInfo>),
55- Presences(Vec<(String, Presence)>),
56-}
crates/server/src/attachment.rsmodified+19 -18
@@ -671,19 +671,19 @@ mod tests {
671 use std::io::Cursor;671 use std::io::Cursor;
672 672
673 use common::{673 use common::{
674+ call::CreateMessage,
674 model::{AttachmentKind, Rank},675 model::{AttachmentKind, Rank},
675 open::Upload,676 open::Upload,
676- request::LegacyRequest,
677 };677 };
678 use image::{ImageFormat, RgbImage};678 use image::{ImageFormat, RgbImage};
679 679
680 use crate::{680 use crate::{
681 attachment::{store, thumb_path},681 attachment::{store, thumb_path},
682+ call::{Cx, Handle, Me},
682 community, database,683 community, database,
683 hub::{Client, Signed},684 hub::{Client, Signed},
684 message,685 message,
685- network::Services,686+ network::{Services, Shared},
686- request::handle,
687 test, user, user_community,687 test, user, user_community,
688 };688 };
689 689
@@ -716,21 +716,22 @@ mod tests {
716 user_id: user.id.clone(),716 user_id: user.id.clone(),
717 token: "token".to_string(),717 token: "token".to_string(),
718 }));718 }));
719- let (reply, _) = handle(719+ let shared = Shared {
720- LegacyRequest::CreateMessage {720+ db: db.clone(),
721- community_id: community.id.clone(),721+ services: Services::default(),
722- body: String::new(),722+ directory: test::directory(),
723- attachments: vec![attachment.id.clone()],723+ backups: test::directory(),
724- reply_to: None,724+ };
725- },725+ let mut cx = Cx::new(&client, &shared, database::connect(&db).await.unwrap());
726- &client,726+ CreateMessage {
727- &db,727+ community_id: community.id.clone(),
728- &Services::default(),728+ body: String::new(),
729- &test::directory(),729+ attachments: vec![attachment.id.clone()],
730- &test::directory(),730+ reply_to: None,
731- )731+ }
732- .await;732+ .handle(Me::User(user), &mut cx)
733- reply.unwrap();733+ .await
734+ .unwrap();
734 735
735 let messages = message::read_page(&community.id, None, &conn)736 let messages = message::read_page(&community.id, None, &conn)
736 .await737 .await
crates/server/src/call/admin.rsadded+814 -0
@@ -0,0 +1,814 @@
1+use std::collections::BTreeMap;
2+
3+use common::{
4+ call::{
5+ BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment,
6+ DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage,
7+ ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes,
8+ ListServerBans, ListUsers, Login, Logout, PurgeUser, Register, RemoveServerBan, RenameUser,
9+ ResetPassword, RevokeSessions, SearchCommunity, SearchMessages, Session, SetCommunityVoice,
10+ SetGhost, SetRole, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership,
11+ UpdateServerSettings, WatchCommunity,
12+ },
13+ error::Error,
14+ event::Event,
15+ model::{
16+ Account, AdminAction, AdminLogEntry, AttachmentInfo, BackupInfo, BanScope, Community,
17+ CommunitySummary, DayStat, InviteCode, LogAction, MessageHit, Overview, Rank, ServerBan,
18+ ServerBanKind, ServerSettings, User,
19+ },
20+ permission,
21+ time::{self, MINUTE_MILLIS},
22+ transport::Close,
23+ validate::{validate_reason, validate_server_settings},
24+};
25+
26+use crate::{
27+ admin_log, attachment, authentication, backup,
28+ call::{Cx, Handle, Me},
29+ community,
30+ error::ServerError,
31+ invite, log, message, overview,
32+ publish::{Broadcast, To},
33+ request::{
34+ allowed, call_ended, ensure, ensure_editable, is_outsider, leave_user_voice, limit_logins,
35+ managed, message_event, record_ghost_voice, shares_ended, user_updated, voice_closed,
36+ voice_joined, voice_silenced, voice_unmuted,
37+ },
38+ server_ban, server_settings, stats, user, user_community,
39+};
40+
41+impl Handle for Register {
42+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Session, ServerError> {
43+ limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?;
44+ let (user, token) = authentication::register(
45+ &self.username,
46+ &self.password,
47+ self.invite.as_deref(),
48+ &mut cx.db,
49+ )
50+ .await?;
51+
52+ Ok(Session { user, token })
53+ }
54+}
55+
56+impl Handle for Login {
57+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Session, ServerError> {
58+ limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?;
59+ let (user, token) = authentication::login(&self.username, &self.password, &cx.db).await?;
60+
61+ Ok(Session { user, token })
62+ }
63+}
64+
65+impl Handle for Logout {
66+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
67+ me.user()?;
68+ let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?;
69+ authentication::logout(&signed.token, &cx.db).await?;
70+
71+ Ok(())
72+ }
73+}
74+
75+impl Handle for UpdateServerSettings {
76+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> {
77+ let me = me.user()?;
78+ let settings = self.settings;
79+ validate_server_settings(&settings)?;
80+ server_settings::update(&settings, &cx.db).await?;
81+ admin_log::record(
82+ Some(&me.id),
83+ None,
84+ None,
85+ &AdminAction::SettingsChanged,
86+ &cx.db,
87+ )
88+ .await?;
89+ if settings.maintenance {
90+ let builders = user::builder_ids(&cx.db).await?;
91+ cx.sh
92+ .services
93+ .hub
94+ .kick_all_except(&builders, Close::Maintenance);
95+ }
96+ cx.emit(To::Everyone, Event::SettingsUpdated(settings.clone()));
97+
98+ Ok(settings)
99+ }
100+}
101+
102+impl Handle for RenameUser {
103+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
104+ let me = me.user()?;
105+ let target = managed(&me, &self.user_id, &cx.db).await?;
106+ let user = user::update(&self.user_id, &self.username, &cx.db).await?;
107+ admin_log::record(
108+ Some(&me.id),
109+ Some(&self.user_id),
110+ None,
111+ &AdminAction::UserRenamed {
112+ from: target.username,
113+ },
114+ &cx.db,
115+ )
116+ .await?;
117+ cx.out.extend(user_updated(&user));
118+
119+ Ok(user)
120+ }
121+}
122+
123+impl Handle for CreateUser {
124+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
125+ let me = me.user()?;
126+ let user = authentication::create_account(&self.username, &self.password, &cx.db).await?;
127+ admin_log::record(
128+ Some(&me.id),
129+ Some(&user.id),
130+ None,
131+ &AdminAction::UserCreated,
132+ &cx.db,
133+ )
134+ .await?;
135+
136+ Ok(user)
137+ }
138+}
139+
140+impl Handle for ListUsers {
141+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<Account>, ServerError> {
142+ user::all(&cx.db).await
143+ }
144+}
145+
146+impl Handle for ListAdminLogs {
147+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<AdminLogEntry>, ServerError> {
148+ admin_log::list(
149+ self.actor_id.as_deref(),
150+ self.target_id.as_deref(),
151+ self.action.as_deref(),
152+ self.after_ms,
153+ self.before_ms,
154+ &cx.db,
155+ )
156+ .await
157+ }
158+}
159+
160+impl Handle for GetDailyStats {
161+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<DayStat>, ServerError> {
162+ stats::daily(self.days, &cx.db).await
163+ }
164+}
165+
166+impl Handle for GetOverview {
167+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Overview, ServerError> {
168+ overview::read(&cx.sh.services.hub, &cx.sh.services.rooms, &cx.db).await
169+ }
170+}
171+
172+impl Handle for SuspendUser {
173+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
174+ let me = me.user()?;
175+ managed(&me, &self.user_id, &cx.db).await?;
176+ user::set_suspended(&self.user_id, self.suspended, &cx.db).await?;
177+ let action = if self.suspended {
178+ AdminAction::UserSuspended
179+ } else {
180+ AdminAction::UserUnsuspended
181+ };
182+ admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?;
183+ if self.suspended {
184+ authentication::revoke(
185+ &cx.sh.services.hub,
186+ authentication::Revoke::User(&self.user_id),
187+ &cx.db,
188+ )
189+ .await?;
190+ }
191+
192+ Ok(())
193+ }
194+}
195+
196+impl Handle for RevokeSessions {
197+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
198+ let me = me.user()?;
199+ managed(&me, &self.user_id, &cx.db).await?;
200+ authentication::revoke(
201+ &cx.sh.services.hub,
202+ authentication::Revoke::User(&self.user_id),
203+ &cx.db,
204+ )
205+ .await?;
206+ admin_log::record(
207+ Some(&me.id),
208+ Some(&self.user_id),
209+ None,
210+ &AdminAction::SessionsRevoked,
211+ &cx.db,
212+ )
213+ .await?;
214+
215+ Ok(())
216+ }
217+}
218+
219+impl Handle for ResetPassword {
220+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
221+ let me = me.user()?;
222+ managed(&me, &self.user_id, &cx.db).await?;
223+ authentication::reset_password(&self.user_id, &self.password, &cx.db).await?;
224+ authentication::revoke(
225+ &cx.sh.services.hub,
226+ authentication::Revoke::User(&self.user_id),
227+ &cx.db,
228+ )
229+ .await?;
230+ admin_log::record(
231+ Some(&me.id),
232+ Some(&self.user_id),
233+ None,
234+ &AdminAction::PasswordReset,
235+ &cx.db,
236+ )
237+ .await?;
238+
239+ Ok(())
240+ }
241+}
242+
243+impl Handle for ClearProfile {
244+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
245+ let me = me.user()?;
246+ managed(&me, &self.user_id, &cx.db).await?;
247+ user::set_avatar(&self.user_id, None, &mut cx.db).await?;
248+ let user = user::update_status(&self.user_id, "", &cx.db).await?;
249+ admin_log::record(
250+ Some(&me.id),
251+ Some(&self.user_id),
252+ None,
253+ &AdminAction::ProfileCleared,
254+ &cx.db,
255+ )
256+ .await?;
257+ cx.out.extend(user_updated(&user));
258+
259+ Ok(user)
260+ }
261+}
262+
263+impl Handle for SetRole {
264+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
265+ let me = me.user()?;
266+ let Self { user_id, role } = self;
267+ ensure(permission::can_set_role(me.role, me.id == user_id))?;
268+ let user = user::set_role_by_id(&user_id, role, &cx.db).await?;
269+ admin_log::record(
270+ Some(&me.id),
271+ Some(&user_id),
272+ None,
273+ &AdminAction::RoleChanged { role },
274+ &cx.db,
275+ )
276+ .await?;
277+ cx.out.extend(user_updated(&user));
278+ if permission::is_builder(role) {
279+ let broadcasts = voice_unmuted(&cx.sh.services.rooms, &user_id, &cx.db).await?;
280+ cx.out.extend(broadcasts);
281+ } else {
282+ user::set_ghost(&user_id, false, &cx.db).await?;
283+ cx.sh.services.hub.kick_user(&user_id, Close::Revoked);
284+ }
285+
286+ Ok(user)
287+ }
288+}
289+
290+impl Handle for DeleteUser {
291+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
292+ let me = me.user()?;
293+ let user_id = self.user_id;
294+ let rooms = &cx.sh.services.rooms;
295+ let target = user::read(&user_id, &cx.db).await?;
296+ ensure(permission::can_delete_user(
297+ me.role,
298+ me.id == user_id,
299+ target.role,
300+ ))?;
301+ let tx = cx.db.transaction().await?;
302+ let mut broadcasts = Vec::new();
303+ if permission::is_builder(me.role) && me.id != user_id {
304+ admin_log::record(
305+ Some(&me.id),
306+ Some(&user_id),
307+ None,
308+ &AdminAction::UserDeleted,
309+ &tx,
310+ )
311+ .await?;
312+ }
313+ for community_id in user_community::owned(&user_id, &tx).await? {
314+ let member_ids = user_community::member_ids(&community_id, &tx).await?;
315+ broadcasts.extend(voice_closed(rooms, &community_id, &tx).await?);
316+ community::delete(&community_id, &user_id, &tx).await?;
317+ let event = Event::CommunityDeleted { community_id };
318+ broadcasts.push(Broadcast::new(To::Users(member_ids), event));
319+ }
320+ for community in community::communities_of(&user_id, &tx).await? {
321+ let member_ids = user_community::member_ids(&community.id, &tx).await?;
322+ if community.kind.is_direct() {
323+ community::delete(&community.id, &user_id, &tx).await?;
324+ }
325+ let event = Event::UserDeleted {
326+ user_id: user_id.clone(),
327+ };
328+ broadcasts.push(Broadcast::new(To::Users(member_ids), event));
329+ }
330+ broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?);
331+ user::delete(&user_id, &tx).await?;
332+ tx.commit().await?;
333+ if me.id != user_id {
334+ cx.sh.services.hub.kick_user(&user_id, Close::Revoked);
335+ }
336+ cx.out.extend(broadcasts);
337+
338+ Ok(())
339+ }
340+}
341+
342+impl Handle for WatchCommunity {
343+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
344+ let me = me.user()?;
345+ let Some(community_id) = self.community_id else {
346+ cx.client.watch(None);
347+ return Ok(());
348+ };
349+ allowed(&me, &community_id, &cx.db, permission::can_read).await?;
350+ let outsider = is_outsider(&me.id, &community_id, &cx.db).await?;
351+ cx.client.watch(outsider.then_some(community_id.as_str()));
352+ let visit =
353+ permission::is_builder(me.role) && outsider && user::is_ghost(&me.id, &cx.db).await?;
354+ if visit && cx.client.first_visit(&community_id) {
355+ let community = community::label(&community_id, &cx.db).await?;
356+ admin_log::record(
357+ Some(&me.id),
358+ None,
359+ Some(&community),
360+ &AdminAction::GhostVisit,
361+ &cx.db,
362+ )
363+ .await?;
364+ }
365+
366+ Ok(())
367+ }
368+}
369+
370+impl Handle for ListAllCommunities {
371+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<CommunitySummary>, ServerError> {
372+ let mut summaries = Vec::new();
373+ for community in community::groups(&cx.db).await? {
374+ let members = user_community::members(&community.id, &cx.db).await?;
375+ let owner = members
376+ .iter()
377+ .find(|member| member.rank == Rank::Owner)
378+ .map(|member| member.user.clone());
379+ summaries.push(CommunitySummary {
380+ community,
381+ owner,
382+ members: members.len() as u64,
383+ });
384+ }
385+
386+ Ok(summaries)
387+ }
388+}
389+
390+impl Handle for TransferOwnership {
391+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
392+ let me = me.user()?;
393+ let Self {
394+ community_id,
395+ user_id,
396+ } = self;
397+ ensure_editable(&community_id, &cx.db).await?;
398+ allowed(
399+ &me,
400+ &community_id,
401+ &cx.db,
402+ permission::can_transfer_ownership,
403+ )
404+ .await?;
405+ let tx = cx.db.transaction().await?;
406+ let members = user_community::members(&community_id, &tx).await?;
407+ let target = members
408+ .iter()
409+ .find(|member| member.user.id == user_id)
410+ .ok_or(Error::NotFound)?;
411+ ensure(target.rank != Rank::Owner)?;
412+ let mut changes = vec![(user_id.clone(), Rank::Owner)];
413+ if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) {
414+ user_community::set_rank(&previous.user.id, &community_id, Rank::Admin, &tx).await?;
415+ log::record(
416+ &community_id,
417+ Some(&me.id),
418+ Some(&previous.user.id),
419+ &LogAction::RankChanged { rank: Rank::Admin },
420+ &tx,
421+ )
422+ .await?;
423+ changes.push((previous.user.id.clone(), Rank::Admin));
424+ }
425+ user_community::set_rank(&user_id, &community_id, Rank::Owner, &tx).await?;
426+ log::record(
427+ &community_id,
428+ Some(&me.id),
429+ Some(&user_id),
430+ &LogAction::RankChanged { rank: Rank::Owner },
431+ &tx,
432+ )
433+ .await?;
434+ if permission::is_builder(me.role) {
435+ let community = community::read(&community_id, &me.id, &tx).await?;
436+ admin_log::record(
437+ Some(&me.id),
438+ Some(&user_id),
439+ Some(&community.name),
440+ &AdminAction::OwnershipTransferred,
441+ &tx,
442+ )
443+ .await?;
444+ }
445+ tx.commit().await?;
446+ for (changed_id, rank) in changes {
447+ cx.emit(
448+ To::Community(community_id.clone()),
449+ Event::RankChanged {
450+ community_id: community_id.clone(),
451+ user_id: changed_id,
452+ rank,
453+ },
454+ );
455+ }
456+
457+ Ok(())
458+ }
459+}
460+
461+impl Handle for TimeoutUser {
462+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
463+ let me = me.user()?;
464+ let Self { user_id, minutes } = self;
465+ managed(&me, &user_id, &cx.db).await?;
466+ let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);
467+ user::set_timeout(&user_id, until, &cx.db).await?;
468+ if until.is_some() {
469+ authentication::revoke(
470+ &cx.sh.services.hub,
471+ authentication::Revoke::User(&user_id),
472+ &cx.db,
473+ )
474+ .await?;
475+ }
476+ admin_log::record(
477+ Some(&me.id),
478+ Some(&user_id),
479+ None,
480+ &AdminAction::UserTimedOut { minutes },
481+ &cx.db,
482+ )
483+ .await?;
484+
485+ Ok(())
486+ }
487+}
488+
489+impl Handle for BanUser {
490+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
491+ let me = me.user()?;
492+ let Self {
493+ user_id,
494+ reason,
495+ scope,
496+ } = self;
497+ let target = managed(&me, &user_id, &cx.db).await?;
498+ validate_reason(reason.as_deref())?;
499+ let tx = cx.db.transaction().await?;
500+ user::set_suspended(&user_id, true, &tx).await?;
501+ authentication::revoke_sessions(&user_id, &tx).await?;
502+ server_ban::insert(
503+ ServerBanKind::Username,
504+ &target.username.to_ascii_lowercase(),
505+ reason.as_deref(),
506+ &me.id,
507+ &tx,
508+ )
509+ .await?;
510+ if scope == BanScope::AccountAndIp
511+ && let Some(address) = user::last_ip(&user_id, &tx).await?
512+ {
513+ server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx).await?;
514+ }
515+ admin_log::record(
516+ Some(&me.id),
517+ Some(&user_id),
518+ None,
519+ &AdminAction::UserBanned { reason },
520+ &tx,
521+ )
522+ .await?;
523+ tx.commit().await?;
524+ cx.sh.services.hub.kick_user(&user_id, Close::Banned);
525+
526+ Ok(())
527+ }
528+}
529+
530+impl Handle for ListServerBans {
531+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<ServerBan>, ServerError> {
532+ server_ban::list(&cx.db).await
533+ }
534+}
535+
536+impl Handle for RemoveServerBan {
537+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
538+ let me = me.user()?;
539+ server_ban::remove(&self.id, &cx.db).await?;
540+ admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &cx.db).await?;
541+
542+ Ok(())
543+ }
544+}
545+
546+impl Handle for CreateInviteCode {
547+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<InviteCode, ServerError> {
548+ let me = me.user()?;
549+ ensure(permission::is_builder(me.role) && self.uses > 0)?;
550+ let code = invite::create(self.uses, self.hours, &me, &cx.db).await?;
551+ admin_log::record(
552+ Some(&me.id),
553+ None,
554+ None,
555+ &AdminAction::InviteCreated,
556+ &cx.db,
557+ )
558+ .await?;
559+
560+ Ok(code)
561+ }
562+}
563+
564+impl Handle for ListInviteCodes {
565+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<InviteCode>, ServerError> {
566+ invite::list(&cx.db).await
567+ }
568+}
569+
570+impl Handle for DeleteInviteCode {
571+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
572+ let me = me.user()?;
573+ invite::delete(&self.code, &cx.db).await?;
574+ admin_log::record(
575+ Some(&me.id),
576+ None,
577+ None,
578+ &AdminAction::InviteDeleted,
579+ &cx.db,
580+ )
581+ .await?;
582+
583+ Ok(())
584+ }
585+}
586+
587+impl Handle for SearchMessages {
588+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<MessageHit>, ServerError> {
589+ message::search(
590+ self.text.as_deref(),
591+ self.user_id.as_deref(),
592+ self.community_id.as_deref(),
593+ self.after_ms,
594+ self.before_ms,
595+ &cx.db,
596+ )
597+ .await
598+ }
599+}
600+
601+impl Handle for SearchCommunity {
602+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<MessageHit>, ServerError> {
603+ let me = me.user()?;
604+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
605+
606+ message::search(
607+ Some(&self.text),
608+ None,
609+ Some(&self.community_id),
610+ None,
611+ None,
612+ &cx.db,
613+ )
614+ .await
615+ }
616+}
617+
618+impl Handle for PurgeUser {
619+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
620+ let me = me.user()?;
621+ let user_id = self.user_id;
622+ managed(&me, &user_id, &cx.db).await?;
623+ let tx = cx.db.transaction().await?;
624+ let upload_ids = attachment::uploads_of(&user_id, &tx).await?;
625+ let message_ids = message::ids_of_user(&user_id, &tx).await?;
626+ let mut deleted: BTreeMap<String, Vec<String>> = BTreeMap::new();
627+ for message_id in &message_ids {
628+ let message = message::delete(message_id, &tx).await?;
629+ deleted
630+ .entry(message.community_id)
631+ .or_default()
632+ .push(message.id);
633+ }
634+ attachment::delete_uploads(&user_id, &tx).await?;
635+ admin_log::record(
636+ Some(&me.id),
637+ Some(&user_id),
638+ None,
639+ &AdminAction::UserPurged {
640+ messages: message_ids.len() as u64,
641+ },
642+ &tx,
643+ )
644+ .await?;
645+ tx.commit().await?;
646+ attachment::remove_files(&upload_ids, &cx.sh.directory);
647+ for (community_id, ids) in deleted {
648+ cx.emit(
649+ To::Community(community_id.clone()),
650+ Event::MessagesDeleted { community_id, ids },
651+ );
652+ }
653+
654+ Ok(())
655+ }
656+}
657+
658+impl Handle for ListAttachments {
659+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<AttachmentInfo>, ServerError> {
660+ attachment::all(
661+ self.user_id.as_deref(),
662+ self.community_id.as_deref(),
663+ &cx.db,
664+ )
665+ .await
666+ }
667+}
668+
669+impl Handle for DeleteAttachment {
670+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
671+ let me = me.user()?;
672+ let attachment_id = self.attachment_id;
673+ let stored = attachment::read(&attachment_id, &cx.db).await?;
674+ let community = community::label(&stored.community_id, &cx.db).await?;
675+ let tx = cx.db.transaction().await?;
676+ attachment::delete(&attachment_id, &tx).await?;
677+ admin_log::record(
678+ Some(&me.id),
679+ Some(&stored.uploader_id),
680+ Some(&community),
681+ &AdminAction::AttachmentDeleted,
682+ &tx,
683+ )
684+ .await?;
685+ let mut broadcast = None;
686+ if let Some(message_id) = &stored.message_id {
687+ let updated = message::read(message_id, &tx).await?;
688+ broadcast = Some(message_event(&updated, Event::MessageUpdated));
689+ }
690+ tx.commit().await?;
691+ attachment::remove_files(&[attachment_id], &cx.sh.directory);
692+ cx.out.extend(broadcast);
693+
694+ Ok(())
695+ }
696+}
697+
698+impl Handle for GetStorageUsage {
699+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<StorageUsage, ServerError> {
700+ let (users, communities) = attachment::usage(&cx.db).await?;
701+
702+ Ok(StorageUsage { users, communities })
703+ }
704+}
705+
706+impl Handle for CreateBackup {
707+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<BackupInfo, ServerError> {
708+ let me = me.user()?;
709+ let backup = backup::create(&cx.db, &cx.sh.backups).await?;
710+ let action = AdminAction::BackupCreated {
711+ name: backup.name.clone(),
712+ };
713+ admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?;
714+
715+ Ok(backup)
716+ }
717+}
718+
719+impl Handle for ListBackups {
720+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<BackupInfo>, ServerError> {
721+ backup::list(&cx.sh.backups)
722+ }
723+}
724+
725+impl Handle for DeleteBackup {
726+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
727+ let me = me.user()?;
728+ backup::delete(&self.name, &cx.sh.backups)?;
729+ let action = AdminAction::BackupDeleted { name: self.name };
730+ admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?;
731+
732+ Ok(())
733+ }
734+}
735+
736+impl Handle for SetCommunityVoice {
737+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
738+ let me = me.user()?;
739+ let Self {
740+ community_id,
741+ enabled,
742+ } = self;
743+ allowed(&me, &community_id, &cx.db, permission::can_manage_voice).await?;
744+ let tx = cx.db.transaction().await?;
745+ community::set_voice_enabled(&community_id, enabled, &tx).await?;
746+ let updated = community::read(&community_id, &me.id, &tx).await?;
747+ if permission::is_builder(me.role) {
748+ admin_log::record(
749+ Some(&me.id),
750+ None,
751+ Some(&updated.name),
752+ &AdminAction::CommunityVoiceSet { enabled },
753+ &tx,
754+ )
755+ .await?;
756+ }
757+ tx.commit().await?;
758+ if !enabled {
759+ let broadcasts = voice_silenced(&cx.sh.services.rooms, &community_id, &cx.db).await?;
760+ cx.out.extend(broadcasts);
761+ }
762+ cx.emit(
763+ To::Community(community_id),
764+ Event::CommunityUpdated(updated.clone()),
765+ );
766+
767+ Ok(updated)
768+ }
769+}
770+
771+impl Handle for SetGhost {
772+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
773+ let me = me.user()?;
774+ let enabled = self.enabled;
775+ let rooms = &cx.sh.services.rooms;
776+ user::set_ghost(&me.id, enabled, &cx.db).await?;
777+ let action = if enabled {
778+ AdminAction::GhostEnabled
779+ } else {
780+ AdminAction::GhostDisabled
781+ };
782+ admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?;
783+ let mut broadcasts = Vec::new();
784+ let outsider = match rooms.room_of(&me.id) {
785+ Some(community_id) => is_outsider(&me.id, &community_id, &cx.db).await?,
786+ None => false,
787+ };
788+ if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) {
789+ let community_id = departure.community_id.clone();
790+ if enabled {
791+ broadcasts.extend(shares_ended(&mut departure));
792+ broadcasts
793+ .extend(call_ended(&community_id, &me.id, departure.call_log, &cx.db).await?);
794+ let event = Event::VoiceLeft {
795+ community_id: community_id.clone(),
796+ user_id: me.id.clone(),
797+ };
798+ broadcasts.push(Broadcast::new(
799+ To::CommunityExcept(community_id, me.id.clone()),
800+ event,
801+ ));
802+ } else {
803+ let muted = user::voice_muted(&me.id, &cx.db).await?;
804+ broadcasts.extend(voice_joined(&community_id, &me.id, muted));
805+ if let Some(seconds) = departure.ghost_seconds {
806+ record_ghost_voice(&me.id, &community_id, seconds, &cx.db).await?;
807+ }
808+ }
809+ }
810+ cx.out.extend(broadcasts);
811+
812+ Ok(())
813+ }
814+}
crates/server/src/call/community.rsadded+363 -0
@@ -0,0 +1,363 @@
1+use common::{
2+ call::{
3+ BanMember, CreateCommunity, DeleteCommunity, GetCommunity, Kick, LeaveCommunity, ListBans,
4+ ListCommunities, ListLogs, ListMembers, SetRank, Unban, UpdateCommunity,
5+ UpdateCommunityAvatar,
6+ },
7+ error::Error,
8+ event::Event,
9+ model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User},
10+ permission,
11+ validate::{validate_avatar_size, validate_reason},
12+};
13+
14+use crate::{
15+ admin_log,
16+ call::{Cx, Handle, Me},
17+ community,
18+ error::ServerError,
19+ log,
20+ publish::To,
21+ request::{
22+ actor_rank, allowed, ensure, ensure_editable, ensure_with, leave_room_voice, voice_closed,
23+ },
24+ server_settings, user, user_community,
25+};
26+
27+struct Removal {
28+ community_id: String,
29+ user_id: String,
30+ reason: Option<String>,
31+ sanction: Sanction,
32+}
33+
34+async fn remove_member(me: &User, removal: Removal, cx: &mut Cx<'_>) -> Result<(), ServerError> {
35+ let Removal {
36+ community_id,
37+ user_id,
38+ reason,
39+ sanction,
40+ } = removal;
41+ validate_reason(reason.as_deref())?;
42+ ensure_editable(&community_id, &cx.db).await?;
43+ let target = user::read(&user_id, &cx.db).await?;
44+ ensure(permission::can_moderate(
45+ actor_rank(me, &community_id, &cx.db).await?,
46+ actor_rank(&target, &community_id, &cx.db).await?,
47+ ))?;
48+ let community = community::read(&community_id, &me.id, &cx.db).await?;
49+ let tx = cx.db.transaction().await?;
50+ user_community::leave(&user_id, &community_id, &tx).await?;
51+ let action = match sanction {
52+ Sanction::Ban => {
53+ user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?;
54+ LogAction::Banned {
55+ reason: reason.clone(),
56+ }
57+ }
58+ Sanction::Kick => LogAction::Kicked {
59+ reason: reason.clone(),
60+ },
61+ };
62+ log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;
63+ tx.commit().await?;
64+ let broadcasts =
65+ leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?;
66+ cx.out.extend(broadcasts);
67+ cx.emit(
68+ To::User(user_id.clone()),
69+ Event::Removed {
70+ community_id: community_id.clone(),
71+ community_name: community.name,
72+ sanction,
73+ reason,
74+ },
75+ );
76+ cx.emit(
77+ To::Community(community_id.clone()),
78+ Event::MemberLeft {
79+ community_id,
80+ user_id,
81+ },
82+ );
83+
84+ Ok(())
85+}
86+
87+impl Handle for CreateCommunity {
88+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
89+ let me = me.user()?;
90+ let limit = server_settings::read(&cx.db)
91+ .await?
92+ .max_communities_per_user;
93+ let owned = user_community::owned_groups(&me.id, &cx.db).await?;
94+ ensure_with(limit == 0 || owned < limit as usize, Error::LimitReached)?;
95+ let tx = cx.db.transaction().await?;
96+ let community = community::create(&self.name, &tx).await?;
97+ user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?;
98+ log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?;
99+ tx.commit().await?;
100+
101+ Ok(community)
102+ }
103+}
104+
105+impl Handle for GetCommunity {
106+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
107+ let me = me.user()?;
108+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
109+
110+ community::read(&self.community_id, &me.id, &cx.db).await
111+ }
112+}
113+
114+impl Handle for UpdateCommunity {
115+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
116+ let me = me.user()?;
117+ ensure_editable(&self.community_id, &cx.db).await?;
118+ allowed(
119+ &me,
120+ &self.community_id,
121+ &cx.db,
122+ permission::can_rename_community,
123+ )
124+ .await?;
125+ let updated = community::update(&self.community_id, &self.name, &me.id, &cx.db).await?;
126+ let action = LogAction::Renamed {
127+ name: updated.name.clone(),
128+ };
129+ log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?;
130+ cx.emit(
131+ To::Community(self.community_id),
132+ Event::CommunityUpdated(updated.clone()),
133+ );
134+
135+ Ok(updated)
136+ }
137+}
138+
139+impl Handle for UpdateCommunityAvatar {
140+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
141+ let me = me.user()?;
142+ ensure_editable(&self.community_id, &cx.db).await?;
143+ allowed(
144+ &me,
145+ &self.community_id,
146+ &cx.db,
147+ permission::can_rename_community,
148+ )
149+ .await?;
150+ if let Some(bytes) = &self.image {
151+ validate_avatar_size(bytes, server_settings::read(&cx.db).await?.max_avatar_bytes)?;
152+ }
153+ let updated = community::set_avatar(
154+ &self.community_id,
155+ self.image.as_deref(),
156+ &me.id,
157+ &mut cx.db,
158+ )
159+ .await?;
160+ let action = if self.image.is_some() {
161+ LogAction::AvatarChanged
162+ } else {
163+ LogAction::AvatarRemoved
164+ };
165+ log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?;
166+ cx.emit(
167+ To::Community(self.community_id),
168+ Event::CommunityUpdated(updated.clone()),
169+ );
170+
171+ Ok(updated)
172+ }
173+}
174+
175+impl Handle for DeleteCommunity {
176+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
177+ let me = me.user()?;
178+ ensure_editable(&self.community_id, &cx.db).await?;
179+ allowed(
180+ &me,
181+ &self.community_id,
182+ &cx.db,
183+ permission::can_delete_community,
184+ )
185+ .await?;
186+ let tx = cx.db.transaction().await?;
187+ let member_ids = user_community::member_ids(&self.community_id, &tx).await?;
188+ let owned =
189+ user_community::rank(&me.id, &self.community_id, &tx).await? == Some(Rank::Owner);
190+ let deleted = community::delete(&self.community_id, &me.id, &tx).await?;
191+ if permission::is_builder(me.role) && !owned {
192+ admin_log::record(
193+ Some(&me.id),
194+ None,
195+ Some(&deleted.name),
196+ &AdminAction::CommunityDeleted,
197+ &tx,
198+ )
199+ .await?;
200+ }
201+ tx.commit().await?;
202+ let broadcasts = voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?;
203+ cx.out.extend(broadcasts);
204+ cx.emit(
205+ To::Users(member_ids),
206+ Event::CommunityDeleted {
207+ community_id: deleted.id.clone(),
208+ },
209+ );
210+
211+ Ok(())
212+ }
213+}
214+
215+impl Handle for LeaveCommunity {
216+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
217+ let me = me.user()?;
218+ ensure_editable(&self.community_id, &cx.db).await?;
219+ allowed(&me, &self.community_id, &cx.db, permission::can_leave).await?;
220+ let tx = cx.db.transaction().await?;
221+ user_community::leave(&me.id, &self.community_id, &tx).await?;
222+ log::record(
223+ &self.community_id,
224+ Some(&me.id),
225+ None,
226+ &LogAction::Left,
227+ &tx,
228+ )
229+ .await?;
230+ if user_community::member_ids(&self.community_id, &tx)
231+ .await?
232+ .is_empty()
233+ {
234+ community::delete(&self.community_id, &me.id, &tx).await?;
235+ }
236+ tx.commit().await?;
237+ let broadcasts =
238+ leave_room_voice(&cx.sh.services.rooms, &self.community_id, &me.id, &cx.db).await?;
239+ cx.out.extend(broadcasts);
240+ cx.emit(
241+ To::Community(self.community_id.clone()),
242+ Event::MemberLeft {
243+ community_id: self.community_id,
244+ user_id: me.id,
245+ },
246+ );
247+
248+ Ok(())
249+ }
250+}
251+
252+impl Handle for ListCommunities {
253+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Community>, ServerError> {
254+ let me = me.user()?;
255+
256+ community::communities_of(&me.id, &cx.db).await
257+ }
258+}
259+
260+impl Handle for ListMembers {
261+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Member>, ServerError> {
262+ let me = me.user()?;
263+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
264+
265+ user_community::members(&self.community_id, &cx.db).await
266+ }
267+}
268+
269+impl Handle for Kick {
270+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
271+ let me = me.user()?;
272+ let removal = Removal {
273+ community_id: self.community_id,
274+ user_id: self.user_id,
275+ reason: self.reason,
276+ sanction: Sanction::Kick,
277+ };
278+
279+ remove_member(&me, removal, cx).await
280+ }
281+}
282+
283+impl Handle for BanMember {
284+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
285+ let me = me.user()?;
286+ let removal = Removal {
287+ community_id: self.community_id,
288+ user_id: self.user_id,
289+ reason: self.reason,
290+ sanction: Sanction::Ban,
291+ };
292+
293+ remove_member(&me, removal, cx).await
294+ }
295+}
296+
297+impl Handle for Unban {
298+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
299+ let me = me.user()?;
300+ allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?;
301+ user_community::unban(&self.user_id, &self.community_id, &cx.db).await?;
302+ log::record(
303+ &self.community_id,
304+ Some(&me.id),
305+ Some(&self.user_id),
306+ &LogAction::Unbanned,
307+ &cx.db,
308+ )
309+ .await?;
310+
311+ Ok(())
312+ }
313+}
314+
315+impl Handle for ListBans {
316+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Ban>, ServerError> {
317+ let me = me.user()?;
318+ allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?;
319+
320+ user_community::bans(&self.community_id, &cx.db).await
321+ }
322+}
323+
324+impl Handle for SetRank {
325+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
326+ let me = me.user()?;
327+ ensure_editable(&self.community_id, &cx.db).await?;
328+ let target = user::read(&self.user_id, &cx.db).await?;
329+ ensure(permission::can_set_rank(
330+ actor_rank(&me, &self.community_id, &cx.db).await?,
331+ actor_rank(&target, &self.community_id, &cx.db).await?,
332+ self.rank,
333+ ))?;
334+ user_community::set_rank(&self.user_id, &self.community_id, self.rank, &cx.db).await?;
335+ log::record(
336+ &self.community_id,
337+ Some(&me.id),
338+ Some(&self.user_id),
339+ &LogAction::RankChanged { rank: self.rank },
340+ &cx.db,
341+ )
342+ .await?;
343+ cx.emit(
344+ To::Community(self.community_id.clone()),
345+ Event::RankChanged {
346+ community_id: self.community_id,
347+ user_id: self.user_id,
348+ rank: self.rank,
349+ },
350+ );
351+
352+ Ok(())
353+ }
354+}
355+
356+impl Handle for ListLogs {
357+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<LogEntry>, ServerError> {
358+ let me = me.user()?;
359+ allowed(&me, &self.community_id, &cx.db, permission::can_read_logs).await?;
360+
361+ log::list(&self.community_id, &cx.db).await
362+ }
363+}
crates/server/src/call/message.rsadded+322 -0
@@ -0,0 +1,322 @@
1+use common::{
2+ call::{
3+ ClosePoll, CreateMessage, CreatePoll, DeleteMessage, ForwardMessages, ListMessages,
4+ ListPins, ListUnreads, MarkRead, Pin, React, Typing, UpdateMessage, Vote,
5+ },
6+ error::Error,
7+ event::Event,
8+ model::{AdminAction, LogAction, Message, ServerSettings, Unread, User},
9+ permission,
10+ validate::{
11+ validate_forward, validate_new_message, validate_poll, validate_reaction, validate_vote,
12+ },
13+};
14+
15+use crate::{
16+ admin_log,
17+ call::{Cx, Handle, Me},
18+ community,
19+ error::ServerError,
20+ log, message,
21+ publish::To,
22+ request::{actor_rank, allowed, ensure, is_outsider},
23+ server_settings, stats, user, user_community,
24+};
25+
26+fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(), ServerError> {
27+ if permission::is_builder(me.role) {
28+ return Ok(());
29+ }
30+
31+ Ok(cx
32+ .sh
33+ .services
34+ .rate_limit
35+ .allow(&me.id, settings.messages_per_minute)?)
36+}
37+
38+fn emit_message(message: &Message, event: fn(Message) -> Event, cx: &mut Cx<'_>) {
39+ cx.emit(
40+ To::Community(message.community_id.clone()),
41+ event(message.clone()),
42+ );
43+}
44+
45+impl Handle for CreateMessage {
46+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {
47+ let me = me.user()?;
48+ let settings = server_settings::read(&cx.db).await?;
49+ limit_messages(&me, &settings, cx)?;
50+ validate_new_message(
51+ &self.body,
52+ self.attachments.len(),
53+ settings.max_message_length as usize,
54+ )?;
55+ allowed(&me, &self.community_id, &cx.db, permission::can_post).await?;
56+ let tx = cx.db.transaction().await?;
57+ let created = message::create(
58+ &me.id,
59+ &self.community_id,
60+ &self.body,
61+ &self.attachments,
62+ self.reply_to.as_deref(),
63+ &tx,
64+ )
65+ .await?;
66+ stats::mark_active(&me.id, &tx).await?;
67+ tx.commit().await?;
68+ emit_message(&created, Event::MessageCreated, cx);
69+
70+ Ok(created)
71+ }
72+}
73+
74+impl Handle for ForwardMessages {
75+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> {
76+ let me = me.user()?;
77+ limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?;
78+ validate_forward(self.message_ids.len())?;
79+ ensure(permission::can_post(
80+ actor_rank(&me, &self.community_id, &cx.db).await?,
81+ ))?;
82+ let tx = cx.db.transaction().await?;
83+ let mut sources = Vec::new();
84+ for message_id in &self.message_ids {
85+ let source = message::read(message_id, &tx).await?;
86+ ensure(permission::can_read(
87+ actor_rank(&me, &source.community_id, &tx).await?,
88+ ))?;
89+ sources.push(source);
90+ }
91+ let mode = if self.snippet {
92+ message::ForwardMode::Snippet
93+ } else {
94+ message::ForwardMode::Copy
95+ };
96+ let created = message::forward(
97+ &me,
98+ &self.community_id,
99+ &sources,
100+ mode,
101+ &cx.sh.directory,
102+ &tx,
103+ )
104+ .await?;
105+ tx.commit().await?;
106+ for message in &created {
107+ emit_message(message, Event::MessageCreated, cx);
108+ }
109+
110+ Ok(created)
111+ }
112+}
113+
114+impl Handle for UpdateMessage {
115+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {
116+ let me = me.user()?;
117+ let existing = message::read(&self.message_id, &cx.db).await?;
118+ allowed(&me, &existing.community_id, &cx.db, permission::can_post).await?;
119+ ensure(existing.user_id == me.id)?;
120+ validate_new_message(
121+ &self.body,
122+ 0,
123+ server_settings::read(&cx.db).await?.max_message_length as usize,
124+ )?;
125+ let updated = message::update(&self.message_id, &self.body, &cx.db).await?;
126+ emit_message(&updated, Event::MessageUpdated, cx);
127+
128+ Ok(updated)
129+ }
130+}
131+
132+impl Handle for DeleteMessage {
133+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
134+ let me = me.user()?;
135+ let existing = message::read(&self.message_id, &cx.db).await?;
136+ let author = user::read(&existing.user_id, &cx.db).await?;
137+ ensure(permission::can_delete_message(
138+ actor_rank(&me, &existing.community_id, &cx.db).await?,
139+ actor_rank(&author, &existing.community_id, &cx.db).await?,
140+ existing.user_id == me.id,
141+ ))?;
142+ let deleted = message::delete(&self.message_id, &cx.db).await?;
143+ if existing.user_id != me.id {
144+ log::record(
145+ &deleted.community_id,
146+ Some(&me.id),
147+ Some(&existing.user_id),
148+ &LogAction::MessageDeleted,
149+ &cx.db,
150+ )
151+ .await?;
152+ }
153+ if permission::is_builder(me.role) && existing.user_id != me.id {
154+ let community = community::label(&deleted.community_id, &cx.db).await?;
155+ admin_log::record(
156+ Some(&me.id),
157+ Some(&existing.user_id),
158+ Some(&community),
159+ &AdminAction::MessageDeleted,
160+ &cx.db,
161+ )
162+ .await?;
163+ }
164+ cx.emit(
165+ To::Community(deleted.community_id.clone()),
166+ Event::MessagesDeleted {
167+ community_id: deleted.community_id,
168+ ids: vec![deleted.id],
169+ },
170+ );
171+
172+ Ok(())
173+ }
174+}
175+
176+impl Handle for CreatePoll {
177+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> {
178+ let me = me.user()?;
179+ let settings = server_settings::read(&cx.db).await?;
180+ limit_messages(&me, &settings, cx)?;
181+ validate_poll(&self.question, &self.options)?;
182+ allowed(&me, &self.community_id, &cx.db, permission::can_post).await?;
183+ let tx = cx.db.transaction().await?;
184+ let created = message::create_poll(
185+ &me.id,
186+ &self.community_id,
187+ &self.question,
188+ &self.options,
189+ self.multiple,
190+ &tx,
191+ )
192+ .await?;
193+ stats::mark_active(&me.id, &tx).await?;
194+ tx.commit().await?;
195+ emit_message(&created, Event::MessageCreated, cx);
196+
197+ Ok(created)
198+ }
199+}
200+
201+impl Handle for Vote {
202+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
203+ let me = me.user()?;
204+ let existing = message::read(&self.message_id, &cx.db).await?;
205+ ensure(permission::can_read(
206+ actor_rank(&me, &existing.community_id, &cx.db).await?,
207+ ))?;
208+ let poll = existing.poll.as_ref().ok_or(Error::NotFound)?;
209+ validate_vote(poll, &self.positions)?;
210+ let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?;
211+ emit_message(&updated, Event::MessageUpdated, cx);
212+
213+ Ok(())
214+ }
215+}
216+
217+impl Handle for ClosePoll {
218+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
219+ let me = me.user()?;
220+ let existing = message::read(&self.message_id, &cx.db).await?;
221+ ensure(permission::can_close_poll(
222+ actor_rank(&me, &existing.community_id, &cx.db).await?,
223+ existing.user_id == me.id,
224+ ))?;
225+ let updated = message::close_poll(&self.message_id, &cx.db).await?;
226+ emit_message(&updated, Event::MessageUpdated, cx);
227+
228+ Ok(())
229+ }
230+}
231+
232+impl Handle for React {
233+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
234+ let me = me.user()?;
235+ validate_reaction(&self.emoji)?;
236+ let existing = message::read(&self.message_id, &cx.db).await?;
237+ ensure(permission::can_read(
238+ actor_rank(&me, &existing.community_id, &cx.db).await?,
239+ ))?;
240+ let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?;
241+ emit_message(&updated, Event::MessageUpdated, cx);
242+
243+ Ok(())
244+ }
245+}
246+
247+impl Handle for Pin {
248+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
249+ let me = me.user()?;
250+ let existing = message::read(&self.message_id, &cx.db).await?;
251+ let direct = community::is_direct(&existing.community_id, &cx.db).await?;
252+ ensure(permission::can_pin(
253+ actor_rank(&me, &existing.community_id, &cx.db).await?,
254+ direct,
255+ ))?;
256+ let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?;
257+ emit_message(&updated, Event::MessageUpdated, cx);
258+
259+ Ok(())
260+ }
261+}
262+
263+impl Handle for ListPins {
264+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> {
265+ let me = me.user()?;
266+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
267+
268+ message::pinned(&self.community_id, &cx.db).await
269+ }
270+}
271+
272+impl Handle for ListMessages {
273+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> {
274+ let me = me.user()?;
275+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
276+
277+ message::read_page(&self.community_id, self.before.as_deref(), &cx.db).await
278+ }
279+}
280+
281+impl Handle for ListUnreads {
282+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Unread>, ServerError> {
283+ let me = me.user()?;
284+
285+ user_community::unreads(&me.id, &me.username, &cx.db).await
286+ }
287+}
288+
289+impl Handle for MarkRead {
290+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
291+ let me = me.user()?;
292+ ensure(!is_outsider(&me.id, &self.community_id, &cx.db).await?)?;
293+ message::ensure_in_community(&self.message_id, &self.community_id, &cx.db).await?;
294+ user_community::mark_read(&me.id, &self.community_id, &self.message_id, &cx.db).await?;
295+
296+ Ok(())
297+ }
298+}
299+
300+impl Handle for Typing {
301+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
302+ let me = me.user()?;
303+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
304+ if user::is_ghost(&me.id, &cx.db).await? {
305+ return Ok(());
306+ }
307+ let others: Vec<String> = user_community::member_ids(&self.community_id, &cx.db)
308+ .await?
309+ .into_iter()
310+ .filter(|user_id| *user_id != me.id)
311+ .collect();
312+ cx.emit(
313+ To::Users(others),
314+ Event::Typing {
315+ community_id: self.community_id,
316+ user_id: me.id,
317+ },
318+ );
319+
320+ Ok(())
321+ }
322+}
crates/server/src/call/mod.rsmodified+99 -19
@@ -1,9 +1,14 @@
1+mod admin;
2+mod community;
3+mod message;
4+mod social;
1 mod user;5 mod user;
6+mod voice;
2 7
3 use std::{future::Future, sync::Arc};8 use std::{future::Future, sync::Arc};
4 9
5 use common::{10 use common::{
6- call::{Call, Gate, Legacy, Request},11+ call::{Call, Gate, Request},
7 error::Error,12 error::Error,
8 event::Event,13 event::Event,
9 frame::{self, DOWN_MAX},14 frame::{self, DOWN_MAX},
@@ -90,7 +95,6 @@ async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> {
90 95
91 pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {96 pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
92 match request {97 match request {
93- Request::Legacy(call) => serve(call, cx).await,
94 Request::GetSettings(call) => serve(call, cx).await,98 Request::GetSettings(call) => serve(call, cx).await,
95 Request::GetUser(call) => serve(call, cx).await,99 Request::GetUser(call) => serve(call, cx).await,
96 Request::UpdateUser(call) => serve(call, cx).await,100 Request::UpdateUser(call) => serve(call, cx).await,
@@ -102,22 +106,98 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
102 Request::GetAvatar(call) => serve(call, cx).await,106 Request::GetAvatar(call) => serve(call, cx).await,
103 Request::ListSessions(call) => serve(call, cx).await,107 Request::ListSessions(call) => serve(call, cx).await,
104 Request::RevokeSession(call) => serve(call, cx).await,108 Request::RevokeSession(call) => serve(call, cx).await,
105- }109+ Request::CreateCommunity(call) => serve(call, cx).await,
106-}110+ Request::GetCommunity(call) => serve(call, cx).await,
107-111+ Request::UpdateCommunity(call) => serve(call, cx).await,
108-impl Handle for Legacy {112+ Request::UpdateCommunityAvatar(call) => serve(call, cx).await,
109- async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Self::Reply, ServerError> {113+ Request::DeleteCommunity(call) => serve(call, cx).await,
110- let (reply, broadcasts) = request::dispatch(114+ Request::LeaveCommunity(call) => serve(call, cx).await,
111- self.0,115+ Request::ListCommunities(call) => serve(call, cx).await,
112- cx.client,116+ Request::ListMembers(call) => serve(call, cx).await,
113- &cx.sh.db,117+ Request::Kick(call) => serve(call, cx).await,
114- &cx.sh.services,118+ Request::BanMember(call) => serve(call, cx).await,
115- &cx.sh.directory,119+ Request::Unban(call) => serve(call, cx).await,
116- &cx.sh.backups,120+ Request::ListBans(call) => serve(call, cx).await,
117- )121+ Request::SetRank(call) => serve(call, cx).await,
118- .await?;122+ Request::ListLogs(call) => serve(call, cx).await,
119- cx.out.extend(broadcasts);123+ Request::CreateMessage(call) => serve(call, cx).await,
120-124+ Request::ForwardMessages(call) => serve(call, cx).await,
121- Ok(reply)125+ Request::UpdateMessage(call) => serve(call, cx).await,
126+ Request::DeleteMessage(call) => serve(call, cx).await,
127+ Request::CreatePoll(call) => serve(call, cx).await,
128+ Request::Vote(call) => serve(call, cx).await,
129+ Request::ClosePoll(call) => serve(call, cx).await,
130+ Request::React(call) => serve(call, cx).await,
131+ Request::Pin(call) => serve(call, cx).await,
132+ Request::ListPins(call) => serve(call, cx).await,
133+ Request::ListMessages(call) => serve(call, cx).await,
134+ Request::ListUnreads(call) => serve(call, cx).await,
135+ Request::MarkRead(call) => serve(call, cx).await,
136+ Request::Typing(call) => serve(call, cx).await,
137+ Request::FindUser(call) => serve(call, cx).await,
138+ Request::OpenDirect(call) => serve(call, cx).await,
139+ Request::OpenNotes(call) => serve(call, cx).await,
140+ Request::ListFriends(call) => serve(call, cx).await,
141+ Request::AddFriend(call) => serve(call, cx).await,
142+ Request::AcceptFriend(call) => serve(call, cx).await,
143+ Request::RemoveFriend(call) => serve(call, cx).await,
144+ Request::Invite(call) => serve(call, cx).await,
145+ Request::ListInvitations(call) => serve(call, cx).await,
146+ Request::AcceptInvitation(call) => serve(call, cx).await,
147+ Request::DeclineInvitation(call) => serve(call, cx).await,
148+ Request::ReportMessage(call) => serve(call, cx).await,
149+ Request::ReportUser(call) => serve(call, cx).await,
150+ Request::ListReports(call) => serve(call, cx).await,
151+ Request::HandleReport(call) => serve(call, cx).await,
152+ Request::JoinVoice(call) => serve(call, cx).await,
153+ Request::LeaveVoice(call) => serve(call, cx).await,
154+ Request::StartShare(call) => serve(call, cx).await,
155+ Request::StopShare(call) => serve(call, cx).await,
156+ Request::ListShares(call) => serve(call, cx).await,
157+ Request::WatchShare(call) => serve(call, cx).await,
158+ Request::UnwatchShare(call) => serve(call, cx).await,
159+ Request::RequestKeyframe(call) => serve(call, cx).await,
160+ Request::DeclineCall(call) => serve(call, cx).await,
161+ Request::ListVoiceParticipants(call) => serve(call, cx).await,
162+ Request::ListVoiceRooms(call) => serve(call, cx).await,
163+ Request::KickFromVoice(call) => serve(call, cx).await,
164+ Request::ServerMute(call) => serve(call, cx).await,
165+ Request::Register(call) => serve(call, cx).await,
166+ Request::Login(call) => serve(call, cx).await,
167+ Request::Logout(call) => serve(call, cx).await,
168+ Request::DeleteUser(call) => serve(call, cx).await,
169+ Request::WatchCommunity(call) => serve(call, cx).await,
170+ Request::ListUsers(call) => serve(call, cx).await,
171+ Request::SetRole(call) => serve(call, cx).await,
172+ Request::ListAdminLogs(call) => serve(call, cx).await,
173+ Request::GetOverview(call) => serve(call, cx).await,
174+ Request::SuspendUser(call) => serve(call, cx).await,
175+ Request::RevokeSessions(call) => serve(call, cx).await,
176+ Request::ResetPassword(call) => serve(call, cx).await,
177+ Request::ClearProfile(call) => serve(call, cx).await,
178+ Request::ListAllCommunities(call) => serve(call, cx).await,
179+ Request::TransferOwnership(call) => serve(call, cx).await,
180+ Request::UpdateServerSettings(call) => serve(call, cx).await,
181+ Request::CreateUser(call) => serve(call, cx).await,
182+ Request::RenameUser(call) => serve(call, cx).await,
183+ Request::TimeoutUser(call) => serve(call, cx).await,
184+ Request::BanUser(call) => serve(call, cx).await,
185+ Request::ListServerBans(call) => serve(call, cx).await,
186+ Request::RemoveServerBan(call) => serve(call, cx).await,
187+ Request::CreateInviteCode(call) => serve(call, cx).await,
188+ Request::ListInviteCodes(call) => serve(call, cx).await,
189+ Request::DeleteInviteCode(call) => serve(call, cx).await,
190+ Request::SearchMessages(call) => serve(call, cx).await,
191+ Request::SearchCommunity(call) => serve(call, cx).await,
192+ Request::PurgeUser(call) => serve(call, cx).await,
193+ Request::SetCommunityVoice(call) => serve(call, cx).await,
194+ Request::ListAttachments(call) => serve(call, cx).await,
195+ Request::DeleteAttachment(call) => serve(call, cx).await,
196+ Request::GetStorageUsage(call) => serve(call, cx).await,
197+ Request::GetDailyStats(call) => serve(call, cx).await,
198+ Request::SetGhost(call) => serve(call, cx).await,
199+ Request::CreateBackup(call) => serve(call, cx).await,
200+ Request::ListBackups(call) => serve(call, cx).await,
201+ Request::DeleteBackup(call) => serve(call, cx).await,
122 }202 }
123 }203 }
crates/server/src/call/social.rsadded+271 -0
@@ -0,0 +1,271 @@
1+use common::{
2+ call::{
3+ AcceptFriend, AcceptInvitation, AddFriend, DeclineInvitation, FindUser, HandleReport,
4+ Invite, ListFriends, ListInvitations, ListReports, OpenDirect, OpenNotes, RemoveFriend,
5+ ReportMessage, ReportUser,
6+ },
7+ error::Error,
8+ event::Event,
9+ model::{
10+ AdminAction, Community, Friends, Invitation, LogAction, Member, Rank, Report, ReportStatus,
11+ User,
12+ },
13+ permission,
14+ validate::validate_reason,
15+};
16+
17+use crate::{
18+ admin_log,
19+ call::{Cx, Handle, Me},
20+ community, direct,
21+ error::ServerError,
22+ friend, invitation, log, message, notes,
23+ publish::To,
24+ report,
25+ request::{actor_rank, allowed, ensure, ensure_editable, ensure_with},
26+ user, user_community,
27+};
28+
29+async fn friends_updated(user_ids: [&str; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> {
30+ for user_id in user_ids {
31+ let event = Event::FriendsUpdated(friend::state(user_id, &cx.db).await?);
32+ cx.emit(To::User(user_id.to_string()), event);
33+ }
34+
35+ Ok(())
36+}
37+
38+async fn invitations_updated(user_id: &str, cx: &mut Cx<'_>) -> Result<(), ServerError> {
39+ let event = Event::InvitationsUpdated(invitation::of(user_id, &cx.db).await?);
40+ cx.emit(To::User(user_id.to_string()), event);
41+
42+ Ok(())
43+}
44+
45+impl Handle for FindUser {
46+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> {
47+ let me = me.user()?;
48+
49+ user::by_username(&self.username, &cx.db)
50+ .await?
51+ .filter(|found| found.id != me.id)
52+ .ok_or(Error::NotFound.into())
53+ }
54+}
55+
56+impl Handle for OpenDirect {
57+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
58+ let me = me.user()?;
59+ match direct::open(&me.id, &self.user_id, &mut cx.db).await? {
60+ direct::Opening::Created(community) => {
61+ let peer_view = community::read(&community.id, &self.user_id, &cx.db).await?;
62+ cx.emit(To::User(self.user_id), Event::CommunityAdded(peer_view));
63+
64+ Ok(community)
65+ }
66+ direct::Opening::Existing(community) => Ok(community),
67+ }
68+ }
69+}
70+
71+impl Handle for OpenNotes {
72+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
73+ let me = me.user()?;
74+
75+ notes::open(&me.id, &mut cx.db).await
76+ }
77+}
78+
79+impl Handle for ListFriends {
80+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Friends, ServerError> {
81+ let me = me.user()?;
82+
83+ friend::state(&me.id, &cx.db).await
84+ }
85+}
86+
87+impl Handle for AddFriend {
88+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
89+ let me = me.user()?;
90+ friend::add(&me.id, &self.user_id, &mut cx.db).await?;
91+
92+ friends_updated([&me.id, &self.user_id], cx).await
93+ }
94+}
95+
96+impl Handle for AcceptFriend {
97+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
98+ let me = me.user()?;
99+ friend::accept(&me.id, &self.user_id, &mut cx.db).await?;
100+
101+ friends_updated([&me.id, &self.user_id], cx).await
102+ }
103+}
104+
105+impl Handle for RemoveFriend {
106+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
107+ let me = me.user()?;
108+ friend::remove(&me.id, &self.user_id, &mut cx.db).await?;
109+
110+ friends_updated([&me.id, &self.user_id], cx).await
111+ }
112+}
113+
114+impl Handle for Invite {
115+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
116+ let me = me.user()?;
117+ ensure_editable(&self.community_id, &cx.db).await?;
118+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
119+ let target = user::read(&self.user_id, &cx.db).await?;
120+ if user_community::rank(&self.user_id, &self.community_id, &cx.db)
121+ .await?
122+ .is_some()
123+ {
124+ return Err(Error::AlreadyMember.into());
125+ }
126+ let banned = user_community::is_banned(&self.user_id, &self.community_id, &cx.db).await?;
127+ ensure(permission::can_join(target.role, banned))?;
128+ if invitation::exists(&self.community_id, &self.user_id, &cx.db).await? {
129+ return Err(Error::AlreadyInvited.into());
130+ }
131+ invitation::insert(&self.community_id, &self.user_id, &me.id, &cx.db).await?;
132+ log::record(
133+ &self.community_id,
134+ Some(&me.id),
135+ Some(&self.user_id),
136+ &LogAction::Invited,
137+ &cx.db,
138+ )
139+ .await?;
140+
141+ invitations_updated(&self.user_id, cx).await
142+ }
143+}
144+
145+impl Handle for ListInvitations {
146+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Invitation>, ServerError> {
147+ let me = me.user()?;
148+
149+ invitation::of(&me.id, &cx.db).await
150+ }
151+}
152+
153+impl Handle for AcceptInvitation {
154+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> {
155+ let me = me.user()?;
156+ let tx = cx.db.transaction().await?;
157+ invitation::take(&self.community_id, &me.id, &tx).await?;
158+ let banned = user_community::is_banned(&me.id, &self.community_id, &tx).await?;
159+ ensure(permission::can_join(me.role, banned))?;
160+ user_community::join(&me.id, &self.community_id, Rank::Member, &tx).await?;
161+ log::record(
162+ &self.community_id,
163+ Some(&me.id),
164+ None,
165+ &LogAction::Joined,
166+ &tx,
167+ )
168+ .await?;
169+ let community = community::read(&self.community_id, &me.id, &tx).await?;
170+ tx.commit().await?;
171+ let event = Event::MemberJoined {
172+ community_id: self.community_id.clone(),
173+ member: Member {
174+ user: me.clone(),
175+ rank: Rank::Member,
176+ },
177+ };
178+ cx.emit(To::Community(self.community_id), event);
179+ invitations_updated(&me.id, cx).await?;
180+
181+ Ok(community)
182+ }
183+}
184+
185+impl Handle for DeclineInvitation {
186+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
187+ let me = me.user()?;
188+ invitation::take(&self.community_id, &me.id, &cx.db).await?;
189+
190+ invitations_updated(&me.id, cx).await
191+ }
192+}
193+
194+impl Handle for ReportMessage {
195+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
196+ let me = me.user()?;
197+ let message = message::read(&self.message_id, &cx.db).await?;
198+ let actor = actor_rank(&me, &message.community_id, &cx.db).await?;
199+ ensure(permission::can_read(actor) && me.id != message.user_id)?;
200+ validate_reason(Some(&self.reason))?;
201+ ensure_with(
202+ !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?,
203+ Error::Taken,
204+ )?;
205+ report::insert(
206+ &me.id,
207+ &message.user_id,
208+ Some(&self.message_id),
209+ Some(&message.community_id),
210+ Some(&message.body),
211+ &self.reason,
212+ &cx.db,
213+ )
214+ .await?;
215+ cx.emit(To::Builders, Event::ReportCreated);
216+
217+ Ok(())
218+ }
219+}
220+
221+impl Handle for ReportUser {
222+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
223+ let me = me.user()?;
224+ user::read(&self.user_id, &cx.db).await?;
225+ ensure(me.id != self.user_id)?;
226+ validate_reason(Some(&self.reason))?;
227+ ensure_with(
228+ !report::is_open(&me.id, &self.user_id, None, &cx.db).await?,
229+ Error::Taken,
230+ )?;
231+ report::insert(
232+ &me.id,
233+ &self.user_id,
234+ None,
235+ None,
236+ None,
237+ &self.reason,
238+ &cx.db,
239+ )
240+ .await?;
241+ cx.emit(To::Builders, Event::ReportCreated);
242+
243+ Ok(())
244+ }
245+}
246+
247+impl Handle for ListReports {
248+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<Report>, ServerError> {
249+ report::list(self.status, &cx.db).await
250+ }
251+}
252+
253+impl Handle for HandleReport {
254+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
255+ let me = me.user()?;
256+ ensure(permission::is_builder(me.role) && self.status != ReportStatus::Open)?;
257+ let target = report::handle(&self.report_id, self.status, &me.id, &cx.db).await?;
258+ admin_log::record(
259+ Some(&me.id),
260+ target.as_deref(),
261+ None,
262+ &AdminAction::ReportHandled {
263+ status: self.status,
264+ },
265+ &cx.db,
266+ )
267+ .await?;
268+
269+ Ok(())
270+ }
271+}
crates/server/src/call/voice.rsadded+249 -0
@@ -0,0 +1,249 @@
1+use common::{
2+ call::{
3+ DeclineCall, JoinVoice, KickFromVoice, LeaveVoice, ListShares, ListVoiceParticipants,
4+ ListVoiceRooms, RequestKeyframe, ServerMute, StartShare, StopShare, UnwatchShare,
5+ WatchShare,
6+ },
7+ error::Error,
8+ event::Event,
9+ model::{AdminAction, CallLog, VoiceRoom},
10+ permission,
11+ share::Share,
12+};
13+
14+use crate::{
15+ admin_log,
16+ call::{Cx, Handle, Me},
17+ community,
18+ error::ServerError,
19+ message,
20+ publish::{Broadcast, To},
21+ request::{
22+ allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event,
23+ share_ended, voice_joined, voice_muted, voice_rooms,
24+ },
25+ user,
26+};
27+
28+impl Handle for JoinVoice {
29+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<String>, ServerError> {
30+ let me = me.user()?;
31+ let community_id = self.community_id;
32+ let rooms = &cx.sh.services.rooms;
33+ allowed(&me, &community_id, &cx.db, permission::can_join_voice).await?;
34+ ensure(community::kind(&community_id, &cx.db).await? != community::Kind::Notes)?;
35+ ensure(
36+ permission::is_builder(me.role)
37+ || community::voice_enabled(&community_id, &cx.db).await?,
38+ )?;
39+ let muted = user::voice_muted(&me.id, &cx.db).await?;
40+ let outsider = is_outsider(&me.id, &community_id, &cx.db).await?;
41+ let ghost = outsider || user::is_ghost(&me.id, &cx.db).await?;
42+ let starts_call = !ghost
43+ && community::is_direct(&community_id, &cx.db).await?
44+ && rooms.participants(&community_id).is_empty();
45+ let joined = rooms.join(cx.client, &community_id, muted, ghost)?;
46+ let mut broadcasts = match joined.departure {
47+ Some(departure) => departed(departure, &cx.db).await?,
48+ None => Vec::new(),
49+ };
50+ if starts_call {
51+ let created =
52+ message::create_call_log(&community_id, &me.id, CallLog::Started, &cx.db).await?;
53+ broadcasts.push(message_event(&created, Event::MessageCreated));
54+ }
55+ if !ghost && !joined.transferred {
56+ broadcasts.extend(voice_joined(&community_id, &me.id, muted));
57+ }
58+ cx.out.extend(broadcasts);
59+
60+ Ok(rooms.participants(&community_id))
61+ }
62+}
63+
64+impl Handle for LeaveVoice {
65+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
66+ me.user()?;
67+ if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) {
68+ let broadcasts = departed(departure, &cx.db).await?;
69+ cx.out.extend(broadcasts);
70+ }
71+
72+ Ok(())
73+ }
74+}
75+
76+impl Handle for StartShare {
77+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
78+ let me = me.user()?;
79+ let rooms = &cx.sh.services.rooms;
80+ let Some(community_id) = rooms.room_of_conn(cx.client.id) else {
81+ return Err(Error::NotFound.into());
82+ };
83+ allowed(&me, &community_id, &cx.db, permission::can_share).await?;
84+ ensure(!self.source.encode.is_empty())?;
85+ ensure(!user::is_ghost(&me.id, &cx.db).await?)?;
86+ let event = Event::ShareStarted {
87+ community_id: community_id.clone(),
88+ share: Share {
89+ user_id: me.id.clone(),
90+ kind: self.kind,
91+ source: self.source.clone(),
92+ },
93+ };
94+ let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)];
95+ broadcasts.extend(
96+ rooms
97+ .start_share(cx.client.id, self.kind, self.source)
98+ .ok_or(Error::NotFound)?,
99+ );
100+ cx.out.extend(broadcasts);
101+
102+ Ok(())
103+ }
104+}
105+
106+impl Handle for StopShare {
107+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
108+ let me = me.user()?;
109+ if let Some(community_id) = cx.sh.services.rooms.stop_share(cx.client.id, self.kind) {
110+ cx.out.push(share_ended(&community_id, &me.id, self.kind));
111+ }
112+
113+ Ok(())
114+ }
115+}
116+
117+impl Handle for ListShares {
118+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Share>, ServerError> {
119+ let me = me.user()?;
120+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
121+
122+ Ok(cx.sh.services.rooms.shares(&self.community_id))
123+ }
124+}
125+
126+impl Handle for WatchShare {
127+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
128+ me.user()?;
129+ let broadcasts = cx
130+ .sh
131+ .services
132+ .rooms
133+ .watch(
134+ cx.client.id,
135+ &self.user_id,
136+ self.kind,
137+ self.quality,
138+ &self.decode,
139+ )
140+ .ok_or(Error::NotFound)?;
141+ cx.out.extend(broadcasts);
142+
143+ Ok(())
144+ }
145+}
146+
147+impl Handle for UnwatchShare {
148+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
149+ me.user()?;
150+ let broadcasts = cx
151+ .sh
152+ .services
153+ .rooms
154+ .unwatch(cx.client.id, &self.user_id, self.kind);
155+ cx.out.extend(broadcasts);
156+
157+ Ok(())
158+ }
159+}
160+
161+impl Handle for RequestKeyframe {
162+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
163+ me.user()?;
164+ let keyframe = cx
165+ .sh
166+ .services
167+ .rooms
168+ .keyframe(cx.client.id, &self.user_id, self.kind)
169+ .ok_or(Error::NotFound)?;
170+ cx.out.push(keyframe);
171+
172+ Ok(())
173+ }
174+}
175+
176+impl Handle for DeclineCall {
177+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
178+ let me = me.user()?;
179+ let community_id = self.community_id;
180+ let rooms = &cx.sh.services.rooms;
181+ ensure(community::is_direct(&community_id, &cx.db).await?)?;
182+ allowed(&me, &community_id, &cx.db, permission::can_read).await?;
183+ let participants = rooms.participants(&community_id);
184+ ensure(!participants.is_empty() && !participants.contains(&me.id))?;
185+ rooms.decline(&community_id);
186+ let created =
187+ message::create_call_log(&community_id, &me.id, CallLog::Declined, &cx.db).await?;
188+ cx.out.push(message_event(&created, Event::MessageCreated));
189+
190+ Ok(())
191+ }
192+}
193+
194+impl Handle for ListVoiceParticipants {
195+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<String>, ServerError> {
196+ let me = me.user()?;
197+ allowed(&me, &self.community_id, &cx.db, permission::can_read).await?;
198+
199+ Ok(cx.sh.services.rooms.participants(&self.community_id))
200+ }
201+}
202+
203+impl Handle for ListVoiceRooms {
204+ async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<VoiceRoom>, ServerError> {
205+ voice_rooms(&cx.sh.services.rooms, &cx.db).await
206+ }
207+}
208+
209+impl Handle for KickFromVoice {
210+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
211+ let me = me.user()?;
212+ managed(&me, &self.user_id, &cx.db).await?;
213+ let broadcasts = leave_user_voice(&cx.sh.services.rooms, &self.user_id, &cx.db).await?;
214+ if !broadcasts.is_empty() {
215+ admin_log::record(
216+ Some(&me.id),
217+ Some(&self.user_id),
218+ None,
219+ &AdminAction::VoiceKicked,
220+ &cx.db,
221+ )
222+ .await?;
223+ }
224+ cx.out.extend(broadcasts);
225+
226+ Ok(())
227+ }
228+}
229+
230+impl Handle for ServerMute {
231+ async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> {
232+ let me = me.user()?;
233+ managed(&me, &self.user_id, &cx.db).await?;
234+ user::set_voice_muted(&self.user_id, self.muted, &cx.db).await?;
235+ admin_log::record(
236+ Some(&me.id),
237+ Some(&self.user_id),
238+ None,
239+ &AdminAction::VoiceMuted { muted: self.muted },
240+ &cx.db,
241+ )
242+ .await?;
243+ let community_id = cx.sh.services.rooms.set_muted(&self.user_id, self.muted);
244+ let broadcast = voice_muted(community_id, &self.user_id, self.muted, &cx.db).await?;
245+ cx.out.push(broadcast);
246+
247+ Ok(())
248+ }
249+}
crates/server/src/request.rsmodified+119 -1725

Diff too large; view file

@@ -1,1525 +1,27 @@
1-use std::{collections::BTreeMap, path::Path};
2-
3 use common::{1 use common::{
4 error::Error as CommonError,2 error::Error as CommonError,
5 event::Event,3 event::Event,
6- model::{4+ model::{AdminAction, CallLog, Message, Presence, Rank, User, VoiceRoom},
7- AdminAction, BanScope, CallLog, CommunitySummary, LogAction, Member, Message, Presence,
8- Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom,
9- },
10 permission,5 permission,
11- request::LegacyRequest,6+ share::Kind,
12- response::Response,
13- share::{Kind, Share},
14- time::{self, MINUTE_MILLIS},
15- transport::Close,
16- validate::{
17- validate_avatar_size, validate_forward, validate_new_message, validate_poll,
18- validate_reaction, validate_reason, validate_server_settings, validate_vote,
19- },
20 };7 };
21 use turso::Connection;8 use turso::Connection;
22 9
23 use crate::{10 use crate::{
24- admin_log, attachment, authentication, backup, community,11+ admin_log, community,
25- database::{self, DB},
26- direct,
27 error::ServerError,12 error::ServerError,
28- friend,
29 hub::{Client, Hub},13 hub::{Client, Hub},
30- invitation, invite, log, message,14+ message,
31- network::Services,
32- notes, overview,
33 publish::{Broadcast, To},15 publish::{Broadcast, To},
34 rate_limit::RateLimit,16 rate_limit::RateLimit,
35- report,
36 rooms::{Departure, Rooms},17 rooms::{Departure, Rooms},
37- server_ban, server_settings, stats, user, user_community,18+ server_settings, user, user_community,
38 };19 };
39 20
40-pub(crate) type Outcome = (Response, Vec<Broadcast>);21+pub(crate) async fn voice_rooms(
41-22+ occupied: &Rooms,
42-#[cfg(test)]23+ conn: &Connection,
43-pub async fn handle(24+) -> Result<Vec<VoiceRoom>, ServerError> {
44- request: LegacyRequest,
45- client: &Client,
46- db: &DB,
47- services: &Services,
48- directory: &Path,
49- backups: &Path,
50-) -> (Result<Response, CommonError>, Vec<Broadcast>) {
51- match dispatch(request, client, db, services, directory, backups).await {
52- Ok((response, broadcasts)) => (Ok(response), broadcasts),
53- Err(error) => (Err(error.into()), Vec::new()),
54- }
55-}
56-
57-pub(crate) async fn dispatch(
58- request: LegacyRequest,
59- client: &Client,
60- db: &DB,
61- services: &Services,
62- directory: &Path,
63- backups: &Path,
64-) -> Result<Outcome, ServerError> {
65- let Services {
66- rooms,
67- hub,
68- rate_limit,
69- } = services;
70- let connection = client.conn.as_ref();
71- let mut conn = database::connect(db).await?;
72-
73- let outcome = match request {
74- LegacyRequest::Register {
75- username,
76- password,
77- invite,
78- } => {
79- limit_logins(rate_limit, connection, &conn).await?;
80- let (user, token) =
81- authentication::register(&username, &password, invite.as_deref(), &mut conn)
82- .await?;
83- (Response::Session { user, token }, Vec::new())
84- }
85- LegacyRequest::Login { username, password } => {
86- limit_logins(rate_limit, connection, &conn).await?;
87- let (user, token) = authentication::login(&username, &password, &conn).await?;
88- (Response::Session { user, token }, Vec::new())
89- }
90- LegacyRequest::Logout => {
91- authenticated(client, &conn).await?;
92- let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?;
93- authentication::logout(&me.token, &conn).await?;
94- (Response::Done, Vec::new())
95- }
96- LegacyRequest::UpdateServerSettings { settings } => {
97- let me = builder(client, &conn).await?;
98- validate_server_settings(&settings)?;
99- server_settings::update(&settings, &conn).await?;
100- admin_log::record(
101- Some(&me.id),
102- None,
103- None,
104- &AdminAction::SettingsChanged,
105- &conn,
106- )
107- .await?;
108- if settings.maintenance {
109- let builders = user::builder_ids(&conn).await?;
110- hub.kick_all_except(&builders, Close::Maintenance);
111- }
112- let broadcasts = vec![Broadcast::new(
113- To::Everyone,
114- Event::SettingsUpdated(settings.clone()),
115- )];
116- (Response::ServerSettings(settings), broadcasts)
117- }
118- LegacyRequest::RenameUser { user_id, username } => {
119- let me = authenticated(client, &conn).await?;
120- let target = managed(&me, &user_id, &conn).await?;
121- let user = user::update(&user_id, &username, &conn).await?;
122- admin_log::record(
123- Some(&me.id),
124- Some(&user_id),
125- None,
126- &AdminAction::UserRenamed {
127- from: target.username,
128- },
129- &conn,
130- )
131- .await?;
132- let broadcasts = user_updated(&user);
133- (Response::User(user), broadcasts)
134- }
135- LegacyRequest::CreateUser { username, password } => {
136- let me = builder(client, &conn).await?;
137- let user = authentication::create_account(&username, &password, &conn).await?;
138- admin_log::record(
139- Some(&me.id),
140- Some(&user.id),
141- None,
142- &AdminAction::UserCreated,
143- &conn,
144- )
145- .await?;
146- (Response::User(user), Vec::new())
147- }
148- LegacyRequest::Users => {
149- builder(client, &conn).await?;
150- (Response::Users(user::all(&conn).await?), Vec::new())
151- }
152- LegacyRequest::AdminLogs {
153- actor_id,
154- target_id,
155- action,
156- after_ms,
157- before_ms,
158- } => {
159- builder(client, &conn).await?;
160- (
161- Response::AdminLogs(
162- admin_log::list(
163- actor_id.as_deref(),
164- target_id.as_deref(),
165- action.as_deref(),
166- after_ms,
167- before_ms,
168- &conn,
169- )
170- .await?,
171- ),
172- Vec::new(),
173- )
174- }
175- LegacyRequest::DailyStats { days } => {
176- builder(client, &conn).await?;
177- (
178- Response::DailyStats(stats::daily(days, &conn).await?),
179- Vec::new(),
180- )
181- }
182- LegacyRequest::Overview => {
183- builder(client, &conn).await?;
184- (
185- Response::Overview(overview::read(hub, rooms, &conn).await?),
186- Vec::new(),
187- )
188- }
189- LegacyRequest::SuspendUser { user_id, suspended } => {
190- let me = authenticated(client, &conn).await?;
191- managed(&me, &user_id, &conn).await?;
192- user::set_suspended(&user_id, suspended, &conn).await?;
193- let action = if suspended {
194- AdminAction::UserSuspended
195- } else {
196- AdminAction::UserUnsuspended
197- };
198- admin_log::record(Some(&me.id), Some(&user_id), None, &action, &conn).await?;
199- if suspended {
200- authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?;
201- }
202- (Response::Done, Vec::new())
203- }
204- LegacyRequest::RevokeSessions { user_id } => {
205- let me = authenticated(client, &conn).await?;
206- managed(&me, &user_id, &conn).await?;
207- authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?;
208- admin_log::record(
209- Some(&me.id),
210- Some(&user_id),
211- None,
212- &AdminAction::SessionsRevoked,
213- &conn,
214- )
215- .await?;
216- (Response::Done, Vec::new())
217- }
218- LegacyRequest::ResetPassword { user_id, password } => {
219- let me = authenticated(client, &conn).await?;
220- managed(&me, &user_id, &conn).await?;
221- authentication::reset_password(&user_id, &password, &conn).await?;
222- authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?;
223- admin_log::record(
224- Some(&me.id),
225- Some(&user_id),
226- None,
227- &AdminAction::PasswordReset,
228- &conn,
229- )
230- .await?;
231- (Response::Done, Vec::new())
232- }
233- LegacyRequest::ClearProfile { user_id } => {
234- let me = authenticated(client, &conn).await?;
235- managed(&me, &user_id, &conn).await?;
236- user::set_avatar(&user_id, None, &mut conn).await?;
237- let user = user::update_status(&user_id, "", &conn).await?;
238- admin_log::record(
239- Some(&me.id),
240- Some(&user_id),
241- None,
242- &AdminAction::ProfileCleared,
243- &conn,
244- )
245- .await?;
246- let broadcasts = user_updated(&user);
247- (Response::User(user), broadcasts)
248- }
249- LegacyRequest::SetRole { user_id, role } => {
250- let me = authenticated(client, &conn).await?;
251- ensure(permission::can_set_role(me.role, me.id == user_id))?;
252- let user = user::set_role_by_id(&user_id, role, &conn).await?;
253- admin_log::record(
254- Some(&me.id),
255- Some(&user_id),
256- None,
257- &AdminAction::RoleChanged { role },
258- &conn,
259- )
260- .await?;
261- let mut broadcasts = user_updated(&user);
262- if permission::is_builder(role) {
263- broadcasts.extend(voice_unmuted(rooms, &user_id, &conn).await?);
264- } else {
265- user::set_ghost(&user_id, false, &conn).await?;
266- hub.kick_user(&user_id, Close::Revoked);
267- }
268- (Response::User(user), broadcasts)
269- }
270- LegacyRequest::DeleteUser { user_id } => {
271- let me = authenticated(client, &conn).await?;
272- let target = user::read(&user_id, &conn).await?;
273- ensure(permission::can_delete_user(
274- me.role,
275- me.id == user_id,
276- target.role,
277- ))?;
278- let tx = conn.transaction().await?;
279- let mut broadcasts = Vec::new();
280- if permission::is_builder(me.role) && me.id != user_id {
281- admin_log::record(
282- Some(&me.id),
283- Some(&user_id),
284- None,
285- &AdminAction::UserDeleted,
286- &tx,
287- )
288- .await?;
289- }
290- for community_id in user_community::owned(&user_id, &tx).await? {
291- let member_ids = user_community::member_ids(&community_id, &tx).await?;
292- broadcasts.extend(voice_closed(rooms, &community_id, &tx).await?);
293- community::delete(&community_id, &user_id, &tx).await?;
294- let event = Event::CommunityDeleted { community_id };
295- broadcasts.push(Broadcast::new(To::Users(member_ids), event));
296- }
297- for community in community::communities_of(&user_id, &tx).await? {
298- let member_ids = user_community::member_ids(&community.id, &tx).await?;
299- if community.kind.is_direct() {
300- community::delete(&community.id, &user_id, &tx).await?;
301- }
302- let event = Event::UserDeleted {
303- user_id: user_id.clone(),
304- };
305- broadcasts.push(Broadcast::new(To::Users(member_ids), event));
306- }
307- broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?);
308- let deleted = user::delete(&user_id, &tx).await?;
309- tx.commit().await?;
310- if me.id != user_id {
311- hub.kick_user(&user_id, Close::Revoked);
312- }
313- (Response::User(deleted), broadcasts)
314- }
315- LegacyRequest::CreateCommunity { name } => {
316- let me = authenticated(client, &conn).await?;
317- let limit = server_settings::read(&conn).await?.max_communities_per_user;
318- let owned = user_community::owned_groups(&me.id, &conn).await?;
319- ensure_with(
320- limit == 0 || owned < limit as usize,
321- CommonError::LimitReached,
322- )?;
323- let tx = conn.transaction().await?;
324- let community = community::create(&name, &tx).await?;
325- user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?;
326- log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?;
327- tx.commit().await?;
328- (Response::Community(community), Vec::new())
329- }
330- LegacyRequest::ReadCommunity { community_id } => {
331- let me = authenticated(client, &conn).await?;
332- allowed(&me, &community_id, &conn, permission::can_read).await?;
333- (
334- Response::Community(community::read(&community_id, &me.id, &conn).await?),
335- Vec::new(),
336- )
337- }
338- LegacyRequest::UpdateCommunity { community_id, name } => {
339- let me = authenticated(client, &conn).await?;
340- ensure_editable(&community_id, &conn).await?;
341- allowed(&me, &community_id, &conn, permission::can_rename_community).await?;
342- let updated = community::update(&community_id, &name, &me.id, &conn).await?;
343- let action = LogAction::Renamed {
344- name: updated.name.clone(),
345- };
346- log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
347- let event = Event::CommunityUpdated(updated.clone());
348- (
349- Response::Community(updated),
350- vec![Broadcast::new(To::Community(community_id), event)],
351- )
352- }
353- LegacyRequest::UpdateCommunityAvatar {
354- community_id,
355- image,
356- } => {
357- let me = authenticated(client, &conn).await?;
358- ensure_editable(&community_id, &conn).await?;
359- allowed(&me, &community_id, &conn, permission::can_rename_community).await?;
360- if let Some(bytes) = &image {
361- validate_avatar_size(bytes, server_settings::read(&conn).await?.max_avatar_bytes)?;
362- }
363- let updated =
364- community::set_avatar(&community_id, image.as_deref(), &me.id, &mut conn).await?;
365- let action = if image.is_some() {
366- LogAction::AvatarChanged
367- } else {
368- LogAction::AvatarRemoved
369- };
370- log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
371- let event = Event::CommunityUpdated(updated.clone());
372- (
373- Response::Community(updated),
374- vec![Broadcast::new(To::Community(community_id), event)],
375- )
376- }
377- LegacyRequest::DeleteCommunity { community_id } => {
378- let me = authenticated(client, &conn).await?;
379- ensure_editable(&community_id, &conn).await?;
380- allowed(&me, &community_id, &conn, permission::can_delete_community).await?;
381- let tx = conn.transaction().await?;
382- let member_ids = user_community::member_ids(&community_id, &tx).await?;
383- let owned =
384- user_community::rank(&me.id, &community_id, &tx).await? == Some(Rank::Owner);
385- let deleted = community::delete(&community_id, &me.id, &tx).await?;
386- if permission::is_builder(me.role) && !owned {
387- admin_log::record(
388- Some(&me.id),
389- None,
390- Some(&deleted.name),
391- &AdminAction::CommunityDeleted,
392- &tx,
393- )
394- .await?;
395- }
396- tx.commit().await?;
397- let mut broadcasts = voice_closed(rooms, &community_id, &conn).await?;
398- let event = Event::CommunityDeleted {
399- community_id: deleted.id.clone(),
400- };
401- broadcasts.push(Broadcast::new(To::Users(member_ids), event));
402- (Response::Community(deleted), broadcasts)
403- }
404- LegacyRequest::LeaveCommunity { community_id } => {
405- let me = authenticated(client, &conn).await?;
406- ensure_editable(&community_id, &conn).await?;
407- allowed(&me, &community_id, &conn, permission::can_leave).await?;
408- let tx = conn.transaction().await?;
409- user_community::leave(&me.id, &community_id, &tx).await?;
410- log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?;
411- if user_community::member_ids(&community_id, &tx)
412- .await?
413- .is_empty()
414- {
415- community::delete(&community_id, &me.id, &tx).await?;
416- }
417- tx.commit().await?;
418- let mut broadcasts = leave_room_voice(rooms, &community_id, &me.id, &conn).await?;
419- let event = Event::MemberLeft {
420- community_id: community_id.clone(),
421- user_id: me.id,
422- };
423- broadcasts.push(Broadcast::new(To::Community(community_id), event));
424- (Response::Done, broadcasts)
425- }
426- LegacyRequest::Communities => {
427- let me = authenticated(client, &conn).await?;
428- (
429- Response::Communities(community::communities_of(&me.id, &conn).await?),
430- Vec::new(),
431- )
432- }
433- LegacyRequest::Members { community_id } => {
434- let me = authenticated(client, &conn).await?;
435- allowed(&me, &community_id, &conn, permission::can_read).await?;
436- (
437- Response::Members(user_community::members(&community_id, &conn).await?),
438- Vec::new(),
439- )
440- }
441- LegacyRequest::Kick {
442- community_id,
443- user_id,
444- reason,
445- } => {
446- let me = authenticated(client, &conn).await?;
447- remove_member(
448- &me,
449- Removal {
450- community_id,
451- user_id,
452- reason,
453- sanction: Sanction::Kick,
454- },
455- rooms,
456- &mut conn,
457- )
458- .await?
459- }
460- LegacyRequest::Ban {
461- community_id,
462- user_id,
463- reason,
464- } => {
465- let me = authenticated(client, &conn).await?;
466- remove_member(
467- &me,
468- Removal {
469- community_id,
470- user_id,
471- reason,
472- sanction: Sanction::Ban,
473- },
474- rooms,
475- &mut conn,
476- )
477- .await?
478- }
479- LegacyRequest::Unban {
480- community_id,
481- user_id,
482- } => {
483- let me = authenticated(client, &conn).await?;
484- allowed(&me, &community_id, &conn, permission::can_unban).await?;
485- user_community::unban(&user_id, &community_id, &conn).await?;
486- log::record(
487- &community_id,
488- Some(&me.id),
489- Some(&user_id),
490- &LogAction::Unbanned,
491- &conn,
492- )
493- .await?;
494- (Response::Done, Vec::new())
495- }
496- LegacyRequest::Bans { community_id } => {
497- let me = authenticated(client, &conn).await?;
498- allowed(&me, &community_id, &conn, permission::can_unban).await?;
499- (
500- Response::Bans(user_community::bans(&community_id, &conn).await?),
501- Vec::new(),
502- )
503- }
504- LegacyRequest::SetRank {
505- community_id,
506- user_id,
507- rank,
508- } => {
509- let me = authenticated(client, &conn).await?;
510- ensure_editable(&community_id, &conn).await?;
511- let target = user::read(&user_id, &conn).await?;
512- ensure(permission::can_set_rank(
513- actor_rank(&me, &community_id, &conn).await?,
514- actor_rank(&target, &community_id, &conn).await?,
515- rank,
516- ))?;
517- user_community::set_rank(&user_id, &community_id, rank, &conn).await?;
518- log::record(
519- &community_id,
520- Some(&me.id),
521- Some(&user_id),
522- &LogAction::RankChanged { rank },
523- &conn,
524- )
525- .await?;
526- let event = Event::RankChanged {
527- community_id: community_id.clone(),
528- user_id,
529- rank,
530- };
531- (
532- Response::Done,
533- vec![Broadcast::new(To::Community(community_id), event)],
534- )
535- }
536- LegacyRequest::CreateMessage {
537- community_id,
538- body,
539- attachments,
540- reply_to,
541- } => {
542- let me = authenticated(client, &conn).await?;
543- let settings = server_settings::read(&conn).await?;
544- limit_messages(&me, rate_limit, &settings)?;
545- validate_new_message(
546- &body,
547- attachments.len(),
548- settings.max_message_length as usize,
549- )?;
550- allowed(&me, &community_id, &conn, permission::can_post).await?;
551- let tx = conn.transaction().await?;
552- let created = message::create(
553- &me.id,
554- &community_id,
555- &body,
556- &attachments,
557- reply_to.as_deref(),
558- &tx,
559- )
560- .await?;
561- stats::mark_active(&me.id, &tx).await?;
562- tx.commit().await?;
563- let broadcast = message_event(&created, Event::MessageCreated);
564- (Response::Message(created), vec![broadcast])
565- }
566- LegacyRequest::ForwardMessages {
567- message_ids,
568- community_id,
569- snippet,
570- } => {
571- let me = authenticated(client, &conn).await?;
572- limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?;
573- validate_forward(message_ids.len())?;
574- ensure(permission::can_post(
575- actor_rank(&me, &community_id, &conn).await?,
576- ))?;
577- let tx = conn.transaction().await?;
578- let mut sources = Vec::new();
579- for message_id in &message_ids {
580- let source = message::read(message_id, &tx).await?;
581- ensure(permission::can_read(
582- actor_rank(&me, &source.community_id, &tx).await?,
583- ))?;
584- sources.push(source);
585- }
586- let mode = if snippet {
587- message::ForwardMode::Snippet
588- } else {
589- message::ForwardMode::Copy
590- };
591- let created =
592- message::forward(&me, &community_id, &sources, mode, directory, &tx).await?;
593- tx.commit().await?;
594- let broadcasts = created
595- .iter()
596- .map(|message| message_event(message, Event::MessageCreated))
597- .collect();
598- (Response::Messages(created), broadcasts)
599- }
600- LegacyRequest::UpdateMessage { message_id, body } => {
601- let me = authenticated(client, &conn).await?;
602- let existing = message::read(&message_id, &conn).await?;
603- allowed(&me, &existing.community_id, &conn, permission::can_post).await?;
604- ensure(existing.user_id == me.id)?;
605- validate_new_message(
606- &body,
607- 0,
608- server_settings::read(&conn).await?.max_message_length as usize,
609- )?;
610- let updated = message::update(&message_id, &body, &conn).await?;
611- let broadcast = message_event(&updated, Event::MessageUpdated);
612- (Response::Message(updated), vec![broadcast])
613- }
614- LegacyRequest::CreatePoll {
615- community_id,
616- question,
617- options,
618- multiple,
619- } => {
620- let me = authenticated(client, &conn).await?;
621- let settings = server_settings::read(&conn).await?;
622- limit_messages(&me, rate_limit, &settings)?;
623- validate_poll(&question, &options)?;
624- allowed(&me, &community_id, &conn, permission::can_post).await?;
625- let tx = conn.transaction().await?;
626- let created =
627- message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx)
628- .await?;
629- stats::mark_active(&me.id, &tx).await?;
630- tx.commit().await?;
631- let broadcast = message_event(&created, Event::MessageCreated);
632- (Response::Message(created), vec![broadcast])
633- }
634- LegacyRequest::Vote {
635- message_id,
636- positions,
637- } => {
638- let me = authenticated(client, &conn).await?;
639- let existing = message::read(&message_id, &conn).await?;
640- ensure(permission::can_read(
641- actor_rank(&me, &existing.community_id, &conn).await?,
642- ))?;
643- let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?;
644- validate_vote(poll, &positions)?;
645- let updated = message::vote(&message_id, &me.id, &positions, &conn).await?;
646- let broadcast = message_event(&updated, Event::MessageUpdated);
647- (Response::Done, vec![broadcast])
648- }
649- LegacyRequest::ClosePoll { message_id } => {
650- let me = authenticated(client, &conn).await?;
651- let existing = message::read(&message_id, &conn).await?;
652- ensure(permission::can_close_poll(
653- actor_rank(&me, &existing.community_id, &conn).await?,
654- existing.user_id == me.id,
655- ))?;
656- let updated = message::close_poll(&message_id, &conn).await?;
657- let broadcast = message_event(&updated, Event::MessageUpdated);
658- (Response::Done, vec![broadcast])
659- }
660- LegacyRequest::React { message_id, emoji } => {
661- let me = authenticated(client, &conn).await?;
662- validate_reaction(&emoji)?;
663- let existing = message::read(&message_id, &conn).await?;
664- ensure(permission::can_read(
665- actor_rank(&me, &existing.community_id, &conn).await?,
666- ))?;
667- let updated = message::react(&message_id, &me.id, &emoji, &conn).await?;
668- let broadcast = message_event(&updated, Event::MessageUpdated);
669- (Response::Done, vec![broadcast])
670- }
671- LegacyRequest::Pin { message_id, pinned } => {
672- let me = authenticated(client, &conn).await?;
673- let existing = message::read(&message_id, &conn).await?;
674- let direct = community::is_direct(&existing.community_id, &conn).await?;
675- ensure(permission::can_pin(
676- actor_rank(&me, &existing.community_id, &conn).await?,
677- direct,
678- ))?;
679- let updated = message::pin(&message_id, pinned, &conn).await?;
680- let broadcast = message_event(&updated, Event::MessageUpdated);
681- (Response::Done, vec![broadcast])
682- }
683- LegacyRequest::Unreads => {
684- let me = authenticated(client, &conn).await?;
685- (
686- Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?),
687- Vec::new(),
688- )
689- }
690- LegacyRequest::MarkRead {
691- community_id,
692- message_id,
693- } => {
694- let me = authenticated(client, &conn).await?;
695- ensure(!is_outsider(&me.id, &community_id, &conn).await?)?;
696- message::ensure_in_community(&message_id, &community_id, &conn).await?;
697- user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?;
698- (Response::Done, Vec::new())
699- }
700- LegacyRequest::Pins { community_id } => {
701- let me = authenticated(client, &conn).await?;
702- allowed(&me, &community_id, &conn, permission::can_read).await?;
703- (
704- Response::Messages(message::pinned(&community_id, &conn).await?),
705- Vec::new(),
706- )
707- }
708- LegacyRequest::DeleteMessage { message_id } => {
709- let me = authenticated(client, &conn).await?;
710- let existing = message::read(&message_id, &conn).await?;
711- let author = user::read(&existing.user_id, &conn).await?;
712- ensure(permission::can_delete_message(
713- actor_rank(&me, &existing.community_id, &conn).await?,
714- actor_rank(&author, &existing.community_id, &conn).await?,
715- existing.user_id == me.id,
716- ))?;
717- let deleted = message::delete(&message_id, &conn).await?;
718- if existing.user_id != me.id {
719- log::record(
720- &deleted.community_id,
721- Some(&me.id),
722- Some(&existing.user_id),
723- &LogAction::MessageDeleted,
724- &conn,
725- )
726- .await?;
727- }
728- if permission::is_builder(me.role) && existing.user_id != me.id {
729- let community = community::label(&deleted.community_id, &conn).await?;
730- admin_log::record(
731- Some(&me.id),
732- Some(&existing.user_id),
733- Some(&community),
734- &AdminAction::MessageDeleted,
735- &conn,
736- )
737- .await?;
738- }
739- let event = Event::MessagesDeleted {
740- community_id: deleted.community_id.clone(),
741- ids: vec![deleted.id.clone()],
742- };
743- let broadcast = Broadcast::new(To::Community(deleted.community_id.clone()), event);
744- (Response::Message(deleted), vec![broadcast])
745- }
746- LegacyRequest::WatchCommunity { community_id } => {
747- let me = authenticated(client, &conn).await?;
748- let Some(community_id) = community_id else {
749- client.watch(None);
750- return Ok((Response::Done, Vec::new()));
751- };
752- allowed(&me, &community_id, &conn, permission::can_read).await?;
753- let outsider = is_outsider(&me.id, &community_id, &conn).await?;
754- client.watch(outsider.then_some(community_id.as_str()));
755- let visit = permission::is_builder(me.role)
756- && outsider
757- && user::is_ghost(&me.id, &conn).await?;
758- if visit && client.first_visit(&community_id) {
759- let community = community::label(&community_id, &conn).await?;
760- admin_log::record(
761- Some(&me.id),
762- None,
763- Some(&community),
764- &AdminAction::GhostVisit,
765- &conn,
766- )
767- .await?;
768- }
769- (Response::Done, Vec::new())
770- }
771- LegacyRequest::ReadMessages {
772- community_id,
773- before,
774- } => {
775- let me = authenticated(client, &conn).await?;
776- allowed(&me, &community_id, &conn, permission::can_read).await?;
777- let messages = message::read_page(&community_id, before.as_deref(), &conn).await?;
778- (Response::Messages(messages), Vec::new())
779- }
780- LegacyRequest::JoinVoice { community_id } => {
781- let me = authenticated(client, &conn).await?;
782- allowed(&me, &community_id, &conn, permission::can_join_voice).await?;
783- ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?;
784- ensure(
785- permission::is_builder(me.role)
786- || community::voice_enabled(&community_id, &conn).await?,
787- )?;
788- let muted = user::voice_muted(&me.id, &conn).await?;
789- let outsider = is_outsider(&me.id, &community_id, &conn).await?;
790- let ghost = outsider || user::is_ghost(&me.id, &conn).await?;
791- let starts_call = !ghost
792- && community::is_direct(&community_id, &conn).await?
793- && rooms.participants(&community_id).is_empty();
794- let joined = rooms.join(client, &community_id, muted, ghost)?;
795- let mut broadcasts = match joined.departure {
796- Some(departure) => departed(departure, &conn).await?,
797- None => Vec::new(),
798- };
799- if starts_call {
800- let created =
801- message::create_call_log(&community_id, &me.id, CallLog::Started, &conn)
802- .await?;
803- broadcasts.push(message_event(&created, Event::MessageCreated));
804- }
805- if !ghost && !joined.transferred {
806- broadcasts.extend(voice_joined(&community_id, &me.id, muted));
807- }
808- (
809- Response::Voice(rooms.participants(&community_id)),
810- broadcasts,
811- )
812- }
813- LegacyRequest::Typing { community_id } => {
814- let me = authenticated(client, &conn).await?;
815- allowed(&me, &community_id, &conn, permission::can_read).await?;
816- let broadcasts = if user::is_ghost(&me.id, &conn).await? {
817- Vec::new()
818- } else {
819- let others: Vec<String> = user_community::member_ids(&community_id, &conn)
820- .await?
821- .into_iter()
822- .filter(|user_id| *user_id != me.id)
823- .collect();
824- let event = Event::Typing {
825- community_id,
826- user_id: me.id.clone(),
827- };
828- vec![Broadcast::new(To::Users(others), event)]
829- };
830- (Response::Done, broadcasts)
831- }
832- LegacyRequest::LeaveVoice => {
833- authenticated(client, &conn).await?;
834- let broadcasts = match rooms.leave(client.id) {
835- Some(departure) => departed(departure, &conn).await?,
836- None => Vec::new(),
837- };
838- (Response::Done, broadcasts)
839- }
840- LegacyRequest::StartShare { kind, source } => {
841- let me = authenticated(client, &conn).await?;
842- let Some(community_id) = rooms.room_of_conn(client.id) else {
843- return Err(CommonError::NotFound.into());
844- };
845- allowed(&me, &community_id, &conn, permission::can_share).await?;
846- ensure(!source.encode.is_empty())?;
847- ensure(!user::is_ghost(&me.id, &conn).await?)?;
848- let event = Event::ShareStarted {
849- community_id: community_id.clone(),
850- share: Share {
851- user_id: me.id.clone(),
852- kind,
853- source: source.clone(),
854- },
855- };
856- let mut broadcasts = vec![Broadcast::new(To::Community(community_id.clone()), event)];
857- broadcasts.extend(
858- rooms
859- .start_share(client.id, kind, source)
860- .ok_or(CommonError::NotFound)?,
861- );
862-
863- (Response::Done, broadcasts)
864- }
865- LegacyRequest::StopShare { kind } => {
866- let me = authenticated(client, &conn).await?;
867- let broadcasts = match rooms.stop_share(client.id, kind) {
868- Some(community_id) => vec![share_ended(&community_id, &me.id, kind)],
869- None => Vec::new(),
870- };
871- (Response::Done, broadcasts)
872- }
873- LegacyRequest::Shares { community_id } => {
874- let me = authenticated(client, &conn).await?;
875- allowed(&me, &community_id, &conn, permission::can_read).await?;
876- (Response::Shares(rooms.shares(&community_id)), Vec::new())
877- }
878- LegacyRequest::WatchShare {
879- user_id,
880- kind,
881- quality,
882- decode,
883- } => {
884- authenticated(client, &conn).await?;
885- let broadcasts = rooms
886- .watch(client.id, &user_id, kind, quality, &decode)
887- .ok_or(CommonError::NotFound)?;
888-
889- (Response::Done, broadcasts)
890- }
891- LegacyRequest::UnwatchShare { user_id, kind } => {
892- authenticated(client, &conn).await?;
893-
894- (Response::Done, rooms.unwatch(client.id, &user_id, kind))
895- }
896- LegacyRequest::RequestKeyframe { user_id, kind } => {
897- authenticated(client, &conn).await?;
898- let keyframe = rooms
899- .keyframe(client.id, &user_id, kind)
900- .ok_or(CommonError::NotFound)?;
901-
902- (Response::Done, vec![keyframe])
903- }
904- LegacyRequest::DeclineCall { community_id } => {
905- let me = authenticated(client, &conn).await?;
906- ensure(community::is_direct(&community_id, &conn).await?)?;
907- allowed(&me, &community_id, &conn, permission::can_read).await?;
908- let participants = rooms.participants(&community_id);
909- ensure(!participants.is_empty() && !participants.contains(&me.id))?;
910- rooms.decline(&community_id);
911- let created =
912- message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?;
913- (
914- Response::Done,
915- vec![message_event(&created, Event::MessageCreated)],
916- )
917- }
918- LegacyRequest::VoiceParticipants { community_id } => {
919- let me = authenticated(client, &conn).await?;
920- allowed(&me, &community_id, &conn, permission::can_read).await?;
921- (
922- Response::Voice(rooms.participants(&community_id)),
923- Vec::new(),
924- )
925- }
926- LegacyRequest::FindUser { username } => {
927- let me = authenticated(client, &conn).await?;
928- let found = user::by_username(&username, &conn)
929- .await?
930- .filter(|found| found.id != me.id)
931- .ok_or(CommonError::NotFound)?;
932- (Response::User(found), Vec::new())
933- }
934- LegacyRequest::OpenDirect { user_id } => {
935- let me = authenticated(client, &conn).await?;
936- match direct::open(&me.id, &user_id, &mut conn).await? {
937- direct::Opening::Created(community) => {
938- let peer_view = community::read(&community.id, &user_id, &conn).await?;
939- (
940- Response::Community(community),
941- vec![Broadcast::new(
942- To::User(user_id),
943- Event::CommunityAdded(peer_view),
944- )],
945- )
946- }
947- direct::Opening::Existing(community) => {
948- (Response::Community(community), Vec::new())
949- }
950- }
951- }
952- LegacyRequest::OpenNotes => {
953- let me = authenticated(client, &conn).await?;
954- (
955- Response::Community(notes::open(&me.id, &mut conn).await?),
956- Vec::new(),
957- )
958- }
959- LegacyRequest::Friends => {
960- let me = authenticated(client, &conn).await?;
961- (
962- Response::Friends(friend::state(&me.id, &conn).await?),
963- Vec::new(),
964- )
965- }
966- LegacyRequest::AddFriend { user_id } => {
967- let me = authenticated(client, &conn).await?;
968- friend::add(&me.id, &user_id, &mut conn).await?;
969- let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
970- (Response::Done, broadcasts)
971- }
972- LegacyRequest::AcceptFriend { user_id } => {
973- let me = authenticated(client, &conn).await?;
974- friend::accept(&me.id, &user_id, &mut conn).await?;
975- let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
976- (Response::Done, broadcasts)
977- }
978- LegacyRequest::RemoveFriend { user_id } => {
979- let me = authenticated(client, &conn).await?;
980- friend::remove(&me.id, &user_id, &mut conn).await?;
981- let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
982- (Response::Done, broadcasts)
983- }
984- LegacyRequest::Invite {
985- community_id,
986- user_id,
987- } => {
988- let me = authenticated(client, &conn).await?;
989- ensure_editable(&community_id, &conn).await?;
990- allowed(&me, &community_id, &conn, permission::can_read).await?;
991- let target = user::read(&user_id, &conn).await?;
992- if user_community::rank(&user_id, &community_id, &conn)
993- .await?
994- .is_some()
995- {
996- return Err(CommonError::AlreadyMember.into());
997- }
998- let banned = user_community::is_banned(&user_id, &community_id, &conn).await?;
999- ensure(permission::can_join(target.role, banned))?;
1000- if invitation::exists(&community_id, &user_id, &conn).await? {
1001- return Err(CommonError::AlreadyInvited.into());
1002- }
1003- invitation::insert(&community_id, &user_id, &me.id, &conn).await?;
1004- log::record(
1005- &community_id,
1006- Some(&me.id),
1007- Some(&user_id),
1008- &LogAction::Invited,
1009- &conn,
1010- )
1011- .await?;
1012- let broadcast = invitations_updated(&user_id, &conn).await?;
1013- (Response::Done, vec![broadcast])
1014- }
1015- LegacyRequest::Invitations => {
1016- let me = authenticated(client, &conn).await?;
1017- (
1018- Response::Invitations(invitation::of(&me.id, &conn).await?),
1019- Vec::new(),
1020- )
1021- }
1022- LegacyRequest::AcceptInvitation { community_id } => {
1023- let me = authenticated(client, &conn).await?;
1024- let tx = conn.transaction().await?;
1025- invitation::take(&community_id, &me.id, &tx).await?;
1026- let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;
1027- ensure(permission::can_join(me.role, banned))?;
1028- user_community::join(&me.id, &community_id, Rank::Member, &tx).await?;
1029- log::record(&community_id, Some(&me.id), None, &LogAction::Joined, &tx).await?;
1030- let community = community::read(&community_id, &me.id, &tx).await?;
1031- tx.commit().await?;
1032- let event = Event::MemberJoined {
1033- community_id: community_id.clone(),
1034- member: Member {
1035- user: me.clone(),
1036- rank: Rank::Member,
1037- },
1038- };
1039- let mut broadcasts = vec![Broadcast::new(To::Community(community_id), event)];
1040- broadcasts.push(invitations_updated(&me.id, &conn).await?);
1041- (Response::Community(community), broadcasts)
1042- }
1043- LegacyRequest::DeclineInvitation { community_id } => {
1044- let me = authenticated(client, &conn).await?;
1045- invitation::take(&community_id, &me.id, &conn).await?;
1046- (
1047- Response::Done,
1048- vec![invitations_updated(&me.id, &conn).await?],
1049- )
1050- }
1051- LegacyRequest::Logs { community_id } => {
1052- let me = authenticated(client, &conn).await?;
1053- allowed(&me, &community_id, &conn, permission::can_read_logs).await?;
1054- (
1055- Response::Logs(log::list(&community_id, &conn).await?),
1056- Vec::new(),
1057- )
1058- }
1059- LegacyRequest::AllCommunities => {
1060- builder(client, &conn).await?;
1061- let mut summaries = Vec::new();
1062- for community in community::groups(&conn).await? {
1063- let members = user_community::members(&community.id, &conn).await?;
1064- let owner = members
1065- .iter()
1066- .find(|member| member.rank == Rank::Owner)
1067- .map(|member| member.user.clone());
1068- summaries.push(CommunitySummary {
1069- community,
1070- owner,
1071- members: members.len() as u64,
1072- });
1073- }
1074- (Response::AllCommunities(summaries), Vec::new())
1075- }
1076- LegacyRequest::TransferOwnership {
1077- community_id,
1078- user_id,
1079- } => {
1080- let me = authenticated(client, &conn).await?;
1081- ensure_editable(&community_id, &conn).await?;
1082- allowed(
1083- &me,
1084- &community_id,
1085- &conn,
1086- permission::can_transfer_ownership,
1087- )
1088- .await?;
1089- let tx = conn.transaction().await?;
1090- let members = user_community::members(&community_id, &tx).await?;
1091- let target = members
1092- .iter()
1093- .find(|member| member.user.id == user_id)
1094- .ok_or(CommonError::NotFound)?;
1095- ensure(target.rank != Rank::Owner)?;
1096- let mut changes = vec![(user_id.clone(), Rank::Owner)];
1097- if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) {
1098- user_community::set_rank(&previous.user.id, &community_id, Rank::Admin, &tx)
1099- .await?;
1100- log::record(
1101- &community_id,
1102- Some(&me.id),
1103- Some(&previous.user.id),
1104- &LogAction::RankChanged { rank: Rank::Admin },
1105- &tx,
1106- )
1107- .await?;
1108- changes.push((previous.user.id.clone(), Rank::Admin));
1109- }
1110- user_community::set_rank(&user_id, &community_id, Rank::Owner, &tx).await?;
1111- log::record(
1112- &community_id,
1113- Some(&me.id),
1114- Some(&user_id),
1115- &LogAction::RankChanged { rank: Rank::Owner },
1116- &tx,
1117- )
1118- .await?;
1119- if permission::is_builder(me.role) {
1120- let community = community::read(&community_id, &me.id, &tx).await?;
1121- admin_log::record(
1122- Some(&me.id),
1123- Some(&user_id),
1124- Some(&community.name),
1125- &AdminAction::OwnershipTransferred,
1126- &tx,
1127- )
1128- .await?;
1129- }
1130- tx.commit().await?;
1131- let mut broadcasts = Vec::new();
1132- for (changed_id, rank) in changes {
1133- let event = Event::RankChanged {
1134- community_id: community_id.clone(),
1135- user_id: changed_id,
1136- rank,
1137- };
1138- broadcasts.push(Broadcast::new(To::Community(community_id.clone()), event));
1139- }
1140- (Response::Done, broadcasts)
1141- }
1142- LegacyRequest::TimeoutUser { user_id, minutes } => {
1143- let me = authenticated(client, &conn).await?;
1144- managed(&me, &user_id, &conn).await?;
1145- let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);
1146- user::set_timeout(&user_id, until, &conn).await?;
1147- if until.is_some() {
1148- authentication::revoke(hub, authentication::Revoke::User(&user_id), &conn).await?;
1149- }
1150- admin_log::record(
1151- Some(&me.id),
1152- Some(&user_id),
1153- None,
1154- &AdminAction::UserTimedOut { minutes },
1155- &conn,
1156- )
1157- .await?;
1158- (Response::Done, Vec::new())
1159- }
1160- LegacyRequest::BanUser {
1161- user_id,
1162- reason,
1163- scope,
1164- } => {
1165- let me = authenticated(client, &conn).await?;
1166- let target = managed(&me, &user_id, &conn).await?;
1167- validate_reason(reason.as_deref())?;
1168- let tx = conn.transaction().await?;
1169- user::set_suspended(&user_id, true, &tx).await?;
1170- authentication::revoke_sessions(&user_id, &tx).await?;
1171- server_ban::insert(
1172- ServerBanKind::Username,
1173- &target.username.to_ascii_lowercase(),
1174- reason.as_deref(),
1175- &me.id,
1176- &tx,
1177- )
1178- .await?;
1179- if scope == BanScope::AccountAndIp
1180- && let Some(address) = user::last_ip(&user_id, &tx).await?
1181- {
1182- server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx)
1183- .await?;
1184- }
1185- admin_log::record(
1186- Some(&me.id),
1187- Some(&user_id),
1188- None,
1189- &AdminAction::UserBanned { reason },
1190- &tx,
1191- )
1192- .await?;
1193- tx.commit().await?;
1194- hub.kick_user(&user_id, Close::Banned);
1195- (Response::Done, Vec::new())
1196- }
1197- LegacyRequest::ServerBans => {
1198- builder(client, &conn).await?;
1199- (
1200- Response::ServerBans(server_ban::list(&conn).await?),
1201- Vec::new(),
1202- )
1203- }
1204- LegacyRequest::RemoveServerBan { id } => {
1205- let me = builder(client, &conn).await?;
1206- server_ban::remove(&id, &conn).await?;
1207- admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?;
1208- (Response::Done, Vec::new())
1209- }
1210- LegacyRequest::CreateInviteCode { uses, hours } => {
1211- let me = authenticated(client, &conn).await?;
1212- ensure(permission::is_builder(me.role) && uses > 0)?;
1213- let code = invite::create(uses, hours, &me, &conn).await?;
1214- admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?;
1215- (Response::InviteCode(code), Vec::new())
1216- }
1217- LegacyRequest::InviteCodes => {
1218- builder(client, &conn).await?;
1219- (
1220- Response::InviteCodes(invite::list(&conn).await?),
1221- Vec::new(),
1222- )
1223- }
1224- LegacyRequest::DeleteInviteCode { code } => {
1225- let me = builder(client, &conn).await?;
1226- invite::delete(&code, &conn).await?;
1227- admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?;
1228- (Response::Done, Vec::new())
1229- }
1230- LegacyRequest::ReportMessage { message_id, reason } => {
1231- let me = authenticated(client, &conn).await?;
1232- let message = message::read(&message_id, &conn).await?;
1233- let actor = actor_rank(&me, &message.community_id, &conn).await?;
1234- ensure(permission::can_read(actor) && me.id != message.user_id)?;
1235- validate_reason(Some(&reason))?;
1236- ensure_with(
1237- !report::is_open(&me.id, &message.user_id, Some(&message_id), &conn).await?,
1238- CommonError::Taken,
1239- )?;
1240- report::insert(
1241- &me.id,
1242- &message.user_id,
1243- Some(&message_id),
1244- Some(&message.community_id),
1245- Some(&message.body),
1246- &reason,
1247- &conn,
1248- )
1249- .await?;
1250- (Response::Done, vec![report_created()])
1251- }
1252- LegacyRequest::ReportUser { user_id, reason } => {
1253- let me = authenticated(client, &conn).await?;
1254- user::read(&user_id, &conn).await?;
1255- ensure(me.id != user_id)?;
1256- validate_reason(Some(&reason))?;
1257- ensure_with(
1258- !report::is_open(&me.id, &user_id, None, &conn).await?,
1259- CommonError::Taken,
1260- )?;
1261- report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?;
1262- (Response::Done, vec![report_created()])
1263- }
1264- LegacyRequest::Reports { status } => {
1265- builder(client, &conn).await?;
1266- (
1267- Response::Reports(report::list(status, &conn).await?),
1268- Vec::new(),
1269- )
1270- }
1271- LegacyRequest::HandleReport { report_id, status } => {
1272- let me = authenticated(client, &conn).await?;
1273- ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?;
1274- let target = report::handle(&report_id, status, &me.id, &conn).await?;
1275- admin_log::record(
1276- Some(&me.id),
1277- target.as_deref(),
1278- None,
1279- &AdminAction::ReportHandled { status },
1280- &conn,
1281- )
1282- .await?;
1283- (Response::Done, Vec::new())
1284- }
1285- LegacyRequest::SearchMessages {
1286- text,
1287- user_id,
1288- community_id,
1289- after_ms,
1290- before_ms,
1291- } => {
1292- builder(client, &conn).await?;
1293- let hits = message::search(
1294- text.as_deref(),
1295- user_id.as_deref(),
1296- community_id.as_deref(),
1297- after_ms,
1298- before_ms,
1299- &conn,
1300- )
1301- .await?;
1302- (Response::MessageHits(hits), Vec::new())
1303- }
1304- LegacyRequest::SearchCommunity { community_id, text } => {
1305- let me = authenticated(client, &conn).await?;
1306- allowed(&me, &community_id, &conn, permission::can_read).await?;
1307- let hits =
1308- message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?;
1309- (Response::MessageHits(hits), Vec::new())
1310- }
1311- LegacyRequest::PurgeUser { user_id } => {
1312- let me = authenticated(client, &conn).await?;
1313- managed(&me, &user_id, &conn).await?;
1314- let tx = conn.transaction().await?;
1315- let upload_ids = attachment::uploads_of(&user_id, &tx).await?;
1316- let message_ids = message::ids_of_user(&user_id, &tx).await?;
1317- let mut deleted: BTreeMap<String, Vec<String>> = BTreeMap::new();
1318- for message_id in &message_ids {
1319- let message = message::delete(message_id, &tx).await?;
1320- deleted
1321- .entry(message.community_id)
1322- .or_default()
1323- .push(message.id);
1324- }
1325- let broadcasts = deleted
1326- .into_iter()
1327- .map(|(community_id, ids)| {
1328- let event = Event::MessagesDeleted {
1329- community_id: community_id.clone(),
1330- ids,
1331- };
1332- Broadcast::new(To::Community(community_id), event)
1333- })
1334- .collect();
1335- attachment::delete_uploads(&user_id, &tx).await?;
1336- admin_log::record(
1337- Some(&me.id),
1338- Some(&user_id),
1339- None,
1340- &AdminAction::UserPurged {
1341- messages: message_ids.len() as u64,
1342- },
1343- &tx,
1344- )
1345- .await?;
1346- tx.commit().await?;
1347- attachment::remove_files(&upload_ids, directory);
1348- (Response::Done, broadcasts)
1349- }
1350- LegacyRequest::AllAttachments {
1351- user_id,
1352- community_id,
1353- } => {
1354- builder(client, &conn).await?;
1355- (
1356- Response::AttachmentInfos(
1357- attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?,
1358- ),
1359- Vec::new(),
1360- )
1361- }
1362- LegacyRequest::DeleteAttachment { attachment_id } => {
1363- let me = builder(client, &conn).await?;
1364- let stored = attachment::read(&attachment_id, &conn).await?;
1365- let community = community::label(&stored.community_id, &conn).await?;
1366- let tx = conn.transaction().await?;
1367- attachment::delete(&attachment_id, &tx).await?;
1368- admin_log::record(
1369- Some(&me.id),
1370- Some(&stored.uploader_id),
1371- Some(&community),
1372- &AdminAction::AttachmentDeleted,
1373- &tx,
1374- )
1375- .await?;
1376- let mut broadcasts = Vec::new();
1377- if let Some(message_id) = &stored.message_id {
1378- let updated = message::read(message_id, &tx).await?;
1379- broadcasts = vec![message_event(&updated, Event::MessageUpdated)];
1380- }
1381- tx.commit().await?;
1382- attachment::remove_files(&[attachment_id], directory);
1383- (Response::Done, broadcasts)
1384- }
1385- LegacyRequest::StorageUsage => {
1386- builder(client, &conn).await?;
1387- let (users, communities) = attachment::usage(&conn).await?;
1388- (Response::StorageUsage { users, communities }, Vec::new())
1389- }
1390- LegacyRequest::CreateBackup => {
1391- let me = builder(client, &conn).await?;
1392- let backup = backup::create(&conn, backups).await?;
1393- let action = AdminAction::BackupCreated {
1394- name: backup.name.clone(),
1395- };
1396- admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1397- (Response::Backup(backup), Vec::new())
1398- }
1399- LegacyRequest::Backups => {
1400- builder(client, &conn).await?;
1401- (Response::Backups(backup::list(backups)?), Vec::new())
1402- }
1403- LegacyRequest::DeleteBackup { name } => {
1404- let me = builder(client, &conn).await?;
1405- backup::delete(&name, backups)?;
1406- let action = AdminAction::BackupDeleted { name };
1407- admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1408- (Response::Done, Vec::new())
1409- }
1410- LegacyRequest::VoiceRooms => {
1411- builder(client, &conn).await?;
1412- (
1413- Response::VoiceRooms(voice_rooms(rooms, &conn).await?),
1414- Vec::new(),
1415- )
1416- }
1417- LegacyRequest::KickFromVoice { user_id } => {
1418- let me = authenticated(client, &conn).await?;
1419- managed(&me, &user_id, &conn).await?;
1420- let broadcasts = leave_user_voice(rooms, &user_id, &conn).await?;
1421- if !broadcasts.is_empty() {
1422- admin_log::record(
1423- Some(&me.id),
1424- Some(&user_id),
1425- None,
1426- &AdminAction::VoiceKicked,
1427- &conn,
1428- )
1429- .await?;
1430- }
1431- (Response::Done, broadcasts)
1432- }
1433- LegacyRequest::ServerMute { user_id, muted } => {
1434- let me = authenticated(client, &conn).await?;
1435- managed(&me, &user_id, &conn).await?;
1436- user::set_voice_muted(&user_id, muted, &conn).await?;
1437- admin_log::record(
1438- Some(&me.id),
1439- Some(&user_id),
1440- None,
1441- &AdminAction::VoiceMuted { muted },
1442- &conn,
1443- )
1444- .await?;
1445- let community_id = rooms.set_muted(&user_id, muted);
1446- let broadcast = voice_muted(community_id, &user_id, muted, &conn).await?;
1447- (Response::Done, vec![broadcast])
1448- }
1449- LegacyRequest::SetCommunityVoice {
1450- community_id,
1451- enabled,
1452- } => {
1453- let me = authenticated(client, &conn).await?;
1454- allowed(&me, &community_id, &conn, permission::can_manage_voice).await?;
1455- let tx = conn.transaction().await?;
1456- community::set_voice_enabled(&community_id, enabled, &tx).await?;
1457- let updated = community::read(&community_id, &me.id, &tx).await?;
1458- if permission::is_builder(me.role) {
1459- admin_log::record(
1460- Some(&me.id),
1461- None,
1462- Some(&updated.name),
1463- &AdminAction::CommunityVoiceSet { enabled },
1464- &tx,
1465- )
1466- .await?;
1467- }
1468- tx.commit().await?;
1469- let mut broadcasts = Vec::new();
1470- if !enabled {
1471- broadcasts.extend(voice_silenced(rooms, &community_id, &conn).await?);
1472- }
1473- let event = Event::CommunityUpdated(updated.clone());
1474- broadcasts.push(Broadcast::new(To::Community(community_id), event));
1475-
1476- (Response::Community(updated), broadcasts)
1477- }
1478- LegacyRequest::SetGhost { enabled } => {
1479- let me = builder(client, &conn).await?;
1480- user::set_ghost(&me.id, enabled, &conn).await?;
1481- let action = if enabled {
1482- AdminAction::GhostEnabled
1483- } else {
1484- AdminAction::GhostDisabled
1485- };
1486- admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1487- let mut broadcasts = Vec::new();
1488- let outsider = match rooms.room_of(&me.id) {
1489- Some(community_id) => is_outsider(&me.id, &community_id, &conn).await?,
1490- None => false,
1491- };
1492- if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) {
1493- let community_id = departure.community_id.clone();
1494- if enabled {
1495- broadcasts.extend(shares_ended(&mut departure));
1496- broadcasts.extend(
1497- call_ended(&community_id, &me.id, departure.call_log, &conn).await?,
1498- );
1499- let event = Event::VoiceLeft {
1500- community_id: community_id.clone(),
1501- user_id: me.id.clone(),
1502- };
1503- broadcasts.push(Broadcast::new(
1504- To::CommunityExcept(community_id, me.id.clone()),
1505- event,
1506- ));
1507- } else {
1508- let muted = user::voice_muted(&me.id, &conn).await?;
1509- broadcasts.extend(voice_joined(&community_id, &me.id, muted));
1510- if let Some(seconds) = departure.ghost_seconds {
1511- record_ghost_voice(&me.id, &community_id, seconds, &conn).await?;
1512- }
1513- }
1514- }
1515- (Response::Done, broadcasts)
1516- }
1517- };
1518-
1519- Ok(outcome)
1520-}
1521-
1522-async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result<Vec<VoiceRoom>, ServerError> {
1523 let mut rooms = Vec::new();25 let mut rooms = Vec::new();
1524 for (community_id, user_ids, ghosts) in occupied.list() {26 for (community_id, user_ids, ghosts) in occupied.list() {
1525 let community = community::label(&community_id, conn).await?;27 let community = community::label(&community_id, conn).await?;
@@ -1545,15 +47,11 @@ async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result<Vec<VoiceRoo
1545 Ok(rooms)47 Ok(rooms)
1546 }48 }
1547 49
1548-fn report_created() -> Broadcast {
1549- Broadcast::new(To::Builders, Event::ReportCreated)
1550-}
1551-
1552 fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> {50 fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> {
1553 connection.map(|connection| connection.remote_address().ip().to_string())51 connection.map(|connection| connection.remote_address().ip().to_string())
1554 }52 }
1555 53
1556-async fn limit_logins(54+pub(crate) async fn limit_logins(
1557 rate_limit: &RateLimit,55 rate_limit: &RateLimit,
1558 connection: Option<&quinn::Connection>,56 connection: Option<&quinn::Connection>,
1559 conn: &Connection,57 conn: &Connection,
@@ -1563,18 +61,6 @@ async fn limit_logins(
1563 Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?)61 Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?)
1564 }62 }
1565 63
1566-fn limit_messages(
1567- me: &User,
1568- rate_limit: &RateLimit,
1569- settings: &ServerSettings,
1570-) -> Result<(), ServerError> {
1571- if permission::is_builder(me.role) {
1572- return Ok(());
1573- }
1574-
1575- Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?)
1576-}
1577-
1578 pub(crate) async fn record_address(64 pub(crate) async fn record_address(
1579 user: &User,65 user: &User,
1580 connection: Option<&quinn::Connection>,66 connection: Option<&quinn::Connection>,
@@ -1587,65 +73,6 @@ pub(crate) async fn record_address(
1587 Ok(())73 Ok(())
1588 }74 }
1589 75
1590-struct Removal {
1591- community_id: String,
1592- user_id: String,
1593- reason: Option<String>,
1594- sanction: Sanction,
1595-}
1596-
1597-async fn remove_member(
1598- me: &User,
1599- removal: Removal,
1600- rooms: &Rooms,
1601- conn: &mut Connection,
1602-) -> Result<Outcome, ServerError> {
1603- let Removal {
1604- community_id,
1605- user_id,
1606- reason,
1607- sanction,
1608- } = removal;
1609- validate_reason(reason.as_deref())?;
1610- ensure_editable(&community_id, conn).await?;
1611- let target = user::read(&user_id, conn).await?;
1612- ensure(permission::can_moderate(
1613- actor_rank(me, &community_id, conn).await?,
1614- actor_rank(&target, &community_id, conn).await?,
1615- ))?;
1616- let community = community::read(&community_id, &me.id, conn).await?;
1617- let tx = conn.transaction().await?;
1618- user_community::leave(&user_id, &community_id, &tx).await?;
1619- let action = match sanction {
1620- Sanction::Ban => {
1621- user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?;
1622- LogAction::Banned {
1623- reason: reason.clone(),
1624- }
1625- }
1626- Sanction::Kick => LogAction::Kicked {
1627- reason: reason.clone(),
1628- },
1629- };
1630- log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;
1631- tx.commit().await?;
1632- let mut broadcasts = leave_room_voice(rooms, &community_id, &user_id, conn).await?;
1633- let removed = Event::Removed {
1634- community_id: community_id.clone(),
1635- community_name: community.name,
1636- sanction,
1637- reason,
1638- };
1639- broadcasts.push(Broadcast::new(To::User(user_id.clone()), removed));
1640- let event = Event::MemberLeft {
1641- community_id: community_id.clone(),
1642- user_id,
1643- };
1644- broadcasts.push(Broadcast::new(To::Community(community_id), event));
1645-
1646- Ok((Response::Done, broadcasts))
1647-}
1648-
1649 pub(crate) fn user_updated(user: &User) -> Vec<Broadcast> {76 pub(crate) fn user_updated(user: &User) -> Vec<Broadcast> {
1650 vec![Broadcast::new(77 vec![Broadcast::new(
1651 To::Related(user.id.clone()),78 To::Related(user.id.clone()),
@@ -1683,26 +110,7 @@ pub async fn presence_changed(
1683 )])110 )])
1684 }111 }
1685 112
1686-async fn friends_updated(113+pub(crate) async fn leave_user_voice(
1687- user_ids: &[&str],
1688- conn: &Connection,
1689-) -> Result<Vec<Broadcast>, ServerError> {
1690- let mut broadcasts = Vec::new();
1691- for user_id in user_ids {
1692- let event = Event::FriendsUpdated(friend::state(user_id, conn).await?);
1693- broadcasts.push(Broadcast::new(To::User(user_id.to_string()), event));
1694- }
1695-
1696- Ok(broadcasts)
1697-}
1698-
1699-async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadcast, ServerError> {
1700- let event = Event::InvitationsUpdated(invitation::of(user_id, conn).await?);
1701-
1702- Ok(Broadcast::new(To::User(user_id.to_string()), event))
1703-}
1704-
1705-async fn leave_user_voice(
1706 rooms: &Rooms,114 rooms: &Rooms,
1707 user_id: &str,115 user_id: &str,
1708 conn: &Connection,116 conn: &Connection,
@@ -1713,7 +121,7 @@ async fn leave_user_voice(
1713 }121 }
1714 }122 }
1715 123
1716-async fn leave_room_voice(124+pub(crate) async fn leave_room_voice(
1717 rooms: &Rooms,125 rooms: &Rooms,
1718 community_id: &str,126 community_id: &str,
1719 user_id: &str,127 user_id: &str,
@@ -1725,7 +133,7 @@ async fn leave_room_voice(
1725 }133 }
1726 }134 }
1727 135
1728-async fn voice_unmuted(136+pub(crate) async fn voice_unmuted(
1729 rooms: &Rooms,137 rooms: &Rooms,
1730 user_id: &str,138 user_id: &str,
1731 conn: &Connection,139 conn: &Connection,
@@ -1739,7 +147,7 @@ async fn voice_unmuted(
1739 ])147 ])
1740 }148 }
1741 149
1742-async fn voice_muted(150+pub(crate) async fn voice_muted(
1743 community_id: Option<String>,151 community_id: Option<String>,
1744 user_id: &str,152 user_id: &str,
1745 muted: bool,153 muted: bool,
@@ -1760,7 +168,7 @@ async fn voice_muted(
1760 Ok(Broadcast::new(To::Users(user_ids), event))168 Ok(Broadcast::new(To::Users(user_ids), event))
1761 }169 }
1762 170
1763-async fn voice_silenced(171+pub(crate) async fn voice_silenced(
1764 rooms: &Rooms,172 rooms: &Rooms,
1765 community_id: &str,173 community_id: &str,
1766 conn: &Connection,174 conn: &Connection,
@@ -1776,7 +184,7 @@ async fn voice_silenced(
1776 Ok(broadcasts)184 Ok(broadcasts)
1777 }185 }
1778 186
1779-async fn voice_closed(187+pub(crate) async fn voice_closed(
1780 rooms: &Rooms,188 rooms: &Rooms,
1781 community_id: &str,189 community_id: &str,
1782 conn: &Connection,190 conn: &Connection,
@@ -1789,7 +197,7 @@ async fn voice_closed(
1789 Ok(broadcasts)197 Ok(broadcasts)
1790 }198 }
1791 199
1792-async fn call_ended(200+pub(crate) async fn call_ended(
1793 community_id: &str,201 community_id: &str,
1794 user_id: &str,202 user_id: &str,
1795 call: Option<CallLog>,203 call: Option<CallLog>,
@@ -1836,7 +244,7 @@ pub async fn departed(
1836 Ok(broadcasts)244 Ok(broadcasts)
1837 }245 }
1838 246
1839-fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast {247+pub(crate) fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast {
1840 let event = Event::ShareStopped {248 let event = Event::ShareStopped {
1841 community_id: community_id.to_string(),249 community_id: community_id.to_string(),
1842 user_id: user_id.to_string(),250 user_id: user_id.to_string(),
@@ -1846,7 +254,7 @@ fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast {
1846 Broadcast::new(To::Community(community_id.to_string()), event)254 Broadcast::new(To::Community(community_id.to_string()), event)
1847 }255 }
1848 256
1849-fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> {257+pub(crate) fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> {
1850 let mut broadcasts: Vec<Broadcast> = departure258 let mut broadcasts: Vec<Broadcast> = departure
1851 .shares259 .shares
1852 .iter()260 .iter()
@@ -1907,7 +315,7 @@ pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError>
1907 Ok(())315 Ok(())
1908 }316 }
1909 317
1910-async fn allowed(318+pub(crate) async fn allowed(
1911 me: &User,319 me: &User,
1912 community_id: &str,320 community_id: &str,
1913 conn: &Connection,321 conn: &Connection,
@@ -1916,7 +324,7 @@ async fn allowed(
1916 ensure(check(actor_rank(me, community_id, conn).await?))324 ensure(check(actor_rank(me, community_id, conn).await?))
1917 }325 }
1918 326
1919-async fn is_outsider(327+pub(crate) async fn is_outsider(
1920 user_id: &str,328 user_id: &str,
1921 community_id: &str,329 community_id: &str,
1922 conn: &Connection,330 conn: &Connection,
@@ -1926,18 +334,21 @@ async fn is_outsider(
1926 .is_none())334 .is_none())
1927 }335 }
1928 336
1929-async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), ServerError> {337+pub(crate) async fn ensure_editable(
338+ community_id: &str,
339+ conn: &Connection,
340+) -> Result<(), ServerError> {
1930 ensure(!community::is_fixed(community_id, conn).await?)341 ensure(!community::is_fixed(community_id, conn).await?)
1931 }342 }
1932 343
1933-fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {344+pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {
1934 Broadcast::new(345 Broadcast::new(
1935 To::Community(message.community_id.clone()),346 To::Community(message.community_id.clone()),
1936 event(message.clone()),347 event(message.clone()),
1937 )348 )
1938 }349 }
1939 350
1940-fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec<Broadcast> {351+pub(crate) fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec<Broadcast> {
1941 let to = || To::Community(community_id.to_string());352 let to = || To::Community(community_id.to_string());
1942 let mut broadcasts = vec![Broadcast::new(353 let mut broadcasts = vec![Broadcast::new(
1943 to(),354 to(),
@@ -1960,7 +371,7 @@ fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec<Broadcast
1960 broadcasts371 broadcasts
1961 }372 }
1962 373
1963-async fn record_ghost_voice(374+pub(crate) async fn record_ghost_voice(
1964 user_id: &str,375 user_id: &str,
1965 community_id: &str,376 community_id: &str,
1966 seconds: u64,377 seconds: u64,
@@ -1983,79 +394,78 @@ async fn record_ghost_voice(
1983 mod tests {394 mod tests {
1984 use std::sync::Arc;395 use std::sync::Arc;
1985 396
1986- use common::{error::Error as CommonError, request::LegacyRequest, response::Response};397+ use common::{
398+ call::{
399+ AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage,
400+ DeleteCommunity, FindUser, Invite, ListCommunities, ListFriends, Register,
401+ UpdateCommunity,
402+ },
403+ error::Error as CommonError,
404+ };
1987 405
1988 use crate::{406 use crate::{
407+ call::{Cx, Handle, Me},
1989 database::{self, DB},408 database::{self, DB},
1990 hub::{Client, Signed},409 hub::{Client, Signed},
1991 message,410 message,
1992- network::Services,411+ network::{Services, Shared},
1993- request::handle,412+ request::authenticated,
1994 test,413 test,
1995 };414 };
1996 415
1997- async fn send(416+ fn shared(db: &DB, services: &Services) -> Shared {
1998- request: LegacyRequest,417+ Shared {
1999- client: &Client,418+ db: db.clone(),
2000- db: &DB,419+ services: services.clone(),
2001- services: &Services,420+ directory: test::directory(),
2002- ) -> Response {421+ backups: test::directory(),
2003- send_result(request, client, db, services)422+ }
2004- .await
2005- .expect("request failed")
2006 }423 }
2007 424
2008- async fn send_result(425+ async fn call<C: Handle>(
2009- request: LegacyRequest,426+ call: C,
2010- client: &Client,427+ client: &Arc<Client>,
2011 db: &DB,428 db: &DB,
2012 services: &Services,429 services: &Services,
2013- ) -> Result<Response, CommonError> {430+ ) -> Result<C::Reply, CommonError> {
2014- handle(431+ let shared = shared(db, services);
2015- request,432+ let conn = database::connect(db).await.unwrap();
2016- client,433+ let me = authenticated(client, &conn).await?;
2017- db,434+ let mut cx = Cx::new(client, &shared, conn);
2018- services,435+
2019- &test::directory(),436+ Ok(call.handle(Me::User(me), &mut cx).await?)
2020- &test::directory(),
2021- )
2022- .await
2023- .0
2024 }437 }
2025 438
2026 async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc<Client> {439 async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc<Client> {
2027 let guest = Client::detached(None);440 let guest = Client::detached(None);
2028- let Response::Session { user, token } = send(441+ let shared = shared(db, services);
2029- LegacyRequest::Register {442+ let conn = database::connect(db).await.unwrap();
2030- username: username.to_string(),443+ let mut cx = Cx::new(&guest, &shared, conn);
2031- password: "password".to_string(),444+ let session = Register {
2032- invite: None,445+ username: username.to_string(),
2033- },446+ password: "password".to_string(),
2034- &guest,447+ invite: None,
2035- db,448+ }
2036- services,449+ .handle(Me::Guest, &mut cx)
2037- )
2038 .await450 .await
2039- else {451+ .unwrap();
2040- panic!("register failed");
2041- };
2042 452
2043 Client::detached(Some(Signed {453 Client::detached(Some(Signed {
2044- user_id: user.id,454+ user_id: session.user.id,
2045- token,455+ token: session.token,
2046 }))456 }))
2047 }457 }
2048 458
2049 async fn invite_and_accept(459 async fn invite_and_accept(
2050 community_id: &str,460 community_id: &str,
2051- owner: &Client,461+ owner: &Arc<Client>,
2052- member: &Client,462+ member: &Arc<Client>,
2053 username: &str,463 username: &str,
2054 db: &DB,464 db: &DB,
2055 services: &Services,465 services: &Services,
2056 ) {466 ) {
2057- let Response::User(member_user) = send(467+ let member_user = call(
2058- LegacyRequest::FindUser {468+ FindUser {
2059 username: username.to_string(),469 username: username.to_string(),
2060 },470 },
2061 owner,471 owner,
@@ -2063,11 +473,9 @@ mod tests {
2063 services,473 services,
2064 )474 )
2065 .await475 .await
2066- else {476+ .unwrap();
2067- panic!("user not found");477+ call(
2068- };478+ Invite {
2069- send(
2070- LegacyRequest::Invite {
2071 community_id: community_id.to_string(),479 community_id: community_id.to_string(),
2072 user_id: member_user.id,480 user_id: member_user.id,
2073 },481 },
@@ -2075,16 +483,18 @@ mod tests {
2075 db,483 db,
2076 services,484 services,
2077 )485 )
2078- .await;486+ .await
2079- send(487+ .unwrap();
2080- LegacyRequest::AcceptInvitation {488+ call(
489+ AcceptInvitation {
2081 community_id: community_id.to_string(),490 community_id: community_id.to_string(),
2082 },491 },
2083 member,492 member,
2084 db,493 db,
2085 services,494 services,
2086 )495 )
2087- .await;496+ .await
497+ .unwrap();
2088 }498 }
2089 499
2090 #[tokio::test]500 #[tokio::test]
@@ -2093,8 +503,8 @@ mod tests {
2093 let services = Services::default();503 let services = Services::default();
2094 let owner = signed_in("Owner", &db, &services).await;504 let owner = signed_in("Owner", &db, &services).await;
2095 let member = signed_in("Member", &db, &services).await;505 let member = signed_in("Member", &db, &services).await;
2096- let Response::Community(community) = send(506+ let community = call(
2097- LegacyRequest::CreateCommunity {507+ CreateCommunity {
2098 name: "The Community".to_string(),508 name: "The Community".to_string(),
2099 },509 },
2100 &owner,510 &owner,
@@ -2102,13 +512,11 @@ mod tests {
2102 &services,512 &services,
2103 )513 )
2104 .await514 .await
2105- else {515+ .unwrap();
2106- panic!("community not created");
2107- };
2108 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;516 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
2109 517
2110- let response = send_result(518+ let response = call(
2111- LegacyRequest::UpdateCommunity {519+ UpdateCommunity {
2112 community_id: community.id,520 community_id: community.id,
2113 name: "Renamed".to_string(),521 name: "Renamed".to_string(),
2114 },522 },
@@ -2127,8 +535,8 @@ mod tests {
2127 let services = Services::default();535 let services = Services::default();
2128 let first = signed_in("First", &db, &services).await;536 let first = signed_in("First", &db, &services).await;
2129 let second = signed_in("Second", &db, &services).await;537 let second = signed_in("Second", &db, &services).await;
2130- let Response::User(first_user) = send(538+ let first_user = call(
2131- LegacyRequest::FindUser {539+ FindUser {
2132 username: "First".to_string(),540 username: "First".to_string(),
2133 },541 },
2134 &second,542 &second,
@@ -2136,11 +544,9 @@ mod tests {
2136 &services,544 &services,
2137 )545 )
2138 .await546 .await
2139- else {547+ .unwrap();
2140- panic!("user not found");548+ let second_user = call(
2141- };549+ FindUser {
2142- let Response::User(second_user) = send(
2143- LegacyRequest::FindUser {
2144 username: "Second".to_string(),550 username: "Second".to_string(),
2145 },551 },
2146 &first,552 &first,
@@ -2148,38 +554,30 @@ mod tests {
2148 &services,554 &services,
2149 )555 )
2150 .await556 .await
2151- else {557+ .unwrap();
2152- panic!("user not found");558+ call(
2153- };559+ AddFriend {
2154- send(
2155- LegacyRequest::AddFriend {
2156 user_id: second_user.id.clone(),560 user_id: second_user.id.clone(),
2157 },561 },
2158 &first,562 &first,
2159 &db,563 &db,
2160 &services,564 &services,
2161 )565 )
2162- .await;
2163- send(