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 @@
11 use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration};
22
33 use common::{
4- call::{Call, Legacy},
4+ call::Call,
55 constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES},
66 error::Error,
77 frame::{self, DOWN_MAX, Sending, UP_MAX},
88 model::{Attachment, User},
99 open::{Blob, Open, Upload},
10- request::LegacyRequest,
11- response::Response,
1210 session::{Hello, Welcome},
1311 transport::{Close, alpn, transport},
1412 validate::{validate_attachment_name, validate_attachment_size},
@@ -265,13 +263,6 @@ pub(super) async fn call<C: Call>(
265263 Ok(frame::read::<Result<C::Reply, Error>>(&mut receive_stream, DOWN_MAX).await??)
266264 }
267265
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-
275266 async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> {
276267 let (send_stream, mut receive_stream) = connection.open_bi().await?;
277268 let mut send_stream = Sending::new(send_stream);
@@ -285,16 +276,6 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<
285276 Ok(frame::read::<Result<Welcome, Error>>(&mut receive_stream, DOWN_MAX).await??)
286277 }
287278
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-
298279 pub(super) async fn send_body(
299280 send_stream: &mut quinn::SendStream,
300281 file: &mut tokio::fs::File,
crates/client/src/net/media.rsmodified+40 -38
@@ -6,10 +6,12 @@ use std::{
66
77 use bytes::Bytes;
88 use common::{
9+ call::{
10+ Call, JoinVoice, LeaveVoice, ListShares, RequestKeyframe, StartShare, StopShare,
11+ UnwatchShare, WatchShare,
12+ },
913 datagram::{Packet, RELAY_PREFIX},
1014 event::{Event, Media as Down},
11- request::LegacyRequest,
12- response::Response,
1315 share::{Fps, Kind, Quality, Resolution, Source},
1416 };
1517 use quinn::Connection;
@@ -28,10 +30,7 @@ use crate::{
2830 voice::{self, Voice, VoiceSample, audio::Choice},
2931 };
3032
31-use super::{
32- link::{done, send},
33- *,
34-};
33+use super::{link::call, *};
3534
3635 const TICK: Duration = Duration::from_secs(1);
3736 const WAIT_STEP: Duration = Duration::from_millis(100);
@@ -187,7 +186,7 @@ impl Media {
187186 Ok(_) if ours => Rejoin::Install,
188187 Ok(_) => {
189188 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));
191190 }
192191 Rejoin::Skip
193192 }
@@ -228,7 +227,7 @@ impl Media {
228227 let media = self.clone();
229228 let connection = connection.clone();
230229 tokio::spawn(async move {
231- if send(&connection, &request).await.is_err() {
230+ if call(&connection, request).await.is_err() {
232231 media.lock().watching.remove(&key);
233232 }
234233 });
@@ -332,7 +331,7 @@ impl Media {
332331 inner.connection.clone().ok_or(Fail::Offline)?
333332 };
334333
335- done(&connection, LegacyRequest::LeaveVoice).await
334+ call(&connection, LeaveVoice).await
336335 }
337336
338337 async fn start_share(&self, kind: Kind, settings: ShareSettings) -> Result<(), Fail> {
@@ -359,7 +358,7 @@ impl Media {
359358 inner.sharing.insert(kind, sharing);
360359 }
361360
362- let result = done(&connection, LegacyRequest::StartShare { kind, source }).await;
361+ let result = call(&connection, StartShare { kind, source }).await;
363362 if result.is_err() {
364363 self.lock().sharing.remove(&kind);
365364 }
@@ -384,9 +383,9 @@ impl Media {
384383 .map_err(Fail::Io)?
385384 };
386385
387- done(
386+ call(
388387 &connection,
389- LegacyRequest::StartShare {
388+ StartShare {
390389 kind: Kind::Screen,
391390 source,
392391 },
@@ -398,16 +397,16 @@ impl Media {
398397 self.lock().sharing.remove(&kind);
399398 let (connection, _) = self.current_wait().await?;
400399
401- done(&connection, LegacyRequest::StopShare { kind }).await
400+ call(&connection, StopShare { kind }).await
402401 }
403402 }
404403
405404 impl Inner {
406- fn watch_requests(&self) -> Vec<((String, Kind), LegacyRequest)> {
405+ fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> {
407406 self.watching
408407 .iter()
409408 .map(|((user_id, kind), watching)| {
410- let request = LegacyRequest::WatchShare {
409+ let request = WatchShare {
411410 user_id: user_id.clone(),
412411 kind: *kind,
413412 quality: watching.wanted(),
@@ -426,17 +425,15 @@ enum Rejoin {
426425 }
427426
428427 async fn join(connection: &Connection, community_id: &str) -> Result<Vec<String>, Fail> {
429- let request = LegacyRequest::JoinVoice {
428+ let request = JoinVoice {
430429 community_id: community_id.to_string(),
431430 };
432- match send(connection, &request).await? {
433- Response::Voice(participants) => Ok(participants),
434- _ => Err(Fail::Protocol),
435- }
431+
432+ call(connection, request).await
436433 }
437434
438-async fn send_quietly(connection: Connection, request: LegacyRequest) {
439- if let Err(error) = send(&connection, &request).await {
435+async fn send_quietly<C: Call>(connection: Connection, request: C) {
436+ if let Err(error) = call(&connection, request).await {
440437 warn!("media request failed: {error}");
441438 }
442439 }
@@ -453,12 +450,20 @@ async fn tick_loop(media: Arc<Media>) {
453450 continue;
454451 };
455452 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+ };
457457 }
458458 }
459459 }
460460
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> {
462467 watching
463468 .iter_mut()
464469 .flat_map(|((user_id, kind), watching)| {
@@ -467,16 +472,16 @@ fn watch_ticks(watching: &mut HashMap<(String, Kind), Watching>) -> Vec<LegacyRe
467472 .tick()
468473 .into_iter()
469474 .map(|tick| match tick {
470- Tick::Quality(quality) => LegacyRequest::WatchShare {
475+ Tick::Quality(quality) => Ping::Watch(WatchShare {
471476 user_id: user_id.clone(),
472477 kind,
473478 quality,
474479 decode: capabilities().decode.clone(),
475- },
476- Tick::Keyframe => LegacyRequest::RequestKeyframe {
480+ }),
481+ Tick::Keyframe => Ping::Keyframe(RequestKeyframe {
477482 user_id: user_id.clone(),
478483 kind,
479- },
484+ }),
480485 })
481486 .collect::<Vec<_>>()
482487 })
@@ -663,13 +668,10 @@ impl NetworkHandle {
663668 }
664669
665670 pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> {
666- expect!(
667- self.request(LegacyRequest::Shares {
668- community_id: community_id.to_string(),
669- })
670- .await?,
671- Response::Shares
672- )
671+ self.call(ListShares {
672+ community_id: community_id.to_string(),
673+ })
674+ .await
673675 }
674676
675677 pub async fn watch_share(
@@ -695,9 +697,9 @@ impl NetworkHandle {
695697 }
696698 inner.watching.insert(key.clone(), watching);
697699 }
698- let result = done(
700+ let result = call(
699701 &connection,
700- LegacyRequest::WatchShare {
702+ WatchShare {
701703 user_id: key.0.clone(),
702704 kind,
703705 quality,
@@ -720,7 +722,7 @@ impl NetworkHandle {
720722 .watching
721723 .remove(&(user_id.to_string(), kind));
722724
723- self.done(LegacyRequest::UnwatchShare {
725+ self.call(UnwatchShare {
724726 user_id: user_id.to_string(),
725727 kind,
726728 })
crates/client/src/net/mod.rsmodified+225 -371
@@ -2,8 +2,22 @@ use std::{path::PathBuf, sync::Arc};
22
33 use common::{
44 call::{
5- Call, GetAvatar, GetSettings, GetUser, Legacy, ListPresences, ListSessions, RemoveAvatar,
6- RevokeSession, UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser,
5+ AcceptFriend, AcceptInvitation, AddFriend, BanMember, BanUser, Call, ClearProfile,
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,
721 },
822 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
923 event::Event,
@@ -14,8 +28,6 @@ use common::{
1428 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
1529 },
1630 open::Blob,
17- request::LegacyRequest,
18- response::Response,
1931 validate::{
2032 validate_avatar_size, validate_community_name, validate_forward, validate_new_message,
2133 validate_password, validate_poll, validate_reason, validate_server_settings,
@@ -24,15 +36,6 @@ use common::{
2436 };
2537 use tokio::sync::{mpsc, oneshot};
2638
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-
3639 mod datagram;
3740 mod events;
3841 mod fail;
@@ -134,22 +137,14 @@ impl NetworkHandle {
134137 .await
135138 }
136139
137- async fn request(&self, request: LegacyRequest) -> Result<Response, Fail> {
138- self.call(Legacy(request)).await
139- }
140-
141140 async fn switch(&self, token: Option<String>) -> Result<Option<User>, Fail> {
142141 self.ask(|reply| Command::SignIn { token, reply }).await
143142 }
144143
145- async fn sign_in(&self, request: LegacyRequest) -> Result<(User, String), Fail> {
146- let (user, token) = match self.request(request).await? {
147- Response::Session { user, token } => (user, token),
148- _ => return Err(Fail::Protocol),
149- };
150- self.switch(Some(token.clone())).await?;
144+ async fn sign_in(&self, session: Session) -> Result<(User, String), Fail> {
145+ self.switch(Some(session.token.clone())).await?;
151146
152- Ok((user, token))
147+ Ok((session.user, session.token))
153148 }
154149
155150 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Fail> {
@@ -170,14 +165,11 @@ impl NetworkHandle {
170165 pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Fail> {
171166 validate_username(username)?;
172167
173- expect!(
174- self.request(LegacyRequest::RenameUser {
175- user_id: user_id.to_string(),
176- username: username.to_string(),
177- })
178- .await?,
179- Response::User
180- )
168+ self.call(RenameUser {
169+ user_id: user_id.to_string(),
170+ username: username.to_string(),
171+ })
172+ .await
181173 }
182174
183175 pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> {
@@ -202,26 +194,32 @@ impl NetworkHandle {
202194 validate_username(username)?;
203195 validate_password(password)?;
204196
205- self.sign_in(LegacyRequest::Register {
206- username: username.to_string(),
207- password: password.to_string(),
208- invite: invite.map(str::to_string),
209- })
210- .await
197+ let session = self
198+ .call(Register {
199+ username: username.to_string(),
200+ password: password.to_string(),
201+ invite: invite.map(str::to_string),
202+ })
203+ .await?;
204+
205+ self.sign_in(session).await
211206 }
212207
213208 pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> {
214209 validate_password(password)?;
215210
216- self.sign_in(LegacyRequest::Login {
217- username: username.to_string(),
218- password: password.to_string(),
219- })
220- .await
211+ let session = self
212+ .call(Login {
213+ username: username.to_string(),
214+ password: password.to_string(),
215+ })
216+ .await?;
217+
218+ self.sign_in(session).await
221219 }
222220
223221 pub async fn logout(&self) -> Result<(), Fail> {
224- let result = self.done(LegacyRequest::Logout).await;
222+ let result = self.call(Logout).await;
225223 self.detach().await?;
226224 result
227225 }
@@ -236,22 +234,18 @@ impl NetworkHandle {
236234 }
237235
238236 pub async fn delete_user(&self, user_id: &str) -> Result<(), Fail> {
239- expect!(
240- self.request(LegacyRequest::DeleteUser {
241- user_id: user_id.to_string(),
242- })
243- .await?,
244- Response::User
245- )
246- .map(|_| ())
237+ self.call(DeleteUser {
238+ user_id: user_id.to_string(),
239+ })
240+ .await
247241 }
248242
249243 pub async fn users(&self) -> Result<Vec<Account>, Fail> {
250- expect!(self.request(LegacyRequest::Users).await?, Response::Users)
244+ self.call(ListUsers).await
251245 }
252246
253247 pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Fail> {
254- self.done(LegacyRequest::SuspendUser {
248+ self.call(SuspendUser {
255249 user_id: user_id.to_string(),
256250 suspended,
257251 })
@@ -259,7 +253,7 @@ impl NetworkHandle {
259253 }
260254
261255 pub async fn timeout_user(&self, user_id: &str, minutes: u32) -> Result<(), Fail> {
262- self.done(LegacyRequest::TimeoutUser {
256+ self.call(TimeoutUser {
263257 user_id: user_id.to_string(),
264258 minutes,
265259 })
@@ -274,7 +268,7 @@ impl NetworkHandle {
274268 ) -> Result<(), Fail> {
275269 validate_reason(reason)?;
276270
277- self.done(LegacyRequest::BanUser {
271+ self.call(BanUser {
278272 user_id: user_id.to_string(),
279273 reason: reason.map(str::to_string),
280274 scope,
@@ -283,15 +277,11 @@ impl NetworkHandle {
283277 }
284278
285279 pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Fail> {
286- expect!(
287- self.request(LegacyRequest::ServerBans).await?,
288- Response::ServerBans
289- )
280+ self.call(ListServerBans).await
290281 }
291282
292283 pub async fn remove_server_ban(&self, id: &str) -> Result<(), Fail> {
293- self.done(LegacyRequest::RemoveServerBan { id: id.to_string() })
294- .await
284+ self.call(RemoveServerBan { id: id.to_string() }).await
295285 }
296286
297287 pub async fn create_invite_code(
@@ -299,29 +289,22 @@ impl NetworkHandle {
299289 uses: u32,
300290 hours: Option<u32>,
301291 ) -> Result<InviteCode, Fail> {
302- expect!(
303- self.request(LegacyRequest::CreateInviteCode { uses, hours })
304- .await?,
305- Response::InviteCode
306- )
292+ self.call(CreateInviteCode { uses, hours }).await
307293 }
308294
309295 pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Fail> {
310- expect!(
311- self.request(LegacyRequest::InviteCodes).await?,
312- Response::InviteCodes
313- )
296+ self.call(ListInviteCodes).await
314297 }
315298
316299 pub async fn delete_invite_code(&self, code: &str) -> Result<(), Fail> {
317- self.done(LegacyRequest::DeleteInviteCode {
300+ self.call(DeleteInviteCode {
318301 code: code.to_string(),
319302 })
320303 .await
321304 }
322305
323306 pub async fn revoke_sessions(&self, user_id: &str) -> Result<(), Fail> {
324- self.done(LegacyRequest::RevokeSessions {
307+ self.call(RevokeSessions {
325308 user_id: user_id.to_string(),
326309 })
327310 .await
@@ -330,7 +313,7 @@ impl NetworkHandle {
330313 pub async fn reset_password(&self, user_id: &str, password: &str) -> Result<(), Fail> {
331314 validate_password(password)?;
332315
333- self.done(LegacyRequest::ResetPassword {
316+ self.call(ResetPassword {
334317 user_id: user_id.to_string(),
335318 password: password.to_string(),
336319 })
@@ -338,24 +321,18 @@ impl NetworkHandle {
338321 }
339322
340323 pub async fn clear_profile(&self, user_id: &str) -> Result<User, Fail> {
341- expect!(
342- self.request(LegacyRequest::ClearProfile {
343- user_id: user_id.to_string(),
344- })
345- .await?,
346- Response::User
347- )
324+ self.call(ClearProfile {
325+ user_id: user_id.to_string(),
326+ })
327+ .await
348328 }
349329
350330 pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Fail> {
351- expect!(
352- self.request(LegacyRequest::SetRole {
353- user_id: user_id.to_string(),
354- role,
355- })
356- .await?,
357- Response::User
358- )
331+ self.call(SetRole {
332+ user_id: user_id.to_string(),
333+ role,
334+ })
335+ .await
359336 }
360337
361338 pub async fn admin_logs(
@@ -366,21 +343,18 @@ impl NetworkHandle {
366343 after_ms: Option<u64>,
367344 before_ms: Option<u64>,
368345 ) -> Result<Vec<AdminLogEntry>, Fail> {
369- let request = LegacyRequest::AdminLogs {
346+ self.call(ListAdminLogs {
370347 actor_id,
371348 target_id,
372349 action,
373350 after_ms,
374351 before_ms,
375- };
376- expect!(self.request(request).await?, Response::AdminLogs)
352+ })
353+ .await
377354 }
378355
379356 pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Fail> {
380- expect!(
381- self.request(LegacyRequest::DailyStats { days }).await?,
382- Response::DailyStats
383- )
357+ self.call(GetDailyStats { days }).await
384358 }
385359
386360 pub async fn server_settings(&self) -> Result<ServerSettings, Fail> {
@@ -393,43 +367,30 @@ impl NetworkHandle {
393367 ) -> Result<ServerSettings, Fail> {
394368 validate_server_settings(&settings)?;
395369
396- expect!(
397- self.request(LegacyRequest::UpdateServerSettings { settings })
398- .await?,
399- Response::ServerSettings
400- )
370+ self.call(UpdateServerSettings { settings }).await
401371 }
402372
403373 pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Fail> {
404374 validate_username(username)?;
405375 validate_password(password)?;
406376
407- expect!(
408- self.request(LegacyRequest::CreateUser {
409- username: username.to_string(),
410- password: password.to_string(),
411- })
412- .await?,
413- Response::User
414- )
377+ self.call(CreateUser {
378+ username: username.to_string(),
379+ password: password.to_string(),
380+ })
381+ .await
415382 }
416383
417384 pub async fn overview(&self) -> Result<Overview, Fail> {
418- expect!(
419- self.request(LegacyRequest::Overview).await?,
420- Response::Overview
421- )
385+ self.call(GetOverview).await
422386 }
423387
424388 pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Fail> {
425- expect!(
426- self.request(LegacyRequest::AllCommunities).await?,
427- Response::AllCommunities
428- )
389+ self.call(ListAllCommunities).await
429390 }
430391
431392 pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
432- self.done(LegacyRequest::TransferOwnership {
393+ self.call(TransferOwnership {
433394 community_id: community_id.to_string(),
434395 user_id: user_id.to_string(),
435396 })
@@ -446,13 +407,10 @@ impl NetworkHandle {
446407 pub async fn create_community(&self, name: &str) -> Result<Community, Fail> {
447408 validate_community_name(name)?;
448409
449- expect!(
450- self.request(LegacyRequest::CreateCommunity {
451- name: name.to_string(),
452- })
453- .await?,
454- Response::Community
455- )
410+ self.call(CreateCommunity {
411+ name: name.to_string(),
412+ })
413+ .await
456414 }
457415
458416 pub async fn update_community(
@@ -462,49 +420,36 @@ impl NetworkHandle {
462420 ) -> Result<Community, Fail> {
463421 validate_community_name(name)?;
464422
465- expect!(
466- self.request(LegacyRequest::UpdateCommunity {
467- community_id: community_id.to_string(),
468- name: name.to_string(),
469- })
470- .await?,
471- Response::Community
472- )
423+ self.call(UpdateCommunity {
424+ community_id: community_id.to_string(),
425+ name: name.to_string(),
426+ })
427+ .await
473428 }
474429
475430 pub async fn delete_community(&self, community_id: &str) -> Result<(), Fail> {
476- expect!(
477- self.request(LegacyRequest::DeleteCommunity {
478- community_id: community_id.to_string(),
479- })
480- .await?,
481- Response::Community
482- )
483- .map(|_| ())
431+ self.call(DeleteCommunity {
432+ community_id: community_id.to_string(),
433+ })
434+ .await
484435 }
485436
486437 pub async fn leave_community(&self, community_id: &str) -> Result<(), Fail> {
487- self.done(LegacyRequest::LeaveCommunity {
438+ self.call(LeaveCommunity {
488439 community_id: community_id.to_string(),
489440 })
490441 .await
491442 }
492443
493444 pub async fn communities(&self) -> Result<Vec<Community>, Fail> {
494- expect!(
495- self.request(LegacyRequest::Communities).await?,
496- Response::Communities
497- )
445+ self.call(ListCommunities).await
498446 }
499447
500448 pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Fail> {
501- expect!(
502- self.request(LegacyRequest::Members {
503- community_id: community_id.to_string(),
504- })
505- .await?,
506- Response::Members
507- )
449+ self.call(ListMembers {
450+ community_id: community_id.to_string(),
451+ })
452+ .await
508453 }
509454
510455 pub async fn kick(
@@ -514,7 +459,7 @@ impl NetworkHandle {
514459 reason: Option<&str>,
515460 ) -> Result<(), Fail> {
516461 validate_reason(reason)?;
517- self.done(LegacyRequest::Kick {
462+ self.call(Kick {
518463 community_id: community_id.to_string(),
519464 user_id: user_id.to_string(),
520465 reason: reason.map(str::to_string),
@@ -529,7 +474,7 @@ impl NetworkHandle {
529474 reason: Option<&str>,
530475 ) -> Result<(), Fail> {
531476 validate_reason(reason)?;
532- self.done(LegacyRequest::Ban {
477+ self.call(BanMember {
533478 community_id: community_id.to_string(),
534479 user_id: user_id.to_string(),
535480 reason: reason.map(str::to_string),
@@ -538,7 +483,7 @@ impl NetworkHandle {
538483 }
539484
540485 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
541- self.done(LegacyRequest::Unban {
486+ self.call(Unban {
542487 community_id: community_id.to_string(),
543488 user_id: user_id.to_string(),
544489 })
@@ -546,23 +491,17 @@ impl NetworkHandle {
546491 }
547492
548493 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Fail> {
549- expect!(
550- self.request(LegacyRequest::Bans {
551- community_id: community_id.to_string(),
552- })
553- .await?,
554- Response::Bans
555- )
494+ self.call(ListBans {
495+ community_id: community_id.to_string(),
496+ })
497+ .await
556498 }
557499
558500 pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Fail> {
559- expect!(
560- self.request(LegacyRequest::Logs {
561- community_id: community_id.to_string(),
562- })
563- .await?,
564- Response::Logs
565- )
501+ self.call(ListLogs {
502+ community_id: community_id.to_string(),
503+ })
504+ .await
566505 }
567506
568507 pub async fn set_rank(
@@ -571,7 +510,7 @@ impl NetworkHandle {
571510 user_id: &str,
572511 rank: Rank,
573512 ) -> Result<(), Fail> {
574- self.done(LegacyRequest::SetRank {
513+ self.call(SetRank {
575514 community_id: community_id.to_string(),
576515 user_id: user_id.to_string(),
577516 rank,
@@ -580,14 +519,10 @@ impl NetworkHandle {
580519 }
581520
582521 pub async fn delete_message(&self, message_id: &str) -> Result<(), Fail> {
583- expect!(
584- self.request(LegacyRequest::DeleteMessage {
585- message_id: message_id.to_string(),
586- })
587- .await?,
588- Response::Message
589- )
590- .map(|_| ())
522+ self.call(DeleteMessage {
523+ message_id: message_id.to_string(),
524+ })
525+ .await
591526 }
592527
593528 pub async fn create_message(
@@ -599,29 +534,23 @@ impl NetworkHandle {
599534 ) -> Result<Message, Fail> {
600535 validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?;
601536
602- expect!(
603- self.request(LegacyRequest::CreateMessage {
604- community_id: community_id.to_string(),
605- body: body.to_string(),
606- attachments,
607- reply_to,
608- })
609- .await?,
610- Response::Message
611- )
537+ self.call(CreateMessage {
538+ community_id: community_id.to_string(),
539+ body: body.to_string(),
540+ attachments,
541+ reply_to,
542+ })
543+ .await
612544 }
613545
614546 pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Fail> {
615547 validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?;
616548
617- expect!(
618- self.request(LegacyRequest::UpdateMessage {
619- message_id: message_id.to_string(),
620- body: body.to_string(),
621- })
622- .await?,
623- Response::Message
624- )
549+ self.call(UpdateMessage {
550+ message_id: message_id.to_string(),
551+ body: body.to_string(),
552+ })
553+ .await
625554 }
626555
627556 pub async fn forward_messages(
@@ -632,49 +561,34 @@ impl NetworkHandle {
632561 ) -> Result<Vec<Message>, Fail> {
633562 validate_forward(message_ids.len())?;
634563
635- expect!(
636- self.request(LegacyRequest::ForwardMessages {
637- message_ids,
638- community_id: community_id.to_string(),
639- snippet,
640- })
641- .await?,
642- Response::Messages
643- )
564+ self.call(ForwardMessages {
565+ message_ids,
566+ community_id: community_id.to_string(),
567+ snippet,
568+ })
569+ .await
644570 }
645571
646572 pub async fn find_user(&self, username: &str) -> Result<User, Fail> {
647- expect!(
648- self.request(LegacyRequest::FindUser {
649- username: username.to_string(),
650- })
651- .await?,
652- Response::User
653- )
573+ self.call(FindUser {
574+ username: username.to_string(),
575+ })
576+ .await
654577 }
655578
656579 pub async fn open_notes(&self) -> Result<Community, Fail> {
657- expect!(
658- self.request(LegacyRequest::OpenNotes).await?,
659- Response::Community
660- )
580+ self.call(OpenNotes).await
661581 }
662582
663583 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Fail> {
664- expect!(
665- self.request(LegacyRequest::OpenDirect {
666- user_id: user_id.to_string(),
667- })
668- .await?,
669- Response::Community
670- )
584+ self.call(OpenDirect {
585+ user_id: user_id.to_string(),
586+ })
587+ .await
671588 }
672589
673590 pub async fn friends(&self) -> Result<Friends, Fail> {
674- expect!(
675- self.request(LegacyRequest::Friends).await?,
676- Response::Friends
677- )
591+ self.call(ListFriends).await
678592 }
679593
680594 pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Fail> {
@@ -686,28 +600,28 @@ impl NetworkHandle {
686600 }
687601
688602 pub async fn add_friend(&self, user_id: &str) -> Result<(), Fail> {
689- self.done(LegacyRequest::AddFriend {
603+ self.call(AddFriend {
690604 user_id: user_id.to_string(),
691605 })
692606 .await
693607 }
694608
695609 pub async fn accept_friend(&self, user_id: &str) -> Result<(), Fail> {
696- self.done(LegacyRequest::AcceptFriend {
610+ self.call(AcceptFriend {
697611 user_id: user_id.to_string(),
698612 })
699613 .await
700614 }
701615
702616 pub async fn remove_friend(&self, user_id: &str) -> Result<(), Fail> {
703- self.done(LegacyRequest::RemoveFriend {
617+ self.call(RemoveFriend {
704618 user_id: user_id.to_string(),
705619 })
706620 .await
707621 }
708622
709623 pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Fail> {
710- self.done(LegacyRequest::Invite {
624+ self.call(Invite {
711625 community_id: community_id.to_string(),
712626 user_id: user_id.to_string(),
713627 })
@@ -715,38 +629,32 @@ impl NetworkHandle {
715629 }
716630
717631 pub async fn invitations(&self) -> Result<Vec<Invitation>, Fail> {
718- expect!(
719- self.request(LegacyRequest::Invitations).await?,
720- Response::Invitations
721- )
632+ self.call(ListInvitations).await
722633 }
723634
724635 pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Fail> {
725- expect!(
726- self.request(LegacyRequest::AcceptInvitation {
727- community_id: community_id.to_string(),
728- })
729- .await?,
730- Response::Community
731- )
636+ self.call(AcceptInvitation {
637+ community_id: community_id.to_string(),
638+ })
639+ .await
732640 }
733641
734642 pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Fail> {
735- self.done(LegacyRequest::DeclineInvitation {
643+ self.call(DeclineInvitation {
736644 community_id: community_id.to_string(),
737645 })
738646 .await
739647 }
740648
741649 pub async fn decline_call(&self, community_id: &str) -> Result<(), Fail> {
742- self.done(LegacyRequest::DeclineCall {
650+ self.call(DeclineCall {
743651 community_id: community_id.to_string(),
744652 })
745653 .await
746654 }
747655
748656 pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Fail> {
749- self.done(LegacyRequest::React {
657+ self.call(React {
750658 message_id: message_id.to_string(),
751659 emoji: emoji.to_string(),
752660 })
@@ -754,7 +662,7 @@ impl NetworkHandle {
754662 }
755663
756664 pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Fail> {
757- self.done(LegacyRequest::Pin {
665+ self.call(Pin {
758666 message_id: message_id.to_string(),
759667 pinned,
760668 })
@@ -762,13 +670,10 @@ impl NetworkHandle {
762670 }
763671
764672 pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Fail> {
765- expect!(
766- self.request(LegacyRequest::Pins {
767- community_id: community_id.to_string(),
768- })
769- .await?,
770- Response::Messages
771- )
673+ self.call(ListPins {
674+ community_id: community_id.to_string(),
675+ })
676+ .await
772677 }
773678
774679 pub async fn create_poll(
@@ -780,20 +685,17 @@ impl NetworkHandle {
780685 ) -> Result<Message, Fail> {
781686 validate_poll(question, &options)?;
782687
783- expect!(
784- self.request(LegacyRequest::CreatePoll {
785- community_id: community_id.to_string(),
786- question: question.to_string(),
787- options,
788- multiple,
789- })
790- .await?,
791- Response::Message
792- )
688+ self.call(CreatePoll {
689+ community_id: community_id.to_string(),
690+ question: question.to_string(),
691+ options,
692+ multiple,
693+ })
694+ .await
793695 }
794696
795697 pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Fail> {
796- self.done(LegacyRequest::Vote {
698+ self.call(Vote {
797699 message_id: message_id.to_string(),
798700 positions,
799701 })
@@ -801,7 +703,7 @@ impl NetworkHandle {
801703 }
802704
803705 pub async fn close_poll(&self, message_id: &str) -> Result<(), Fail> {
804- self.done(LegacyRequest::ClosePoll {
706+ self.call(ClosePoll {
805707 message_id: message_id.to_string(),
806708 })
807709 .await
@@ -810,7 +712,7 @@ impl NetworkHandle {
810712 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Fail> {
811713 validate_reason(Some(reason))?;
812714
813- self.done(LegacyRequest::ReportMessage {
715+ self.call(ReportMessage {
814716 message_id: message_id.to_string(),
815717 reason: reason.to_string(),
816718 })
@@ -820,7 +722,7 @@ impl NetworkHandle {
820722 pub async fn report_user(&self, user_id: &str, reason: &str) -> Result<(), Fail> {
821723 validate_reason(Some(reason))?;
822724
823- self.done(LegacyRequest::ReportUser {
725+ self.call(ReportUser {
824726 user_id: user_id.to_string(),
825727 reason: reason.to_string(),
826728 })
@@ -828,14 +730,11 @@ impl NetworkHandle {
828730 }
829731
830732 pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Fail> {
831- expect!(
832- self.request(LegacyRequest::Reports { status }).await?,
833- Response::Reports
834- )
733+ self.call(ListReports { status }).await
835734 }
836735
837736 pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Fail> {
838- self.done(LegacyRequest::HandleReport {
737+ self.call(HandleReport {
839738 report_id: report_id.to_string(),
840739 status,
841740 })
@@ -850,17 +749,14 @@ impl NetworkHandle {
850749 after_ms: Option<u64>,
851750 before_ms: Option<u64>,
852751 ) -> Result<Vec<MessageHit>, Fail> {
853- expect!(
854- self.request(LegacyRequest::SearchMessages {
855- text,
856- user_id,
857- community_id,
858- after_ms,
859- before_ms,
860- })
861- .await?,
862- Response::MessageHits
863- )
752+ self.call(SearchMessages {
753+ text,
754+ user_id,
755+ community_id,
756+ after_ms,
757+ before_ms,
758+ })
759+ .await
864760 }
865761
866762 pub async fn search_community(
@@ -868,36 +764,25 @@ impl NetworkHandle {
868764 community_id: String,
869765 text: String,
870766 ) -> Result<Vec<MessageHit>, Fail> {
871- expect!(
872- self.request(LegacyRequest::SearchCommunity { community_id, text })
873- .await?,
874- Response::MessageHits
875- )
767+ self.call(SearchCommunity { community_id, text }).await
876768 }
877769
878770 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Fail> {
879- match self.request(LegacyRequest::StorageUsage).await? {
880- Response::StorageUsage { users, communities } => Ok((users, communities)),
881- _ => Err(Fail::Protocol),
882- }
771+ let usage = self.call(GetStorageUsage).await?;
772+
773+ Ok((usage.users, usage.communities))
883774 }
884775
885776 pub async fn create_backup(&self) -> Result<BackupInfo, Fail> {
886- expect!(
887- self.request(LegacyRequest::CreateBackup).await?,
888- Response::Backup
889- )
777+ self.call(CreateBackup).await
890778 }
891779
892780 pub async fn backups(&self) -> Result<Vec<BackupInfo>, Fail> {
893- expect!(
894- self.request(LegacyRequest::Backups).await?,
895- Response::Backups
896- )
781+ self.call(ListBackups).await
897782 }
898783
899784 pub async fn delete_backup(&self, name: &str) -> Result<(), Fail> {
900- self.done(LegacyRequest::DeleteBackup {
785+ self.call(DeleteBackup {
901786 name: name.to_string(),
902787 })
903788 .await
@@ -908,37 +793,27 @@ impl NetworkHandle {
908793 user_id: Option<String>,
909794 community_id: Option<String>,
910795 ) -> Result<Vec<AttachmentInfo>, Fail> {
911- expect!(
912- self.request(LegacyRequest::AllAttachments {
913- user_id,
914- community_id,
915- })
916- .await?,
917- Response::AttachmentInfos
918- )
796+ self.call(ListAttachments {
797+ user_id,
798+ community_id,
799+ })
800+ .await
919801 }
920802
921803 pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Fail> {
922- self.done(LegacyRequest::DeleteAttachment {
804+ self.call(DeleteAttachment {
923805 attachment_id: attachment_id.to_string(),
924806 })
925807 .await
926808 }
927809
928810 pub async fn purge_user(&self, user_id: &str) -> Result<(), Fail> {
929- self.done(LegacyRequest::PurgeUser {
811+ self.call(PurgeUser {
930812 user_id: user_id.to_string(),
931813 })
932814 .await
933815 }
934816
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-
942817 pub async fn upload_attachment(
943818 &self,
944819 community_id: &str,
@@ -978,7 +853,7 @@ impl NetworkHandle {
978853 }
979854
980855 pub async fn watch_community(&self, community_id: Option<&str>) -> Result<(), Fail> {
981- self.done(LegacyRequest::WatchCommunity {
856+ self.call(WatchCommunity {
982857 community_id: community_id.map(str::to_string),
983858 })
984859 .await
@@ -989,25 +864,19 @@ impl NetworkHandle {
989864 community_id: &str,
990865 before: Option<&str>,
991866 ) -> Result<Vec<Message>, Fail> {
992- expect!(
993- self.request(LegacyRequest::ReadMessages {
994- community_id: community_id.to_string(),
995- before: before.map(str::to_string),
996- })
997- .await?,
998- Response::Messages
999- )
867+ self.call(ListMessages {
868+ community_id: community_id.to_string(),
869+ before: before.map(str::to_string),
870+ })
871+ .await
1000872 }
1001873
1002874 pub async fn unreads(&self) -> Result<Vec<Unread>, Fail> {
1003- expect!(
1004- self.request(LegacyRequest::Unreads).await?,
1005- Response::Unreads
1006- )
875+ self.call(ListUnreads).await
1007876 }
1008877
1009878 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Fail> {
1010- self.done(LegacyRequest::MarkRead {
879+ self.call(MarkRead {
1011880 community_id: community_id.to_string(),
1012881 message_id: message_id.to_string(),
1013882 })
@@ -1038,14 +907,11 @@ impl NetworkHandle {
1038907 validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?;
1039908 }
1040909
1041- expect!(
1042- self.request(LegacyRequest::UpdateCommunityAvatar {
1043- community_id: community_id.to_string(),
1044- image,
1045- })
1046- .await?,
1047- Response::Community
1048- )
910+ self.call(UpdateCommunityAvatar {
911+ community_id: community_id.to_string(),
912+ image,
913+ })
914+ .await
1049915 }
1050916
1051917 pub async fn remove_avatar(&self) -> Result<User, Fail> {
@@ -1060,52 +926,43 @@ impl NetworkHandle {
1060926 }
1061927
1062928 pub async fn typing(&self, community_id: &str) -> Result<(), Fail> {
1063- self.done(LegacyRequest::Typing {
929+ self.call(Typing {
1064930 community_id: community_id.to_string(),
1065931 })
1066932 .await
1067933 }
1068934
1069935 pub async fn read_community(&self, community_id: &str) -> Result<Community, Fail> {
1070- expect!(
1071- self.request(LegacyRequest::ReadCommunity {
1072- community_id: community_id.to_string(),
1073- })
1074- .await?,
1075- Response::Community
1076- )
936+ self.call(GetCommunity {
937+ community_id: community_id.to_string(),
938+ })
939+ .await
1077940 }
1078941
1079942 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Fail> {
1080- expect!(
1081- self.request(LegacyRequest::VoiceParticipants {
1082- community_id: community_id.to_string(),
1083- })
1084- .await?,
1085- Response::Voice
1086- )
943+ self.call(ListVoiceParticipants {
944+ community_id: community_id.to_string(),
945+ })
946+ .await
1087947 }
1088948
1089949 pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Fail> {
1090- expect!(
1091- self.request(LegacyRequest::VoiceRooms).await?,
1092- Response::VoiceRooms
1093- )
950+ self.call(ListVoiceRooms).await
1094951 }
1095952
1096953 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Fail> {
1097- self.done(LegacyRequest::SetGhost { enabled }).await
954+ self.call(SetGhost { enabled }).await
1098955 }
1099956
1100957 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Fail> {
1101- self.done(LegacyRequest::KickFromVoice {
958+ self.call(KickFromVoice {
1102959 user_id: user_id.to_string(),
1103960 })
1104961 .await
1105962 }
1106963
1107964 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Fail> {
1108- self.done(LegacyRequest::ServerMute {
965+ self.call(ServerMute {
1109966 user_id: user_id.to_string(),
1110967 muted,
1111968 })
@@ -1117,13 +974,10 @@ impl NetworkHandle {
1117974 community_id: &str,
1118975 enabled: bool,
1119976 ) -> Result<Community, Fail> {
1120- expect!(
1121- self.request(LegacyRequest::SetCommunityVoice {
1122- community_id: community_id.to_string(),
1123- enabled,
1124- })
1125- .await?,
1126- Response::Community
1127- )
977+ self.call(SetCommunityVoice {
978+ community_id: community_id.to_string(),
979+ enabled,
980+ })
981+ .await
1128982 }
1129983 }
crates/common/src/call.rsmodified+603 -7
@@ -1,9 +1,13 @@
11 use bitcode::{Decode, DecodeOwned, Encode};
22
33 use crate::{
4- model::{Presence, ServerSettings, SessionInfo, User},
5- request::LegacyRequest,
6- response::Response,
4+ model::{
5+ Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
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},
711 };
812
913 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -40,9 +44,6 @@ macro_rules! calls {
4044 };
4145 }
4246
43-#[derive(Debug, Clone, Encode, Decode)]
44-pub struct Legacy(pub LegacyRequest);
45-
4647 #[derive(Debug, Clone, Encode, Decode)]
4748 pub struct GetSettings;
4849
@@ -93,8 +94,510 @@ pub struct RevokeSession {
9394 pub session_id: String,
9495 }
9596
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+
96600 calls! {
97- Legacy: Guest -> Response;
98601 GetSettings: Guest -> ServerSettings;
99602 GetUser: User -> User;
100603 UpdateUser: User -> User;
@@ -106,4 +609,97 @@ calls! {
106609 GetAvatar: User -> Vec<u8>;
107610 ListSessions: User -> Vec<SessionInfo>;
108611 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 -> ();
109705 }
crates/common/src/lib.rsmodified+0 -2
@@ -8,8 +8,6 @@ pub mod frame;
88 pub mod model;
99 pub mod open;
1010 pub mod permission;
11-pub mod request;
12-pub mod response;
1311 pub mod session;
1412 pub mod share;
1513 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 {
671671 use std::io::Cursor;
672672
673673 use common::{
674+ call::CreateMessage,
674675 model::{AttachmentKind, Rank},
675676 open::Upload,
676- request::LegacyRequest,
677677 };
678678 use image::{ImageFormat, RgbImage};
679679
680680 use crate::{
681681 attachment::{store, thumb_path},
682+ call::{Cx, Handle, Me},
682683 community, database,
683684 hub::{Client, Signed},
684685 message,
685- network::Services,
686- request::handle,
686+ network::{Services, Shared},
687687 test, user, user_community,
688688 };
689689
@@ -716,21 +716,22 @@ mod tests {
716716 user_id: user.id.clone(),
717717 token: "token".to_string(),
718718 }));
719- let (reply, _) = handle(
720- LegacyRequest::CreateMessage {
721- community_id: community.id.clone(),
722- body: String::new(),
723- attachments: vec![attachment.id.clone()],
724- reply_to: None,
725- },
726- &client,
727- &db,
728- &Services::default(),
729- &test::directory(),
730- &test::directory(),
731- )
732- .await;
733- reply.unwrap();
719+ let shared = Shared {
720+ db: db.clone(),
721+ services: Services::default(),
722+ directory: test::directory(),
723+ backups: test::directory(),
724+ };
725+ let mut cx = Cx::new(&client, &shared, database::connect(&db).await.unwrap());
726+ CreateMessage {
727+ community_id: community.id.clone(),
728+ body: String::new(),
729+ attachments: vec![attachment.id.clone()],
730+ reply_to: None,
731+ }
732+ .handle(Me::User(user), &mut cx)
733+ .await
734+ .unwrap();
734735
735736 let messages = message::read_page(&community.id, None, &conn)
736737 .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;
15 mod user;
6+mod voice;
27
38 use std::{future::Future, sync::Arc};
49
510 use common::{
6- call::{Call, Gate, Legacy, Request},
11+ call::{Call, Gate, Request},
712 error::Error,
813 event::Event,
914 frame::{self, DOWN_MAX},
@@ -90,7 +95,6 @@ async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> {
9095
9196 pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
9297 match request {
93- Request::Legacy(call) => serve(call, cx).await,
9498 Request::GetSettings(call) => serve(call, cx).await,
9599 Request::GetUser(call) => serve(call, cx).await,
96100 Request::UpdateUser(call) => serve(call, cx).await,
@@ -102,22 +106,98 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> {
102106 Request::GetAvatar(call) => serve(call, cx).await,
103107 Request::ListSessions(call) => serve(call, cx).await,
104108 Request::RevokeSession(call) => serve(call, cx).await,
105- }
106-}
107-
108-impl Handle for Legacy {
109- async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Self::Reply, ServerError> {
110- let (reply, broadcasts) = request::dispatch(
111- self.0,
112- cx.client,
113- &cx.sh.db,
114- &cx.sh.services,
115- &cx.sh.directory,
116- &cx.sh.backups,
117- )
118- .await?;
119- cx.out.extend(broadcasts);
120-
121- Ok(reply)
109+ Request::CreateCommunity(call) => serve(call, cx).await,
110+ Request::GetCommunity(call) => serve(call, cx).await,
111+ Request::UpdateCommunity(call) => serve(call, cx).await,
112+ Request::UpdateCommunityAvatar(call) => serve(call, cx).await,
113+ Request::DeleteCommunity(call) => serve(call, cx).await,
114+ Request::LeaveCommunity(call) => serve(call, cx).await,
115+ Request::ListCommunities(call) => serve(call, cx).await,
116+ Request::ListMembers(call) => serve(call, cx).await,
117+ Request::Kick(call) => serve(call, cx).await,
118+ Request::BanMember(call) => serve(call, cx).await,
119+ Request::Unban(call) => serve(call, cx).await,
120+ Request::ListBans(call) => serve(call, cx).await,
121+ Request::SetRank(call) => serve(call, cx).await,
122+ Request::ListLogs(call) => serve(call, cx).await,
123+ Request::CreateMessage(call) => serve(call, cx).await,
124+ Request::ForwardMessages(call) => serve(call, cx).await,
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,
122202 }
123203 }
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-
31 use common::{
42 error::Error as CommonError,
53 event::Event,
6- model::{
7- AdminAction, BanScope, CallLog, CommunitySummary, LogAction, Member, Message, Presence,
8- Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom,
9- },
4+ model::{AdminAction, CallLog, Message, Presence, Rank, User, VoiceRoom},
105 permission,
11- request::LegacyRequest,
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- },
6+ share::Kind,
207 };
218 use turso::Connection;
229
2310 use crate::{
24- admin_log, attachment, authentication, backup, community,
25- database::{self, DB},
26- direct,
11+ admin_log, community,
2712 error::ServerError,
28- friend,
2913 hub::{Client, Hub},
30- invitation, invite, log, message,
31- network::Services,
32- notes, overview,
14+ message,
3315 publish::{Broadcast, To},
3416 rate_limit::RateLimit,
35- report,
3617 rooms::{Departure, Rooms},
37- server_ban, server_settings, stats, user, user_community,
18+ server_settings, user, user_community,
3819 };
3920
40-pub(crate) type Outcome = (Response, Vec<Broadcast>);
41-
42-#[cfg(test)]
43-pub async fn handle(
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> {
21+pub(crate) async fn voice_rooms(
22+ occupied: &Rooms,
23+ conn: &Connection,
24+) -> Result<Vec<VoiceRoom>, ServerError> {
152325 let mut rooms = Vec::new();
152426 for (community_id, user_ids, ghosts) in occupied.list() {
152527 let community = community::label(&community_id, conn).await?;
@@ -1545,15 +47,11 @@ async fn voice_rooms(occupied: &Rooms, conn: &Connection) -> Result<Vec<VoiceRoo
154547 Ok(rooms)
154648 }
154749
1548-fn report_created() -> Broadcast {
1549- Broadcast::new(To::Builders, Event::ReportCreated)
1550-}
1551-
155250 fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> {
155351 connection.map(|connection| connection.remote_address().ip().to_string())
155452 }
155553
1556-async fn limit_logins(
54+pub(crate) async fn limit_logins(
155755 rate_limit: &RateLimit,
155856 connection: Option<&quinn::Connection>,
155957 conn: &Connection,
@@ -1563,18 +61,6 @@ async fn limit_logins(
156361 Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?)
156462 }
156563
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-
157864 pub(crate) async fn record_address(
157965 user: &User,
158066 connection: Option<&quinn::Connection>,
@@ -1587,65 +73,6 @@ pub(crate) async fn record_address(
158773 Ok(())
158874 }
158975
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-
164976 pub(crate) fn user_updated(user: &User) -> Vec<Broadcast> {
165077 vec![Broadcast::new(
165178 To::Related(user.id.clone()),
@@ -1683,26 +110,7 @@ pub async fn presence_changed(
1683110 )])
1684111 }
1685112
1686-async fn friends_updated(
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(
113+pub(crate) async fn leave_user_voice(
1706114 rooms: &Rooms,
1707115 user_id: &str,
1708116 conn: &Connection,
@@ -1713,7 +121,7 @@ async fn leave_user_voice(
1713121 }
1714122 }
1715123
1716-async fn leave_room_voice(
124+pub(crate) async fn leave_room_voice(
1717125 rooms: &Rooms,
1718126 community_id: &str,
1719127 user_id: &str,
@@ -1725,7 +133,7 @@ async fn leave_room_voice(
1725133 }
1726134 }
1727135
1728-async fn voice_unmuted(
136+pub(crate) async fn voice_unmuted(
1729137 rooms: &Rooms,
1730138 user_id: &str,
1731139 conn: &Connection,
@@ -1739,7 +147,7 @@ async fn voice_unmuted(
1739147 ])
1740148 }
1741149
1742-async fn voice_muted(
150+pub(crate) async fn voice_muted(
1743151 community_id: Option<String>,
1744152 user_id: &str,
1745153 muted: bool,
@@ -1760,7 +168,7 @@ async fn voice_muted(
1760168 Ok(Broadcast::new(To::Users(user_ids), event))
1761169 }
1762170
1763-async fn voice_silenced(
171+pub(crate) async fn voice_silenced(
1764172 rooms: &Rooms,
1765173 community_id: &str,
1766174 conn: &Connection,
@@ -1776,7 +184,7 @@ async fn voice_silenced(
1776184 Ok(broadcasts)
1777185 }
1778186
1779-async fn voice_closed(
187+pub(crate) async fn voice_closed(
1780188 rooms: &Rooms,
1781189 community_id: &str,
1782190 conn: &Connection,
@@ -1789,7 +197,7 @@ async fn voice_closed(
1789197 Ok(broadcasts)
1790198 }
1791199
1792-async fn call_ended(
200+pub(crate) async fn call_ended(
1793201 community_id: &str,
1794202 user_id: &str,
1795203 call: Option<CallLog>,
@@ -1836,7 +244,7 @@ pub async fn departed(
1836244 Ok(broadcasts)
1837245 }
1838246
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 {
1840248 let event = Event::ShareStopped {
1841249 community_id: community_id.to_string(),
1842250 user_id: user_id.to_string(),
@@ -1846,7 +254,7 @@ fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast {
1846254 Broadcast::new(To::Community(community_id.to_string()), event)
1847255 }
1848256
1849-fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> {
257+pub(crate) fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> {
1850258 let mut broadcasts: Vec<Broadcast> = departure
1851259 .shares
1852260 .iter()
@@ -1907,7 +315,7 @@ pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError>
1907315 Ok(())
1908316 }
1909317
1910-async fn allowed(
318+pub(crate) async fn allowed(
1911319 me: &User,
1912320 community_id: &str,
1913321 conn: &Connection,
@@ -1916,7 +324,7 @@ async fn allowed(
1916324 ensure(check(actor_rank(me, community_id, conn).await?))
1917325 }
1918326
1919-async fn is_outsider(
327+pub(crate) async fn is_outsider(
1920328 user_id: &str,
1921329 community_id: &str,
1922330 conn: &Connection,
@@ -1926,18 +334,21 @@ async fn is_outsider(
1926334 .is_none())
1927335 }
1928336
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> {
1930341 ensure(!community::is_fixed(community_id, conn).await?)
1931342 }
1932343
1933-fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {
344+pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast {
1934345 Broadcast::new(
1935346 To::Community(message.community_id.clone()),
1936347 event(message.clone()),
1937348 )
1938349 }
1939350
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> {
1941352 let to = || To::Community(community_id.to_string());
1942353 let mut broadcasts = vec![Broadcast::new(
1943354 to(),
@@ -1960,7 +371,7 @@ fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec<Broadcast
1960371 broadcasts
1961372 }
1962373
1963-async fn record_ghost_voice(
374+pub(crate) async fn record_ghost_voice(
1964375 user_id: &str,
1965376 community_id: &str,
1966377 seconds: u64,
@@ -1983,79 +394,78 @@ async fn record_ghost_voice(
1983394 mod tests {
1984395 use std::sync::Arc;
1985396
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+ };
1987405
1988406 use crate::{
407+ call::{Cx, Handle, Me},
1989408 database::{self, DB},
1990409 hub::{Client, Signed},
1991410 message,
1992- network::Services,
1993- request::handle,
411+ network::{Services, Shared},
412+ request::authenticated,
1994413 test,
1995414 };
1996415
1997- async fn send(
1998- request: LegacyRequest,
1999- client: &Client,
2000- db: &DB,
2001- services: &Services,
2002- ) -> Response {
2003- send_result(request, client, db, services)
2004- .await
2005- .expect("request failed")
416+ fn shared(db: &DB, services: &Services) -> Shared {
417+ Shared {
418+ db: db.clone(),
419+ services: services.clone(),
420+ directory: test::directory(),
421+ backups: test::directory(),
422+ }
2006423 }
2007424
2008- async fn send_result(
2009- request: LegacyRequest,
2010- client: &Client,
425+ async fn call<C: Handle>(
426+ call: C,
427+ client: &Arc<Client>,
2011428 db: &DB,
2012429 services: &Services,
2013- ) -> Result<Response, CommonError> {
2014- handle(
2015- request,
2016- client,
2017- db,
2018- services,
2019- &test::directory(),
2020- &test::directory(),
2021- )
2022- .await
2023- .0
430+ ) -> Result<C::Reply, CommonError> {
431+ let shared = shared(db, services);
432+ let conn = database::connect(db).await.unwrap();
433+ let me = authenticated(client, &conn).await?;
434+ let mut cx = Cx::new(client, &shared, conn);
435+
436+ Ok(call.handle(Me::User(me), &mut cx).await?)
2024437 }
2025438
2026439 async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc<Client> {
2027440 let guest = Client::detached(None);
2028- let Response::Session { user, token } = send(
2029- LegacyRequest::Register {
2030- username: username.to_string(),
2031- password: "password".to_string(),
2032- invite: None,
2033- },
2034- &guest,
2035- db,
2036- services,
2037- )
441+ let shared = shared(db, services);
442+ let conn = database::connect(db).await.unwrap();
443+ let mut cx = Cx::new(&guest, &shared, conn);
444+ let session = Register {
445+ username: username.to_string(),
446+ password: "password".to_string(),
447+ invite: None,
448+ }
449+ .handle(Me::Guest, &mut cx)
2038450 .await
2039- else {
2040- panic!("register failed");
2041- };
451+ .unwrap();
2042452
2043453 Client::detached(Some(Signed {
2044- user_id: user.id,
2045- token,
454+ user_id: session.user.id,
455+ token: session.token,
2046456 }))
2047457 }
2048458
2049459 async fn invite_and_accept(
2050460 community_id: &str,
2051- owner: &Client,
2052- member: &Client,
461+ owner: &Arc<Client>,
462+ member: &Arc<Client>,
2053463 username: &str,
2054464 db: &DB,
2055465 services: &Services,
2056466 ) {
2057- let Response::User(member_user) = send(
2058- LegacyRequest::FindUser {
467+ let member_user = call(
468+ FindUser {
2059469 username: username.to_string(),
2060470 },
2061471 owner,
@@ -2063,11 +473,9 @@ mod tests {
2063473 services,
2064474 )
2065475 .await
2066- else {
2067- panic!("user not found");
2068- };
2069- send(
2070- LegacyRequest::Invite {
476+ .unwrap();
477+ call(
478+ Invite {
2071479 community_id: community_id.to_string(),
2072480 user_id: member_user.id,
2073481 },
@@ -2075,16 +483,18 @@ mod tests {
2075483 db,
2076484 services,
2077485 )
2078- .await;
2079- send(
2080- LegacyRequest::AcceptInvitation {
486+ .await
487+ .unwrap();
488+ call(
489+ AcceptInvitation {
2081490 community_id: community_id.to_string(),
2082491 },
2083492 member,
2084493 db,
2085494 services,
2086495 )
2087- .await;
496+ .await
497+ .unwrap();
2088498 }
2089499
2090500 #[tokio::test]
@@ -2093,8 +503,8 @@ mod tests {
2093503 let services = Services::default();
2094504 let owner = signed_in("Owner", &db, &services).await;
2095505 let member = signed_in("Member", &db, &services).await;
2096- let Response::Community(community) = send(
2097- LegacyRequest::CreateCommunity {
506+ let community = call(
507+ CreateCommunity {
2098508 name: "The Community".to_string(),
2099509 },
2100510 &owner,
@@ -2102,13 +512,11 @@ mod tests {
2102512 &services,
2103513 )
2104514 .await
2105- else {
2106- panic!("community not created");
2107- };
515+ .unwrap();
2108516 invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await;
2109517
2110- let response = send_result(
2111- LegacyRequest::UpdateCommunity {
518+ let response = call(
519+ UpdateCommunity {
2112520 community_id: community.id,
2113521 name: "Renamed".to_string(),
2114522 },
@@ -2127,8 +535,8 @@ mod tests {
2127535 let services = Services::default();
2128536 let first = signed_in("First", &db, &services).await;
2129537 let second = signed_in("Second", &db, &services).await;
2130- let Response::User(first_user) = send(
2131- LegacyRequest::FindUser {
538+ let first_user = call(
539+ FindUser {
2132540 username: "First".to_string(),
2133541 },
2134542 &second,
@@ -2136,11 +544,9 @@ mod tests {
2136544 &services,
2137545 )
2138546 .await
2139- else {
2140- panic!("user not found");
2141- };
2142- let Response::User(second_user) = send(
2143- LegacyRequest::FindUser {
547+ .unwrap();
548+ let second_user = call(
549+ FindUser {
2144550 username: "Second".to_string(),
2145551 },
2146552 &first,
@@ -2148,38 +554,30 @@ mod tests {
2148554 &services,
2149555 )
2150556 .await
2151- else {
2152- panic!("user not found");
2153- };
2154- send(
2155- LegacyRequest::AddFriend {
557+ .unwrap();
558+ call(
559+ AddFriend {
2156560 user_id: second_user.id.clone(),
2157561 },
2158562 &first,
2159563 &db,
2160564 &services,
2161565 )
2162- .await;
2163- send(