use std::cmp::Reverse; use common::{ call::{ BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment, DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage, ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes, ListServerBans, ListUserFriends, ListUsers, Logout, PurgeUser, RemoveServerBan, RenameUser, ResetPassword, RestartServer, RevokeSessions, SearchCommunity, SearchMessages, SetCommunityVoice, SetGhost, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, UpdateServerSettings, WatchCommunity, }, constant::LOG_PAGE_LIMIT, error::Error, event::Event, model::{ Account, AdminAction, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, BanScope, Community, CommunitySummary, DayStat, InviteCode, LogAction, MessageHit, Overview, Rank, ServerBan, ServerBanKind, ServerSettings, User, }, permission, time::{self, MINUTE_MILLIS}, transport::Close, }; use crate::{ authentication, backup, call::shared::{ allowed, call_ended, delete_community, departed_all, ensure_editable, is_outsider, managed, message_event, messages_deleted, record_ghost_voice, shares_ended, voice_joined, }, call::user::user_updated, call::{Cx, Handle}, db::{ attachment, avatar::{self, Owner}, community, direct, friend, log, member, message, registration_code, server_ban, session, settings, stats, user, }, error::{ServerError, ensure}, publish::To, rooms::Left, }; const CODE_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; const CODE_LENGTH: usize = 8; fn generate_code() -> Result { let bytes = authentication::random_bytes::()?; Ok(bytes .iter() .map(|byte| char::from(CODE_ALPHABET[usize::from(*byte) % CODE_ALPHABET.len()])) .collect()) } impl Handle for Logout { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?; session::delete(signed.session_id, cx.db).await?; Ok(()) } } impl Handle for UpdateServerSettings { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let settings = self.settings; settings::update(&settings, cx.db).await?; log::record_admin( Some(me.id), None, None, &AdminAction::SettingsChanged, cx.db, ) .await?; if settings.maintenance { let builders = user::builder_ids(cx.db).await?; cx.sh .services .hub .kick_all_except(&builders, Close::Maintenance); } cx.emit(To::Everyone, Event::SettingsUpdated(settings.clone())); Ok(settings) } } impl Handle for RenameUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let target = managed(&me, self.user_id, cx.db).await?; let user = user::rename(self.user_id, &self.username, cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), None, &AdminAction::UserRenamed { from: target.username, }, cx.db, ) .await?; user_updated(&user, cx); Ok(user) } } impl Handle for CreateUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let user = authentication::create_account(&self.username, &self.password, cx.db).await?; log::record_admin( Some(me.id), Some(user.id), None, &AdminAction::UserCreated, cx.db, ) .await?; Ok(user) } } impl Handle for ListUsers { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { user::all_accounts(cx.db).await } } impl Handle for ListAdminLogs { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let admin = match self.action { Some(AdminActionKind::Community) => Vec::new(), action => { log::list_admin( self.actor_id, self.target_id, action, self.after_ms, self.before_ms, cx.db, ) .await? } }; let communities = match self.action { None | Some(AdminActionKind::Community) => { log::list_communities( self.actor_id, self.target_id, self.after_ms, self.before_ms, cx.db, ) .await? } Some(_) => Vec::new(), }; let mut entries = admin; entries.extend(communities); entries.sort_by_key(|entry| Reverse(entry.created_at)); entries.truncate(LOG_PAGE_LIMIT as usize); Ok(entries) } } impl Handle for ListUserFriends { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { Ok(friend::state(self.user_id, cx.db).await?.friends) } } impl Handle for GetDailyStats { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { stats::daily(self.days, cx.db).await } } impl Handle for GetOverview { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result { let (users, builders, communities, storage_bytes) = stats::counts(cx.db).await?; Ok(Overview { users, builders, communities, online: cx.sh.services.hub.online() as u64, voice: cx.sh.services.rooms.count() as u64, storage_bytes, }) } } impl Handle for SuspendUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; user::set_suspended(self.user_id, self.suspended, cx.db).await?; let action = if self.suspended { AdminAction::UserSuspended } else { AdminAction::UserUnsuspended }; log::record_admin(Some(me.id), Some(self.user_id), None, &action, cx.db).await?; if self.suspended { authentication::revoke_user(&cx.sh.services.hub, self.user_id, cx.db).await?; } Ok(()) } } impl Handle for RevokeSessions { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; authentication::revoke_user(&cx.sh.services.hub, self.user_id, cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), None, &AdminAction::SessionsRevoked, cx.db, ) .await?; Ok(()) } } impl Handle for ResetPassword { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; authentication::reset_password(self.user_id, &self.password, cx.db).await?; authentication::revoke_user(&cx.sh.services.hub, self.user_id, cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), None, &AdminAction::PasswordReset, cx.db, ) .await?; Ok(()) } } impl Handle for ClearProfile { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { managed(&me, self.user_id, cx.db).await?; avatar::set(Owner::User(self.user_id), None, cx.db).await?; let user = user::set_status(self.user_id, "", cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), None, &AdminAction::ProfileCleared, cx.db, ) .await?; user_updated(&user, cx); Ok(user) } } impl Handle for DeleteUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let user_id = self.user_id; let target = user::read(user_id, cx.db).await?; ensure(permission::can_delete_user( me.role, me.id == user_id, target.role, ))?; if permission::is_builder(me.role) && me.id != user_id { log::record_admin( Some(me.id), Some(user_id), None, &AdminAction::UserDeleted, cx.db, ) .await?; } cx.out .extend(departed_all(cx.sh.services.rooms.leave_user(user_id), cx.db).await?); for community_id in member::owned(user_id, cx.db).await? { delete_community(community_id, cx).await?; } for community_id in direct::communities_of(user_id, cx.db).await? { let member_ids = member::member_ids(community_id, cx.db).await?; delete_community(community_id, cx).await?; cx.emit(To::Users(member_ids), Event::UserDeleted { user_id }); } for community in community::communities_of(user_id, cx.db).await? { let member_ids = member::member_ids(community.id, cx.db).await?; cx.emit(To::Users(member_ids), Event::UserDeleted { user_id }); } user::delete(user_id, cx.db).await?; if me.id != user_id { cx.sh.services.hub.kick_user(user_id, Close::Revoked); } Ok(()) } } impl Handle for WatchCommunity { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Some(community_id) = self.community_id else { cx.client.watch(None); return Ok(()); }; allowed(&me, community_id, cx.db, permission::is_member).await?; let outsider = is_outsider(me.id, community_id, cx.db).await?; cx.client.watch(outsider.then_some(community_id)); let visit = permission::is_builder(me.role) && outsider && user::is_ghost(me.id, cx.db).await?; if visit && cx.client.first_visit(community_id) { let community = community::label(community_id, cx.db).await?; log::record_admin( Some(me.id), None, Some(&community), &AdminAction::GhostVisit, cx.db, ) .await?; } Ok(()) } } impl Handle for ListAllCommunities { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let mut summaries = Vec::new(); for community in community::groups(cx.db).await? { let members = member::members(community.id, cx.db).await?; let owner = members .iter() .find(|member| member.rank == Rank::Owner) .map(|member| member.user.clone()); summaries.push(CommunitySummary { community, owner, members: members.len() as u64, }); } Ok(summaries) } } impl Handle for TransferOwnership { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Self { community_id, user_id, } = self; ensure_editable(community_id, cx.db).await?; allowed(&me, community_id, cx.db, permission::is_owner).await?; let members = member::members(community_id, cx.db).await?; let target = members .iter() .find(|member| member.user.id == user_id) .ok_or(Error::NotFound)?; ensure(target.rank != Rank::Owner)?; let mut changes = vec![(user_id, Rank::Owner)]; if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) { member::set_rank(previous.user.id, community_id, Rank::Admin, cx.db).await?; log::record( community_id, Some(me.id), Some(previous.user.id), &LogAction::RankChanged { rank: Rank::Admin }, cx.db, ) .await?; changes.push((previous.user.id, Rank::Admin)); } member::set_rank(user_id, community_id, Rank::Owner, cx.db).await?; log::record( community_id, Some(me.id), Some(user_id), &LogAction::RankChanged { rank: Rank::Owner }, cx.db, ) .await?; if permission::is_builder(me.role) { let community = community::read(community_id, me.id, cx.db).await?; log::record_admin( Some(me.id), Some(user_id), Some(&community.name), &AdminAction::OwnershipTransferred, cx.db, ) .await?; } for (changed_id, rank) in changes { cx.emit( To::Community(community_id), Event::RankChanged { community_id, user_id: changed_id, rank, }, ); } Ok(()) } } impl Handle for TimeoutUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Self { user_id, minutes } = self; managed(&me, user_id, cx.db).await?; let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); user::set_timeout(user_id, until, cx.db).await?; if until.is_some() { authentication::revoke_user(&cx.sh.services.hub, user_id, cx.db).await?; } log::record_admin( Some(me.id), Some(user_id), None, &AdminAction::UserTimedOut { minutes }, cx.db, ) .await?; Ok(()) } } impl Handle for BanUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Self { user_id, reason, scope, } = self; let target = managed(&me, user_id, cx.db).await?; user::set_suspended(user_id, true, cx.db).await?; session::delete_all(user_id, cx.db).await?; server_ban::insert( ServerBanKind::Username, &target.username, reason.as_deref(), cx.db, ) .await?; if scope == BanScope::AccountAndIp && let Some(address) = user::last_ip(user_id, cx.db).await? { server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), cx.db).await?; } log::record_admin( Some(me.id), Some(user_id), None, &AdminAction::UserBanned { reason }, cx.db, ) .await?; cx.sh.services.hub.kick_user(user_id, Close::Banned); Ok(()) } } impl Handle for ListServerBans { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { server_ban::list(cx.db).await } } impl Handle for RemoveServerBan { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { server_ban::remove(self.id, cx.db).await?; log::record_admin(Some(me.id), None, None, &AdminAction::BanRemoved, cx.db).await?; Ok(()) } } impl Handle for CreateInviteCode { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let code = registration_code::create(&generate_code()?, self.uses, self.hours, cx.db).await?; log::record_admin(Some(me.id), None, None, &AdminAction::InviteCreated, cx.db).await?; Ok(code) } } impl Handle for ListInviteCodes { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { registration_code::list(cx.db).await } } impl Handle for DeleteInviteCode { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { registration_code::delete(&self.code, cx.db).await?; log::record_admin(Some(me.id), None, None, &AdminAction::InviteDeleted, cx.db).await?; Ok(()) } } impl Handle for SearchMessages { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { message::search( self.text.as_deref(), self.user_id, self.community_id, self.after_ms, self.before_ms, cx.db, ) .await } } impl Handle for SearchCommunity { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { allowed(&me, self.community_id, cx.db, permission::is_member).await?; message::search( Some(&self.text), None, Some(self.community_id), None, None, cx.db, ) .await } } impl Handle for PurgeUser { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let user_id = self.user_id; managed(&me, user_id, cx.db).await?; let deleted = message::delete_where_user(user_id, cx.db).await?; attachment::delete_uploads(user_id, cx.db).await?; log::record_admin( Some(me.id), Some(user_id), None, &AdminAction::UserPurged { messages: deleted.len() as u64, }, cx.db, ) .await?; cx.out.extend(messages_deleted(deleted)); Ok(()) } } impl Handle for ListAttachments { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { attachment::list(self.user_id, self.community_id, cx.db).await } } impl Handle for DeleteAttachment { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let stored = attachment::read(self.attachment_id, cx.db).await?; let community = community::label(stored.community_id, cx.db).await?; let mut message_ids = attachment::delete_file(self.attachment_id, cx.db).await?; log::record_admin( Some(me.id), Some(stored.uploader_id), Some(&community), &AdminAction::AttachmentDeleted, cx.db, ) .await?; message_ids.sort_unstable(); message_ids.dedup(); for message_id in message_ids { let updated = message::read(message_id, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); } Ok(()) } } impl Handle for GetStorageUsage { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result { let (users, communities) = attachment::usage(cx.db).await?; Ok(StorageUsage { users, communities }) } } impl Handle for CreateBackup { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let backup = backup::create(&cx.sh.db, &cx.sh.backups).await?; let action = AdminAction::BackupCreated { name: backup.name.clone(), }; log::record_admin(Some(me.id), None, None, &action, cx.db).await?; Ok(backup) } } impl Handle for ListBackups { async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { backup::list(&cx.sh.backups) } } impl Handle for DeleteBackup { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { backup::delete(&self.name, &cx.sh.backups)?; let action = AdminAction::BackupDeleted { name: self.name }; log::record_admin(Some(me.id), None, None, &action, cx.db).await?; Ok(()) } } impl Handle for SetCommunityVoice { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let Self { community_id, enabled, } = self; allowed(&me, community_id, cx.db, permission::is_owner).await?; community::set_voice_enabled(community_id, enabled, cx.db).await?; let updated = community::read(community_id, me.id, cx.db).await?; if permission::is_builder(me.role) { log::record_admin( Some(me.id), None, Some(&updated.name), &AdminAction::CommunityVoiceSet { enabled }, cx.db, ) .await?; } if !enabled { let rooms = &cx.sh.services.rooms; for user_id in rooms.room_users(community_id) { if !permission::is_builder(user::read(user_id, cx.db).await?.role) { cx.out.extend( departed_all(rooms.leave_room(community_id, user_id), cx.db).await?, ); } } } cx.emit( To::Community(community_id), Event::CommunityUpdated(updated.clone()), ); Ok(updated) } } impl Handle for RestartServer { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { tracing::info!("restart requested by {}", me.username); cx.sh.services.restart_soon(); Ok(()) } } impl Handle for SetGhost { async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let enabled = self.enabled; let rooms = &cx.sh.services.rooms; user::set_ghost(me.id, enabled, cx.db).await?; let action = if enabled { AdminAction::GhostEnabled } else { AdminAction::GhostDisabled }; log::record_admin(Some(me.id), None, None, &action, cx.db).await?; let outsider = match rooms.room_of(me.id) { Some(community_id) => is_outsider(me.id, community_id, cx.db).await?, None => false, }; if !outsider && let Some(mut departure) = rooms.set_ghost(me.id, enabled) { let community_id = departure.community_id; if enabled { cx.out.extend(shares_ended(&mut departure)); if let Left::Seated { call_log } = departure.left { cx.out .extend(call_ended(community_id, me.id, call_log, cx.db).await?); } cx.emit( To::CommunityExcept(community_id, me.id), Event::VoiceLeft { community_id, user_id: me.id, }, ); } else { let muted = user::voice_muted(me.id, cx.db).await?; cx.out.extend(voice_joined(community_id, me.id, muted)); if let Left::Ghost { seconds } = departure.left { record_ghost_voice(me.id, community_id, seconds, cx.db).await?; } } } Ok(()) } }