From 22b1bb749547306d0141d16b5073e40e78fc1e3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 26 Nov 2026 01:38:35 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20one=20clean=20?= =?UTF-8?q?schema,=20integer=20ids=20and=20one=20transaction=20per=20call?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The database layer is rebuilt on turso with one STRICT schema file in place of the migration list, integer ids, explicit created_at columns and settings, log actions and snippet polls stored as bitcode. A single connection runs every call inside one BEGIN IMMEDIATE transaction and events are published only on success. SQL lives only in db/, one file per table, through four helpers and one row reader; disk work for attachments moves to files.rs. Session tokens are stored hashed. Fixes case sensitive login against case insensitive uniqueness, logout leaving the connection signed in, user deletion failing inside a lone DM call, deleted DMs keeping their voice room, kicking non members, builders leaving owned groups ownerless, half applied multi step writes and events sent for failed calls. A stale database file now refuses to start instead of failing later. --- crates/client/Cargo.toml | 1 - crates/client/src/accounts.rs | 38 +- crates/client/src/gui.rs | 137 ++- crates/client/src/gui/auth.rs | 10 +- crates/client/src/gui/builder.rs | 21 +- crates/client/src/gui/builder/access.rs | 10 +- crates/client/src/gui/builder/backups.rs | 2 +- crates/client/src/gui/builder/communities.rs | 79 +- crates/client/src/gui/builder/log.rs | 34 +- crates/client/src/gui/builder/messages.rs | 37 +- crates/client/src/gui/builder/reports.rs | 40 +- crates/client/src/gui/builder/storage.rs | 15 +- crates/client/src/gui/builder/ui.rs | 6 +- crates/client/src/gui/builder/users.rs | 177 ++-- crates/client/src/gui/builder/voice.rs | 27 +- crates/client/src/gui/camera_view.rs | 38 +- crates/client/src/gui/chat.rs | 501 +++++------ crates/client/src/gui/community_settings.rs | 63 +- crates/client/src/gui/composer.rs | 78 +- crates/client/src/gui/forward.rs | 18 +- crates/client/src/gui/media_view.rs | 48 +- crates/client/src/gui/message_actions.rs | 50 +- crates/client/src/gui/poll.rs | 26 +- crates/client/src/gui/profile.rs | 108 ++- crates/client/src/gui/settings_page.rs | 2 +- crates/client/src/gui/share_view.rs | 43 +- crates/client/src/gui/sidebar.rs | 118 ++- crates/client/src/gui/snippet.rs | 15 +- crates/client/src/gui/social.rs | 67 +- crates/client/src/gui/voice_note.rs | 4 +- crates/client/src/gui/voice_stats.rs | 11 +- crates/client/src/gui/wave.rs | 34 +- crates/client/src/mutes.rs | 10 +- crates/client/src/net/link.rs | 10 +- crates/client/src/net/media.rs | 95 +- crates/client/src/net/mod.rs | 19 +- crates/client/src/settings.rs | 5 +- crates/client/src/share/session.rs | 3 +- crates/client/src/voice/engine.rs | 16 +- crates/client/src/voice/mod.rs | 3 +- crates/common/Cargo.toml | 1 - crates/common/src/call.rs | 180 ++-- crates/common/src/datagram.rs | 8 +- crates/common/src/event.rs | 47 +- crates/common/src/model.rs | 106 +-- crates/common/src/open.rs | 8 +- crates/common/src/share.rs | 4 +- crates/common/src/time.rs | 20 - crates/server/Cargo.toml | 4 +- crates/server/src/admin_log.rs | 117 --- crates/server/src/attachment.rs | 746 ---------------- crates/server/src/authentication.rs | 343 ++++---- crates/server/src/backup.rs | 62 +- crates/server/src/call/admin.rs | 503 +++++------ crates/server/src/call/community.rs | 233 +++-- crates/server/src/call/message.rs | 173 ++-- crates/server/src/call/mod.rs | 35 +- crates/server/src/call/social.rs | 170 ++-- crates/server/src/call/user.rs | 61 +- crates/server/src/call/voice.rs | 120 +-- crates/server/src/community.rs | 405 --------- crates/server/src/database.rs | 375 -------- crates/server/src/datagram.rs | 10 +- crates/server/src/db/attachment.rs | 268 ++++++ crates/server/src/db/avatar.rs | 52 ++ crates/server/src/db/community.rs | 182 ++++ crates/server/src/db/direct.rs | 47 + crates/server/src/db/friend.rs | 104 +++ crates/server/src/db/invitation.rs | 63 ++ crates/server/src/db/log.rs | 134 +++ crates/server/src/db/member.rs | 234 +++++ crates/server/src/db/message.rs | 513 +++++++++++ crates/server/src/db/mod.rs | 167 ++++ crates/server/src/db/poll.rs | 114 +++ crates/server/src/db/registration_code.rs | 60 ++ crates/server/src/db/report.rs | 126 +++ crates/server/src/db/schema.sql | 215 +++++ crates/server/src/db/server_ban.rs | 63 ++ crates/server/src/db/session.rs | 109 +++ crates/server/src/db/settings.rs | 26 + crates/server/src/db/snippet.rs | 94 ++ crates/server/src/db/stats.rs | 69 ++ crates/server/src/db/user.rs | 314 +++++++ crates/server/src/direct.rs | 51 -- crates/server/src/error.rs | 32 +- crates/server/src/files.rs | 497 +++++++++++ crates/server/src/friend.rs | 141 --- crates/server/src/hub.rs | 65 +- crates/server/src/invitation.rs | 72 -- crates/server/src/invite.rs | 89 -- crates/server/src/lib.rs | 45 +- crates/server/src/log.rs | 105 --- crates/server/src/message.rs | 860 ------------------- crates/server/src/network.rs | 136 +-- crates/server/src/notes.rs | 36 - crates/server/src/overview.rs | 36 - crates/server/src/publish.rs | 71 +- crates/server/src/report.rs | 92 -- crates/server/src/request.rs | 319 ++++--- crates/server/src/retention.rs | 112 +-- crates/server/src/rooms.rs | 155 ++-- crates/server/src/server_ban.rs | 80 -- crates/server/src/server_settings.rs | 71 -- crates/server/src/stats.rs | 61 -- crates/server/src/test.rs | 6 +- crates/server/src/user.rs | 555 ------------ crates/server/src/user_community.rs | 411 --------- 107 files changed, 5819 insertions(+), 6983 deletions(-) delete mode 100644 crates/server/src/admin_log.rs delete mode 100644 crates/server/src/attachment.rs delete mode 100644 crates/server/src/community.rs delete mode 100644 crates/server/src/database.rs create mode 100644 crates/server/src/db/attachment.rs create mode 100644 crates/server/src/db/avatar.rs create mode 100644 crates/server/src/db/community.rs create mode 100644 crates/server/src/db/direct.rs create mode 100644 crates/server/src/db/friend.rs create mode 100644 crates/server/src/db/invitation.rs create mode 100644 crates/server/src/db/log.rs create mode 100644 crates/server/src/db/member.rs create mode 100644 crates/server/src/db/message.rs create mode 100644 crates/server/src/db/mod.rs create mode 100644 crates/server/src/db/poll.rs create mode 100644 crates/server/src/db/registration_code.rs create mode 100644 crates/server/src/db/report.rs create mode 100644 crates/server/src/db/schema.sql create mode 100644 crates/server/src/db/server_ban.rs create mode 100644 crates/server/src/db/session.rs create mode 100644 crates/server/src/db/settings.rs create mode 100644 crates/server/src/db/snippet.rs create mode 100644 crates/server/src/db/stats.rs create mode 100644 crates/server/src/db/user.rs delete mode 100644 crates/server/src/direct.rs create mode 100644 crates/server/src/files.rs delete mode 100644 crates/server/src/friend.rs delete mode 100644 crates/server/src/invitation.rs delete mode 100644 crates/server/src/invite.rs delete mode 100644 crates/server/src/log.rs delete mode 100644 crates/server/src/message.rs delete mode 100644 crates/server/src/notes.rs delete mode 100644 crates/server/src/overview.rs delete mode 100644 crates/server/src/report.rs delete mode 100644 crates/server/src/server_ban.rs delete mode 100644 crates/server/src/server_settings.rs delete mode 100644 crates/server/src/stats.rs delete mode 100644 crates/server/src/user.rs delete mode 100644 crates/server/src/user_community.rs diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index eb3df60..3b61f4f 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -25,7 +25,6 @@ ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d9 ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ureq = "3.5.2" bytes = "1.12.2" -uuid = "1.29.3" tracing = "0.1.44" tracing-subscriber = "0.3.23" jiff = "1.0.2" diff --git a/crates/client/src/accounts.rs b/crates/client/src/accounts.rs index 1a244c5..46a3ffc 100644 --- a/crates/client/src/accounts.rs +++ b/crates/client/src/accounts.rs @@ -1,10 +1,10 @@ -use common::model::User; +use common::model::{Id, User}; use crate::{read_config, write_config}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Account { - pub user_id: String, + pub user_id: Id, pub username: String, pub token: String, } @@ -12,28 +12,28 @@ pub struct Account { #[derive(Debug, Clone, Default)] pub struct Accounts { pub list: Vec, - pub active: Option, + pub active: Option, } impl Accounts { - pub fn get(&self, user_id: &str) -> Option<&Account> { + pub fn get(&self, user_id: Id) -> Option<&Account> { self.list.iter().find(|account| account.user_id == user_id) } pub fn others(&self) -> impl Iterator { self.list .iter() - .filter(|account| Some(&account.user_id) != self.active.as_ref()) + .filter(|account| Some(account.user_id) != self.active) } pub fn sign_in(&mut self, user: &User, token: String) { - self.remove(&user.id); + self.remove(user.id); self.list.push(Account { - user_id: user.id.clone(), + user_id: user.id, username: user.username.clone(), token, }); - self.active = Some(user.id.clone()); + self.active = Some(user.id); save(self); } @@ -57,15 +57,15 @@ impl Accounts { save(self); } - pub fn forget(&mut self, user_id: &str) { + pub fn forget(&mut self, user_id: Id) { self.remove(user_id); - if self.active.as_deref() == Some(user_id) { + if self.active == Some(user_id) { self.active = None; } save(self); } - fn remove(&mut self, user_id: &str) { + fn remove(&mut self, user_id: Id) { self.list.retain(|account| account.user_id != user_id); } } @@ -78,12 +78,16 @@ pub fn load() -> Accounts { for line in content.lines() { match line.split('\t').collect::>().as_slice() { - ["active", user_id] => accounts.active = Some(user_id.to_string()), - [user_id, username, token] => accounts.list.push(Account { - user_id: user_id.to_string(), - username: username.to_string(), - token: token.to_string(), - }), + ["active", user_id] => accounts.active = user_id.parse().ok(), + [user_id, username, token] => { + if let Ok(user_id) = user_id.parse() { + accounts.list.push(Account { + user_id, + username: username.to_string(), + token: token.to_string(), + }); + } + } _ => {} } } diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 9e2e848..05e2d8e 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::{ collections::HashMap, fmt::Display, @@ -15,7 +16,6 @@ use common::{ BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, ServerSettings, Unread, User, mentions, }, - time::created_at_ms, }; use gpui_kit::{ Anchor, Animation, AnimationElement, AnimationExt, AnyElement, AnyWindowHandle, App, @@ -100,7 +100,7 @@ pub struct Palette { } impl Palette { - pub fn tinted(self, id: &str) -> Hsla { + pub fn tinted(self, id: Id) -> Hsla { let color = tint(id); if self.dark { color @@ -109,7 +109,7 @@ impl Palette { } } - pub fn for_community(self, community: Option<&Community>, hues: &HashMap) -> Self { + pub fn for_community(self, community: Option<&Community>, hues: &HashMap) -> Self { let Some(community) = community else { return self; }; @@ -120,7 +120,7 @@ impl Palette { let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) { Some(&hue) if self.dark => hsla(hue, 0.75, 0.55, 1.), Some(&hue) => hsla(hue, 0.75, 0.4, 1.), - None => self.tinted(id), + None => self.tinted(*id), }; Palette { accent, ..self } } @@ -216,13 +216,13 @@ pub fn sync_theme(cx: &mut App) { const FIND_KEY: &str = "ctrl-k"; pub const FIND_HINT: &str = "Ctrl K"; -pub fn tint(id: &str) -> Hsla { +pub fn tint(id: Id) -> Hsla { let mut hasher = DefaultHasher::new(); id.hash(&mut hasher); rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into() } -pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Rems) -> Div { +pub fn badge(palette: Palette, id: Id, name: &str, size: Pixels, font: Rems) -> Div { let initial = name .chars() .next() @@ -248,10 +248,10 @@ pub fn avatar( user: &User, size: Pixels, font: Rems, - avatars: &HashMap>, + avatars: &HashMap>, ) -> Div { let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else { - return badge(palette, &user.id, &user.username, size, font).rounded_full(); + return badge(palette, user.id, &user.username, size, font).rounded_full(); }; div() @@ -276,7 +276,7 @@ pub fn community_icon( community: &Community, size: Pixels, font: Rems, - avatars: &HashMap>, + avatars: &HashMap>, ) -> Div { match &community.kind { CommunityKind::Group => match community.avatar_id.as_ref().and_then(|id| avatars.get(id)) { @@ -286,10 +286,10 @@ pub fn community_icon( .rounded(px(4.)) .overflow_hidden() .child(img(image.clone()).size_full()), - None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)), + None => badge(palette, community.id, &community.name, size, font).rounded(px(4.)), }, CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars), - CommunityKind::Notes => badge(palette, &community.id, "Notes", size, font).rounded(px(4.)), + CommunityKind::Notes => badge(palette, community.id, "Notes", size, font).rounded(px(4.)), } } @@ -315,12 +315,6 @@ pub fn storage(bytes: u64) -> String { } } -pub fn id_time(id: &str, format: &str) -> String { - created_at_ms(id) - .map(|millis| millis_time(millis, format)) - .unwrap_or_default() -} - pub fn millis_time(millis: u64, format: &str) -> String { let Ok(timestamp) = Timestamp::from_millisecond(millis as i64) else { return String::new(); @@ -709,7 +703,7 @@ impl Yumush { ) { self.accounts.sign_in(&user, token); self.request_user_avatar(&user, cx); - self.chat.muted = mutes::load(&user.id); + self.chat.muted = mutes::load(user.id); self.user = Some(user); self.change_page(Route::Chat, window, cx); self.load_communities(window, cx); @@ -719,11 +713,11 @@ impl Yumush { pub(super) fn switch_account( &mut self, - user_id: String, + user_id: Id, window: &mut Window, cx: &mut Context, ) { - let Some(account) = self.accounts.get(&user_id).cloned() else { + let Some(account) = self.accounts.get(user_id).cloned() else { return; }; if !self.connection.is_connected() { @@ -741,7 +735,7 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| match result { Ok((user, token)) => yumush.enter_session(user, token, window, cx), Err(error @ Fail::Server(Error::NotFound | Error::Unauthenticated)) => { - yumush.accounts.forget(&account.user_id); + yumush.accounts.forget(account.user_id); window.push_notification(Notification::error(error.to_string()), cx); cx.notify(); } @@ -766,19 +760,19 @@ impl Yumush { .detach(); } - pub(super) fn forget_account(&mut self, user_id: &str, cx: &mut Context) { + pub(super) fn forget_account(&mut self, user_id: Id, cx: &mut Context) { self.accounts.forget(user_id); cx.notify(); } - pub(super) fn toggle_community_mute(&mut self, community_id: String, cx: &mut Context) { - let Some(me) = self.user.as_ref().map(|me| me.id.clone()) else { + pub(super) fn toggle_community_mute(&mut self, community_id: Id, cx: &mut Context) { + let Some(me) = self.user.as_ref().map(|me| me.id) else { return; }; if !self.chat.muted.remove(&community_id) { self.chat.muted.insert(community_id); } - mutes::save(&me, &self.chat.muted); + mutes::save(me, &self.chat.muted); cx.notify(); } @@ -786,7 +780,7 @@ impl Yumush { let Some(user) = self.user.clone() else { return; }; - self.accounts.forget(&user.id); + self.accounts.forget(user.id); self.end_session(window, cx); let network = self.network.clone(); @@ -871,45 +865,40 @@ impl Yumush { let icon = community_icon(palette, community, size, font, &self.chat.avatars); match &community.kind { CommunityKind::Direct { peer } => { - presence_avatar(icon, self.presence_of(&peer.id), size, palette) + presence_avatar(icon, self.presence_of(peer.id), size, palette) } CommunityKind::Group | CommunityKind::Notes => icon, } } - pub fn presence_of(&self, user_id: &str) -> Presence { + pub fn presence_of(&self, user_id: Id) -> Presence { if self.is_me(user_id) && !self.connection.is_connected() { return Presence::Offline; } self.chat .presences - .get(user_id) + .get(&user_id) .copied() .unwrap_or(Presence::Offline) } - pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context) { - if self.chat.avatars.contains_key(avatar_id) - || self.chat.avatar_requests.contains(avatar_id) + pub fn request_avatar(&mut self, avatar_id: Id, cx: &mut Context) { + if self.chat.avatars.contains_key(&avatar_id) + || self.chat.avatar_requests.contains(&avatar_id) { return; } - self.chat.avatar_requests.insert(avatar_id.to_string()); + self.chat.avatar_requests.insert(avatar_id); let network = self.network.clone(); - let avatar_id = avatar_id.to_string(); cx.spawn(async move |this, cx| { - let result = network - .call(GetAvatar { - avatar_id: avatar_id.clone(), - }) - .await; + let result = network.call(GetAvatar { avatar_id }).await; let _ = this.update(cx, |yumush, cx| { yumush.chat.avatar_requests.remove(&avatar_id); if let Ok(bytes) = result { if let Some(hue) = crate::avatar::dominant_hue(&bytes) { - yumush.chat.hues.insert(avatar_id.clone(), hue); + yumush.chat.hues.insert(avatar_id, hue); } yumush.chat.avatars.insert( avatar_id, @@ -923,7 +912,7 @@ impl Yumush { } pub fn request_user_avatar(&mut self, user: &User, cx: &mut Context) { - if let Some(avatar_id) = &user.avatar_id { + if let Some(avatar_id) = user.avatar_id { self.request_avatar(avatar_id, cx); } } @@ -932,7 +921,7 @@ impl Yumush { match &event { Event::MemberJoined { member, .. } => self.request_user_avatar(&member.user, cx), Event::UserUpdated(user) => { - if self.is_me(&user.id) { + if self.is_me(user.id) { self.user = Some(user.clone()); self.accounts.rename(user); if !self.is_builder() && self.chat.view == View::Builder { @@ -944,13 +933,13 @@ impl Yumush { Event::VoiceLeft { community_id, user_id, - } if self.is_me(user_id) => self.leave_voice_in(community_id, cx), + } if self.is_me(*user_id) => self.leave_voice_in(*community_id, cx), Event::VoiceMuted { user_id, muted: true, .. - } if self.is_me(user_id) => self.set_muted(true, cx), - Event::ShareStopped { user_id, kind, .. } if self.is_watching(user_id, *kind) => { + } if self.is_me(*user_id) => self.set_muted(true, cx), + Event::ShareStopped { user_id, kind, .. } if self.is_watching(*user_id, *kind) => { self.close_viewer(cx) } Event::Typing { .. } => { @@ -963,17 +952,15 @@ impl Yumush { _ => {} } self.chat - .apply_event(event, self.user.as_ref().map(|user| user.id.as_str())); + .apply_event(event, self.user.as_ref().map(|user| user.id)); self.request_authors(cx); self.request_social_avatars(cx); self.request_media(cx); } - fn mark_read(&mut self, community_id: &str, message_id: &str, cx: &mut Context) { + fn mark_read(&mut self, community_id: Id, message_id: Id, cx: &mut Context) { self.chat.mark_read(community_id, message_id); let network = self.network.clone(); - let community_id = community_id.to_string(); - let message_id = message_id.to_string(); cx.spawn(async move |_, _| { let _ = network @@ -987,10 +974,10 @@ impl Yumush { } fn read_selected(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; - let Some(message_id) = self.chat.messages.last().map(|message| message.id.clone()) else { + let Some(message_id) = self.chat.messages.last().map(|message| message.id) else { return; }; if self @@ -999,7 +986,7 @@ impl Yumush { .get(&community_id) .is_some_and(|unread| unread.messages > 0) { - self.mark_read(&community_id, &message_id, cx); + self.mark_read(community_id, message_id, cx); } } @@ -1010,16 +997,16 @@ impl Yumush { if message.user_id == me.id { return; } - if active && self.chat.is_selected(&message.community_id) { - self.mark_read(&message.community_id, &message.id, cx); + if active && self.chat.is_selected(message.community_id) { + self.mark_read(message.community_id, message.id, cx); return; } let unread = self .chat .unread - .entry(message.community_id.clone()) + .entry(message.community_id) .or_insert_with(|| Unread { - community_id: message.community_id.clone(), + community_id: message.community_id, ..Default::default() }); unread.messages += 1; @@ -1032,22 +1019,22 @@ impl Yumush { let Some(me) = self.user.as_ref() else { return false; }; - let viewing = active && self.chat.is_selected(&message.community_id); + let viewing = active && self.chat.is_selected(message.community_id); message.user_id != me.id && message.call.is_none() && !self.chat.muted.contains(&message.community_id) - && self.presence_of(&me.id) == Presence::Online + && self.presence_of(me.id) == Presence::Online && !viewing } - fn starts_call(&self, community_id: &str, user_id: &str) -> bool { + fn starts_call(&self, community_id: Id, user_id: Id) -> bool { !self.is_me(user_id) && self.chat.voice_ids(community_id).is_empty() && self.is_direct(community_id) } - fn ends_call(&self, community_id: &str, user_id: &str) -> bool { + fn ends_call(&self, community_id: Id, user_id: Id) -> bool { !self.is_me(user_id) && self.chat.in_voice(community_id) && self.is_direct(community_id) @@ -1055,17 +1042,17 @@ impl Yumush { .chat .voice_ids(community_id) .iter() - .all(|id| id == user_id || self.is_me(id)) + .all(|id| *id == user_id || self.is_me(*id)) } - pub(super) fn is_direct(&self, community_id: &str) -> bool { + pub(super) fn is_direct(&self, community_id: Id) -> bool { self.chat .communities() .iter() .any(|community| community.id == community_id && community.kind.is_direct()) } - fn is_me(&self, user_id: &str) -> bool { + fn is_me(&self, user_id: Id) -> bool { self.user.as_ref().is_some_and(|me| me.id == user_id) } @@ -1148,7 +1135,7 @@ impl Yumush { self.load_server_settings(window, cx); if self.user.is_some() { self.reload(window, cx); - } else if let Some(active) = self.accounts.active.clone() { + } else if let Some(active) = self.accounts.active { self.switch_account(active, window, cx); } } @@ -1157,7 +1144,7 @@ impl Yumush { NetworkEvent::VoiceEnded => self.chat.set_voice_off(), NetworkEvent::SessionLost => { if let Some(user) = &self.user { - self.accounts.forget(&user.id); + self.accounts.forget(user.id); } self.end_session(window, cx); } @@ -1165,9 +1152,9 @@ impl Yumush { Event::MemberLeft { community_id, user_id, - } if self.is_me(&user_id) => { - self.leave_voice_in(&community_id, cx); - self.chat.remove_community(&community_id); + } if self.is_me(user_id) => { + self.leave_voice_in(community_id, cx); + self.chat.remove_community(community_id); } Event::Removed { community_id, @@ -1175,8 +1162,8 @@ impl Yumush { sanction, reason, } => { - self.leave_voice_in(&community_id, cx); - self.chat.remove_community(&community_id); + self.leave_voice_in(community_id, cx); + self.chat.remove_community(community_id); let action = match sanction { Sanction::Ban => "Banned from", Sanction::Kick => "Kicked from", @@ -1188,7 +1175,7 @@ impl Yumush { window.push_notification(Notification::warning(text), cx); } Event::CommunityDeleted { community_id } => { - self.leave_voice_in(&community_id, cx); + self.leave_voice_in(community_id, cx); self.apply_pushed(Event::CommunityDeleted { community_id }, cx); } Event::ReportCreated => self.report_created(window, cx), @@ -1220,7 +1207,7 @@ impl Yumush { } self.count_message(message, active, cx); if message.call == Some(CallLog::Declined) - && self.chat.in_voice(&message.community_id) + && self.chat.in_voice(message.community_id) { self.end_voice(cx); } @@ -1228,13 +1215,13 @@ impl Yumush { Event::VoiceJoined { community_id, user_id, - } if self.starts_call(community_id, user_id) => { - self.chat.ringing.insert(community_id.clone()); + } if self.starts_call(*community_id, *user_id) => { + self.chat.ringing.insert(*community_id); } Event::VoiceLeft { community_id, user_id, - } if self.ends_call(community_id, user_id) => { + } if self.ends_call(*community_id, *user_id) => { self.end_voice(cx); } _ => {} diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index 84f8b4f..5bc89ac 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -174,8 +174,8 @@ impl Yumush { .map(|account| { let switch_entity = entity.clone(); let forget_entity = entity.clone(); - let switch_id = account.user_id.clone(); - let forget_id = account.user_id.clone(); + let switch_id = account.user_id; + let forget_id = account.user_id; hoverable( format!("saved_{}", account.user_id), @@ -189,7 +189,7 @@ impl Yumush { .child( badge( palette, - &account.user_id, + account.user_id, &account.username, px(22.), text(11.), @@ -204,7 +204,7 @@ impl Yumush { move |_, cx| { cx.stop_propagation(); forget_entity.update(cx, |yumush, cx| { - yumush.forget_account(&forget_id, cx) + yumush.forget_account(forget_id, cx) }); }, ) @@ -221,7 +221,7 @@ impl Yumush { ) .on_click(move |_, window, cx| { switch_entity.update(cx, |yumush, cx| { - yumush.switch_account(switch_id.clone(), window, cx) + yumush.switch_account(switch_id, window, cx) }) }) .into_any_element() diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 858a3bb..183caf0 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -11,6 +11,7 @@ mod ui; mod users; mod voice; +use common::model::Id; use std::{fmt::Display, future::Future, path::PathBuf}; use common::{ @@ -99,9 +100,9 @@ impl BuilderTab { } pub(super) struct Transfer { - pub(super) community_id: String, + pub(super) community_id: Id, pub(super) members: Vec, - pub(super) pending: Option, + pub(super) pending: Option, } impl Yumush { @@ -405,15 +406,15 @@ impl Yumush { } } - fn resolve_user(&self, username: &str) -> Option { + fn resolve_user(&self, username: &str) -> Option { self.chat .builder_users .iter() .find(|account| account.user.username.to_lowercase() == username) - .map(|account| account.user.id.clone()) + .map(|account| account.user.id) } - fn resolve_community(&self, name: &str) -> Option { + fn resolve_community(&self, name: &str) -> Option { self.chat .builder_communities .iter() @@ -421,14 +422,10 @@ impl Yumush { summary.community.kind == CommunityKind::Group && summary.community.name.to_lowercase() == name }) - .map(|summary| summary.community.id.clone()) + .map(|summary| summary.community.id) } - pub(super) fn filter_user( - &self, - input: &Entity, - cx: &App, - ) -> Option> { + pub(super) fn filter_user(&self, input: &Entity, cx: &App) -> Option> { let name = search_text(input, cx); if name.is_empty() { return Some(None); @@ -440,7 +437,7 @@ impl Yumush { &self, input: &Entity, cx: &App, - ) -> Option> { + ) -> Option> { let name = search_text(input, cx); if name.is_empty() { return Some(None); diff --git a/crates/client/src/gui/builder/access.rs b/crates/client/src/gui/builder/access.rs index 74222c4..54d2773 100644 --- a/crates/client/src/gui/builder/access.rs +++ b/crates/client/src/gui/builder/access.rs @@ -1,3 +1,4 @@ +use common::model::Id; use common::{ call::{CreateInviteCode, DeleteInviteCode, ListInviteCodes, ListServerBans, RemoveServerBan}, model::{InviteCode, ServerBan, ServerBanKind}, @@ -102,7 +103,7 @@ fn invite_row( } fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { - let remove_id = ban.id.clone(); + let remove_id = ban.id; let kind = match ban.kind { ServerBanKind::Ip => "IP", ServerBanKind::Username => "Username", @@ -143,7 +144,7 @@ fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.remove_ban(&remove_id, window, cx) + yumush.remove_ban(remove_id, window, cx) }), )) } @@ -211,7 +212,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_invite_delete, code) { + if !confirmed(&mut self.chat.pending_invite_delete, code.to_string()) { cx.notify(); return; } @@ -234,9 +235,8 @@ impl Yumush { cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); } - pub(super) fn remove_ban(&mut self, id: &str, window: &mut Window, cx: &mut Context) { + pub(super) fn remove_ban(&mut self, id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); - let id = id.to_string(); cx.spawn_in(window, async move |this, cx| { match network.call(RemoveServerBan { id }).await { diff --git a/crates/client/src/gui/builder/backups.rs b/crates/client/src/gui/builder/backups.rs index 9da8c1b..69cbed9 100644 --- a/crates/client/src/gui/builder/backups.rs +++ b/crates/client/src/gui/builder/backups.rs @@ -145,7 +145,7 @@ impl Yumush { } fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context) { - if !confirmed(&mut self.pending_backup_delete, name) { + if !confirmed(&mut self.pending_backup_delete, name.to_string()) { cx.notify(); return; } diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs index f7efe47..8e0029e 100644 --- a/crates/client/src/gui/builder/communities.rs +++ b/crates/client/src/gui/builder/communities.rs @@ -1,3 +1,4 @@ +use common::model::Id; use common::{ call::{ DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, SetCommunityVoice, @@ -22,13 +23,12 @@ use crate::gui::{ impl Yumush { pub(super) fn set_builder_community_voice( &mut self, - community_id: &str, + community_id: Id, enabled: bool, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); - let community_id = community_id.to_string(); cx.spawn_in(window, async move |this, cx| { match network @@ -56,7 +56,7 @@ impl Yumush { |network| async move { network.call(ListAllCommunities).await }, |yumush, summaries, cx| { for summary in &summaries { - if let Some(avatar_id) = &summary.community.avatar_id { + if let Some(avatar_id) = summary.community.avatar_id { yumush.request_avatar(avatar_id, cx); } if let Some(owner) = &summary.owner { @@ -71,7 +71,7 @@ impl Yumush { pub(super) fn delete_builder_community( &mut self, - community_id: &str, + community_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -80,18 +80,12 @@ impl Yumush { return; } let network = self.network.clone(); - let community_id = community_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network - .call(DeleteCommunity { - community_id: community_id.clone(), - }) - .await - { + match network.call(DeleteCommunity { community_id }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.remove_community(&community_id); + yumush.chat.remove_community(community_id); yumush.load_builder_communities(window, cx); }); } @@ -103,7 +97,7 @@ impl Yumush { pub(super) fn open_transfer( &mut self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -118,7 +112,7 @@ impl Yumush { return; } self.chat.transfer = Some(Transfer { - community_id: community_id.clone(), + community_id, members: Vec::new(), pending: None, }); @@ -128,19 +122,14 @@ impl Yumush { pub(super) fn load_transfer_members( &self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let members = match network - .call(ListMembers { - community_id: community_id.clone(), - }) - .await - { + let members = match network.call(ListMembers { community_id }).await { Ok(members) => members, Err(error) => { notify_error(&this, cx, error); @@ -175,19 +164,14 @@ impl Yumush { .iter() .filter(|member| member.rank != Rank::Owner) .map(|member| { - let pending = transfer.pending.as_deref() == Some(member.user.id.as_str()); + let pending = transfer.pending == Some(member.user.id); self.transfer_row(member, pending, entity, palette) .into_any_element() }) .collect() } - pub(super) fn transfer_to( - &mut self, - user_id: &str, - window: &mut Window, - cx: &mut Context, - ) { + pub(super) fn transfer_to(&mut self, user_id: Id, window: &mut Window, cx: &mut Context) { let Some(transfer) = self.chat.transfer.as_mut() else { return; }; @@ -196,9 +180,8 @@ impl Yumush { cx.notify(); return; } - let community_id = transfer.community_id.clone(); + let community_id = transfer.community_id; let network = self.network.clone(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { match network @@ -222,7 +205,7 @@ impl Yumush { pub(super) fn jump_to( &mut self, - community_id: String, + community_id: Id, voice: bool, window: &mut Window, cx: &mut Context, @@ -259,14 +242,14 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let community_id = community.id.clone(); - if self.chat.joined(&community_id) { + let community_id = community.id; + if self.chat.joined(community_id) { let direct = community.kind.is_direct(); - self.go_to_community(community_id.clone(), direct, window, cx); + self.go_to_community(community_id, direct, window, cx); } else { self.open_builder_community(community, window, cx); } - if voice && !self.chat.in_voice(&community_id) { + if voice && !self.chat.in_voice(community_id) { self.toggle_voice(community_id, window, cx); } } @@ -277,7 +260,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let community_id = community.id.clone(); + let community_id = community.id; self.chat.opened = Some(community); self.show_view(View::Chat, window, cx); self.select_community(community_id, window, cx); @@ -332,7 +315,7 @@ impl Yumush { entity: &Entity, palette: Palette, ) -> Div { - let user_id = member.user.id.clone(); + let user_id = member.user.id; div() .h(px(40.)) @@ -369,7 +352,7 @@ impl Yumush { if pending { "Confirm" } else { "Transfer" }, palette, entity_action(entity, move |yumush, window, cx| { - yumush.transfer_to(&user_id, window, cx) + yumush.transfer_to(user_id, window, cx) }), )) } @@ -382,13 +365,13 @@ impl Yumush { ) -> Div { let community = &summary.community; let opened = community.clone(); - let id = community.id.clone(); - let log_id = id.clone(); - let transfer_id = id.clone(); - let delete_id = id.clone(); - let voice_id = id.clone(); + let id = community.id; + let log_id = id; + let transfer_id = id; + let delete_id = id; + let voice_id = id; let voice_enabled = community.voice_enabled; - let pending_delete = self.chat.pending_community_delete.as_deref() == Some(id.as_str()); + let pending_delete = self.chat.pending_community_delete == Some(id); let expanded = self .chat .transfer @@ -453,7 +436,7 @@ impl Yumush { palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.show_logs(log_id.clone(), window, cx) + yumush.show_logs(log_id, window, cx) }), )) .child(icon_button( @@ -471,7 +454,7 @@ impl Yumush { palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.set_builder_community_voice(&voice_id, !voice_enabled, window, cx) + yumush.set_builder_community_voice(voice_id, !voice_enabled, window, cx) }), )) .child(icon_button( @@ -485,7 +468,7 @@ impl Yumush { }, palette, entity_action(entity, move |yumush, window, cx| { - yumush.open_transfer(transfer_id.clone(), window, cx) + yumush.open_transfer(transfer_id, window, cx) }), )) .child( @@ -504,7 +487,7 @@ impl Yumush { }, palette, entity_action(entity, move |yumush, window, cx| { - yumush.delete_builder_community(&delete_id, window, cx) + yumush.delete_builder_community(delete_id, window, cx) }), ) .when(pending_delete, |this| this.bg(palette.danger)), diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index e1c72b3..2030dad 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -1,7 +1,7 @@ use common::{ call::ListAdminLogs, - model::{AdminAction, AdminLogEntry, action_detail}, - time::{created_at_ms, now_ms}, + model::{AdminAction, AdminActionKind, AdminLogEntry}, + time::now_ms, }; use gpui_kit::{ AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, @@ -21,7 +21,7 @@ use crate::gui::STAMP; use crate::gui::{ Palette, Yumush, community_settings::user_name, - entity_action, id_time, millis_time, notify_error, text, + entity_action, millis_time, notify_error, text, widget::{field, search_text}, }; @@ -86,6 +86,24 @@ fn builder_log_text(entry: &AdminLogEntry) -> String { } } +fn action_detail(action: &AdminAction) -> Option { + match action { + AdminAction::RoleChanged { role } => Some(role.as_str().to_string()), + AdminAction::UserRenamed { from } => Some(from.clone()), + AdminAction::UserTimedOut { minutes } => Some(minutes.to_string()), + AdminAction::UserBanned { reason } => reason.clone(), + AdminAction::ReportHandled { status } => Some(status.as_str().to_string()), + AdminAction::UserPurged { messages } => Some(messages.to_string()), + AdminAction::VoiceMuted { muted } => Some(muted.to_string()), + AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()), + AdminAction::GhostVoice { seconds } => Some(seconds.to_string()), + AdminAction::BackupCreated { name } + | AdminAction::BackupDeleted { name } + | AdminAction::BackupDownloaded { name } => Some(name.clone()), + _ => None, + } +} + fn csv_field(text: &str) -> String { format!("\"{}\"", text.replace('"', "\"\"")) } @@ -93,8 +111,8 @@ fn csv_field(text: &str) -> String { fn builder_log_csv(entries: &[AdminLogEntry]) -> String { let mut lines = vec!["time,actor,action,target,community,detail".to_string()]; for entry in entries { - let time = created_at_ms(&entry.id) - .and_then(|millis| Timestamp::from_millisecond(millis as i64).ok()) + let time = Timestamp::from_millisecond(entry.created_at as i64) + .ok() .map(|timestamp| timestamp.to_string()) .unwrap_or_default(); let actor = entry @@ -108,7 +126,7 @@ fn builder_log_csv(entries: &[AdminLogEntry]) -> String { let fields = [ time, actor, - entry.action.name().to_string(), + entry.action.kind().as_str().to_string(), target, entry.community.clone().unwrap_or_default(), action_detail(&entry.action).unwrap_or_default(), @@ -185,7 +203,7 @@ fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { div() .text_size(text(11.)) .text_color(palette.muted) - .child(id_time(&entry.id, STAMP)), + .child(millis_time(entry.created_at, STAMP)), ), ) .children( @@ -215,7 +233,7 @@ impl Yumush { .selected_value() .copied() .filter(|name| *name != "All") - .map(str::to_string); + .and_then(AdminActionKind::parse); let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx)); let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx)); self.fetch_builder( diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs index 84b734c..bd5012f 100644 --- a/crates/client/src/gui/builder/messages.rs +++ b/crates/client/src/gui/builder/messages.rs @@ -1,3 +1,4 @@ +use common::model::Id; use common::{ call::{DeleteMessage, SearchMessages}, model::MessageHit, @@ -19,7 +20,7 @@ use crate::gui::YEAR_STAMP; use crate::gui::{ Palette, Yumush, avatar, community_settings::user_name, - entity_action, id_time, notify_error, + entity_action, millis_time, notify_error, profile::user_link, text, widget::{field, search_text}, @@ -33,8 +34,8 @@ fn message_hit_row( entity: &Entity, palette: Palette, ) -> Div { - let message_id = hit.message.id.clone(); - let community_id = hit.message.community_id.clone(); + let message_id = hit.message.id; + let community_id = hit.message.community_id; let open = icon_button( format!("open_message_{}", hit.message.id), IconName::MessageSquare, @@ -42,7 +43,7 @@ fn message_hit_row( palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.jump_to(community_id.clone(), false, window, cx) + yumush.jump_to(community_id, false, window, cx) }), ); let delete = delete_icon_button( @@ -50,11 +51,11 @@ fn message_hit_row( pending, palette, entity_action(entity, move |yumush, window, cx| { - yumush.delete_builder_message(&message_id, window, cx) + yumush.delete_builder_message(message_id, window, cx) }), ); let purge = hit.author.as_ref().map(|author| { - let user_id = author.id.clone(); + let user_id = author.id; icon_button( format!("purge_message_user_{}", hit.message.id), IconName::UserX, @@ -66,7 +67,7 @@ fn message_hit_row( palette.danger, palette, entity_action(entity, move |yumush, window, cx| { - yumush.purge_builder_user(&user_id, window, cx) + yumush.purge_builder_user(user_id, window, cx) }), ) .when(purge_pending, |this| { @@ -118,7 +119,7 @@ fn message_hit_row( .flex_shrink_0() .text_size(text(11.)) .text_color(palette.muted) - .child(id_time(&hit.message.id, YEAR_STAMP)), + .child(millis_time(hit.message.created_at, YEAR_STAMP)), ), ) .child( @@ -186,11 +187,11 @@ impl Yumush { .builder_messages .iter() .map(|hit| { - let pending = - self.chat.pending_message_delete.as_deref() == Some(hit.message.id.as_str()); - let purge_pending = hit.author.as_ref().is_some_and(|author| { - self.chat.pending_builder_purge.as_deref() == Some(author.id.as_str()) - }); + let pending = self.chat.pending_message_delete == Some(hit.message.id); + let purge_pending = hit + .author + .as_ref() + .is_some_and(|author| self.chat.pending_builder_purge == Some(author.id)); let picture = match &hit.author { Some(author) => avatar(palette, author, px(28.), text(11.), &self.chat.avatars), None => div() @@ -253,7 +254,7 @@ impl Yumush { pub(super) fn delete_builder_message( &mut self, - message_id: &str, + message_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -262,15 +263,9 @@ impl Yumush { return; } let network = self.network.clone(); - let message_id = message_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network - .call(DeleteMessage { - message_id: message_id.clone(), - }) - .await - { + match network.call(DeleteMessage { message_id }).await { Ok(()) => { let _ = this.update(cx, |yumush, cx| { yumush diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index 138d603..4fb8dea 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::future::Future; use common::{ @@ -15,7 +16,7 @@ use crate::{ gui::{ Palette, Yumush, avatar, badge, clickable, community_settings::user_name, - entity_action, id_time, notify_error, + entity_action, millis_time, notify_error, profile::user_link, settings_page::{segment, segment_track}, text, @@ -108,12 +109,11 @@ impl Yumush { pub(super) fn handle_report( &mut self, - report_id: &str, + report_id: Id, status: ReportStatus, window: &mut Window, cx: &mut Context, ) { - let report_id = report_id.to_string(); self.report_action(window, cx, move |network| async move { network.call(HandleReport { report_id, status }).await }); @@ -121,11 +121,10 @@ impl Yumush { pub(super) fn delete_report_message( &mut self, - message_id: &str, + message_id: Id, window: &mut Window, cx: &mut Context, ) { - let message_id = message_id.to_string(); self.report_action(window, cx, move |network| async move { network.call(DeleteMessage { message_id }).await }); @@ -133,11 +132,10 @@ impl Yumush { pub(super) fn timeout_report_target( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); self.report_action(window, cx, move |network| async move { network .call(TimeoutUser { @@ -150,12 +148,11 @@ impl Yumush { pub(super) fn ban_report_target( &mut self, - user_id: &str, + user_id: Id, reason: &str, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); let reason = reason.to_string(); self.report_action(window, cx, move |network| async move { network @@ -213,7 +210,7 @@ impl Yumush { Some(user) => { avatar(palette, user, px(20.), text(9.), &self.chat.avatars).into_any_element() } - None => badge(palette, &report.id, "someone", px(20.), text(9.)).into_any_element(), + None => badge(palette, report.id, "someone", px(20.), text(9.)).into_any_element(), }; let head = div() .flex_1() @@ -259,7 +256,7 @@ impl Yumush { .child(format!( "{} · {}", report.community.as_deref().unwrap_or("deleted community"), - id_time(&report.id, STAMP) + millis_time(report.created_at, STAMP) )); let actions = self.report_actions(report, entity, palette); let handled = (report.status != ReportStatus::Open).then(|| { @@ -320,15 +317,15 @@ impl Yumush { if report.status != ReportStatus::Open { return Vec::new(); } - let resolve_id = report.id.clone(); - let dismiss_id = report.id.clone(); + let resolve_id = report.id; + let dismiss_id = report.id; let mut buttons = vec![ plain_button( format!("resolve_report_{}", report.id), "Resolve", palette, entity_action(entity, move |yumush, window, cx| { - yumush.handle_report(&resolve_id, ReportStatus::Resolved, window, cx) + yumush.handle_report(resolve_id, ReportStatus::Resolved, window, cx) }), ) .into_any_element(), @@ -337,28 +334,27 @@ impl Yumush { "Dismiss", palette, entity_action(entity, move |yumush, window, cx| { - yumush.handle_report(&dismiss_id, ReportStatus::Dismissed, window, cx) + yumush.handle_report(dismiss_id, ReportStatus::Dismissed, window, cx) }), ) .into_any_element(), ]; - if let (Some(message_id), Some(_)) = (&report.message_id, &report.community_id) { - let message_id = message_id.clone(); + if let (Some(message_id), Some(_)) = (report.message_id, report.community_id) { buttons.push( plain_button( format!("delete_report_message_{}", report.id), "Delete message", palette, entity_action(entity, move |yumush, window, cx| { - yumush.delete_report_message(&message_id, window, cx) + yumush.delete_report_message(message_id, window, cx) }), ) .into_any_element(), ); } if let Some(target) = &report.target { - let timeout_id = target.id.clone(); - let ban_id = target.id.clone(); + let timeout_id = target.id; + let ban_id = target.id; let ban_reason = report.reason.clone(); buttons.push( plain_button( @@ -366,7 +362,7 @@ impl Yumush { "Timeout 1h", palette, entity_action(entity, move |yumush, window, cx| { - yumush.timeout_report_target(&timeout_id, window, cx) + yumush.timeout_report_target(timeout_id, window, cx) }), ) .into_any_element(), @@ -377,7 +373,7 @@ impl Yumush { "Ban", palette, entity_action(entity, move |yumush, window, cx| { - yumush.ban_report_target(&ban_id, &ban_reason, window, cx) + yumush.ban_report_target(ban_id, &ban_reason, window, cx) }), ) .into_any_element(), diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index af30b98..34970a7 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -1,3 +1,4 @@ +use common::model::Id; use common::{ call::{DeleteAttachment, ListAttachments}, model::AttachmentInfo, @@ -16,7 +17,7 @@ use super::ui::{ toolbar, }; use crate::gui::{ - DATE, Palette, Yumush, community_settings::user_name, entity_action, id_time, notify_error, + DATE, Palette, Yumush, community_settings::user_name, entity_action, millis_time, notify_error, storage, text, widget::field, }; @@ -85,13 +86,13 @@ fn attachment_row( entity: &Entity, palette: Palette, ) -> Div { - let attachment_id = info.attachment.id.clone(); + let attachment_id = info.attachment.id; let delete = delete_icon_button( format!("delete_attachment_{}", info.attachment.id), pending, palette, entity_action(entity, move |yumush, window, cx| { - yumush.delete_builder_attachment(&attachment_id, window, cx) + yumush.delete_builder_attachment(attachment_id, window, cx) }), ); @@ -126,7 +127,7 @@ fn attachment_row( "{} · {} · {}", user_name(&info.uploader), info.community, - id_time(&info.attachment.id, DATE) + millis_time(info.attachment.created_at, DATE) )), ), ) @@ -220,8 +221,7 @@ impl Yumush { .builder_attachments .iter() .map(|info| { - let pending = self.chat.pending_attachment_delete.as_deref() - == Some(info.attachment.id.as_str()); + let pending = self.chat.pending_attachment_delete == Some(info.attachment.id); attachment_row(info, pending, entity, palette) }) .collect(); @@ -309,7 +309,7 @@ impl Yumush { pub(super) fn delete_builder_attachment( &mut self, - attachment_id: &str, + attachment_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -318,7 +318,6 @@ impl Yumush { return; } let network = self.network.clone(); - let attachment_id = attachment_id.to_string(); cx.spawn_in(window, async move |this, cx| { match network.call(DeleteAttachment { attachment_id }).await { diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs index 89140c7..8cac8a1 100644 --- a/crates/client/src/gui/builder/ui.rs +++ b/crates/client/src/gui/builder/ui.rs @@ -13,12 +13,12 @@ pub(super) fn to_units(bytes: u64, unit: u64) -> String { (bytes / unit).to_string() } -pub(super) fn confirmed(pending: &mut Option, id: &str) -> bool { - if pending.as_deref() == Some(id) { +pub(super) fn confirmed(pending: &mut Option, id: T) -> bool { + if pending.as_ref() == Some(&id) { *pending = None; true } else { - *pending = Some(id.to_string()); + *pending = Some(id); false } } diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 49ebaad..ec53515 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::future::Future; use common::{ @@ -23,8 +24,8 @@ use super::ui::{ }; use crate::{ gui::{ - DATE, DAY, Palette, Tooltip as _, Yumush, avatar, clickable, entity_action, id_time, - millis_time, notify_error, + DATE, DAY, Palette, Tooltip as _, Yumush, avatar, clickable, entity_action, millis_time, + notify_error, profile::user_link, text, widget::{field, search_text}, @@ -81,13 +82,12 @@ impl Yumush { pub(super) fn set_builder_role( &mut self, - user_id: &str, + user_id: Id, role: Role, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { match network.call(SetRole { user_id, role }).await { @@ -112,7 +112,7 @@ impl Yumush { pub(super) fn delete_builder_user( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -121,15 +121,9 @@ impl Yumush { return; } let network = self.network.clone(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network - .call(DeleteUser { - user_id: user_id.clone(), - }) - .await - { + match network.call(DeleteUser { user_id }).await { Ok(()) => { let _ = this.update(cx, |yumush, cx| { yumush @@ -166,12 +160,11 @@ impl Yumush { pub(super) fn suspend_builder_user( &mut self, - user_id: &str, + user_id: Id, suspended: bool, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); self.builder_user_action(window, cx, move |network| async move { network.call(SuspendUser { user_id, suspended }).await }); @@ -179,11 +172,10 @@ impl Yumush { pub(super) fn revoke_builder_sessions( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); self.builder_user_action(window, cx, move |network| async move { network.call(RevokeSessions { user_id }).await }); @@ -191,21 +183,20 @@ impl Yumush { pub(super) fn clear_builder_profile( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); self.builder_user_action(window, cx, move |network| async move { network.call(ClearProfile { user_id }).await.map(|_| ()) }); } - pub(super) fn toggle_builder_password(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_builder_password.as_deref() == Some(user_id) { + pub(super) fn toggle_builder_password(&mut self, user_id: Id, cx: &mut Context) { + if self.chat.pending_builder_password == Some(user_id) { self.chat.pending_builder_password = None; } else { - self.chat.pending_builder_password = Some(user_id.to_string()); + self.chat.pending_builder_password = Some(user_id); } cx.notify(); } @@ -223,21 +214,11 @@ impl Yumush { }); } - pub(super) fn load_sessions( - &self, - user_id: String, - window: &mut Window, - cx: &mut Context, - ) { + pub(super) fn load_sessions(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network - .call(ListSessions { - user_id: user_id.clone(), - }) - .await - { + match network.call(ListSessions { user_id }).await { Ok(sessions) => { let _ = this.update(cx, |yumush, cx| { yumush.chat.builder_sessions = Some((user_id, sessions)); @@ -252,7 +233,7 @@ impl Yumush { pub(super) fn toggle_builder_sessions( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -260,30 +241,28 @@ impl Yumush { .chat .builder_sessions .as_ref() - .is_some_and(|(open, _)| open == user_id) + .is_some_and(|(open, _)| *open == user_id) { self.chat.builder_sessions = None; cx.notify(); return; } - self.load_sessions(user_id.to_string(), window, cx); + self.load_sessions(user_id, window, cx); } pub(super) fn revoke_builder_session( &mut self, - user_id: &str, - session_id: &str, + user_id: Id, + session_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); - let user_id = user_id.to_string(); - let session_id = session_id.to_string(); cx.spawn_in(window, async move |this, cx| { match network .call(RevokeSession { - user_id: user_id.clone(), + user_id, session_id, }) .await @@ -299,11 +278,11 @@ impl Yumush { .detach(); } - pub(super) fn toggle_builder_rename(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_builder_rename.as_deref() == Some(user_id) { + pub(super) fn toggle_builder_rename(&mut self, user_id: Id, cx: &mut Context) { + if self.chat.pending_builder_rename == Some(user_id) { self.chat.pending_builder_rename = None; } else { - self.chat.pending_builder_rename = Some(user_id.to_string()); + self.chat.pending_builder_rename = Some(user_id); } cx.notify(); } @@ -324,17 +303,17 @@ impl Yumush { }); } - pub(super) fn toggle_builder_timeout(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_builder_timeout.as_deref() == Some(user_id) { + pub(super) fn toggle_builder_timeout(&mut self, user_id: Id, cx: &mut Context) { + if self.chat.pending_builder_timeout == Some(user_id) { self.chat.pending_builder_timeout = None; } else { - self.chat.pending_builder_timeout = Some(user_id.to_string()); + self.chat.pending_builder_timeout = Some(user_id); } cx.notify(); } pub(super) fn confirm_builder_timeout(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_builder_timeout.clone() else { + let Some(user_id) = self.chat.pending_builder_timeout else { return; }; let minutes = self.chat.builder_timeout.read(cx).text().to_string(); @@ -350,11 +329,11 @@ impl Yumush { }); } - pub(super) fn toggle_builder_ban(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_builder_ban.as_deref() == Some(user_id) { + pub(super) fn toggle_builder_ban(&mut self, user_id: Id, cx: &mut Context) { + if self.chat.pending_builder_ban == Some(user_id) { self.chat.pending_builder_ban = None; } else { - self.chat.pending_builder_ban = Some(user_id.to_string()); + self.chat.pending_builder_ban = Some(user_id); } cx.notify(); } @@ -391,7 +370,7 @@ impl Yumush { pub(super) fn purge_builder_user( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -400,15 +379,9 @@ impl Yumush { return; } let network = self.network.clone(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network - .call(PurgeUser { - user_id: user_id.clone(), - }) - .await - { + match network.call(PurgeUser { user_id }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush @@ -508,7 +481,7 @@ impl Yumush { pub(super) fn builder_timeout_row( &self, - user_id: &str, + user_id: Id, entity: &Entity, palette: Palette, ) -> Div { @@ -536,7 +509,7 @@ impl Yumush { pub(super) fn builder_ban_row( &self, - user_id: &str, + user_id: Id, entity: &Entity, palette: Palette, ) -> Div { @@ -576,13 +549,13 @@ impl Yumush { pub(super) fn builder_session_row( &self, - user_id: &str, + user_id: Id, session: &SessionInfo, entity: &Entity, palette: Palette, ) -> Div { - let revoke_user_id = user_id.to_string(); - let session_id = session.id.clone(); + let revoke_user_id = user_id; + let session_id = session.id; let revoke_button = action_button( format!("revoke_session_{}", session.id), IconName::LogOut, @@ -591,7 +564,7 @@ impl Yumush { palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.revoke_builder_session(&revoke_user_id, &session_id, window, cx) + yumush.revoke_builder_session(revoke_user_id, session_id, window, cx) }), ); let device = if session.device.is_empty() { @@ -632,7 +605,7 @@ impl Yumush { pub(super) fn builder_rename_row( &self, - user_id: &str, + user_id: Id, entity: &Entity, palette: Palette, ) -> Div { @@ -660,7 +633,7 @@ impl Yumush { pub(super) fn builder_password_row( &self, - user_id: &str, + user_id: Id, entity: &Entity, palette: Palette, ) -> Div { @@ -711,20 +684,20 @@ impl Yumush { .filter(|(open, _)| *open == user.id) .map(|(_, sessions)| sessions); let expanded = expanded_sessions.is_some(); - let pending_delete = self.chat.pending_builder_delete.as_deref() == Some(user.id.as_str()); - let pending_purge = self.chat.pending_builder_purge.as_deref() == Some(user.id.as_str()); - let role_id = user.id.clone(); - let delete_id = user.id.clone(); - let suspend_id = user.id.clone(); - let sessions_id = user.id.clone(); - let password_id = user.id.clone(); - let profile_id = user.id.clone(); - let sessions_list_id = user.id.clone(); - let rename_id = user.id.clone(); - let timeout_id = user.id.clone(); - let ban_id = user.id.clone(); - let purge_id = user.id.clone(); - let joined = id_time(&user.id, DATE); + let pending_delete = self.chat.pending_builder_delete == Some(user.id); + let pending_purge = self.chat.pending_builder_purge == Some(user.id); + let role_id = user.id; + let delete_id = user.id; + let suspend_id = user.id; + let sessions_id = user.id; + let password_id = user.id; + let profile_id = user.id; + let sessions_list_id = user.id; + let rename_id = user.id; + let timeout_id = user.id; + let ban_id = user.id; + let purge_id = user.id; + let joined = millis_time(user.created_at, DATE); let seen = seen_text(account.last_seen); let next_role = if builder { Role::User } else { Role::Builder }; @@ -749,7 +722,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, window, cx| { - yumush.set_builder_role(&role_id, next_role, window, cx) + yumush.set_builder_role(role_id, next_role, window, cx) }), ); @@ -765,7 +738,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, window, cx| { - yumush.suspend_builder_user(&suspend_id, !suspended, window, cx) + yumush.suspend_builder_user(suspend_id, !suspended, window, cx) }), ); @@ -777,7 +750,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, window, cx| { - yumush.revoke_builder_sessions(&sessions_id, window, cx) + yumush.revoke_builder_sessions(sessions_id, window, cx) }), ); @@ -789,7 +762,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_password(&password_id, cx) + yumush.toggle_builder_password(password_id, cx) }), ); @@ -797,7 +770,7 @@ impl Yumush { format!("sessions_list_user_{}", user.id), palette, entity_action(entity, move |yumush, window, cx| { - yumush.toggle_builder_sessions(&sessions_list_id, window, cx) + yumush.toggle_builder_sessions(sessions_list_id, window, cx) }), ) .tip("Manage") @@ -819,7 +792,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_rename(&rename_id, cx) + yumush.toggle_builder_rename(rename_id, cx) }), ); @@ -831,7 +804,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_timeout(&timeout_id, cx) + yumush.toggle_builder_timeout(timeout_id, cx) }), ); @@ -843,7 +816,7 @@ impl Yumush { tone, palette, entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_ban(&ban_id, cx) + yumush.toggle_builder_ban(ban_id, cx) }), ); @@ -855,7 +828,7 @@ impl Yumush { palette.danger, palette, entity_action(entity, move |yumush, window, cx| { - yumush.clear_builder_profile(&profile_id, window, cx) + yumush.clear_builder_profile(profile_id, window, cx) }), ); @@ -867,7 +840,7 @@ impl Yumush { pending_purge, palette, entity_action(entity, move |yumush, window, cx| { - yumush.purge_builder_user(&purge_id, window, cx) + yumush.purge_builder_user(purge_id, window, cx) }), ); @@ -879,7 +852,7 @@ impl Yumush { pending_delete, palette, entity_action(entity, move |yumush, window, cx| { - yumush.delete_builder_user(&delete_id, window, cx) + yumush.delete_builder_user(delete_id, window, cx) }), ); @@ -944,11 +917,11 @@ impl Yumush { .children(has_actions.then_some(toggle_button)); let panel = expanded_sessions.map(|sessions| { - let open_id = user.id.as_str(); - let password_open = self.chat.pending_builder_password.as_deref() == Some(open_id); - let rename_open = self.chat.pending_builder_rename.as_deref() == Some(open_id); - let timeout_open = self.chat.pending_builder_timeout.as_deref() == Some(open_id); - let ban_open = self.chat.pending_builder_ban.as_deref() == Some(open_id); + let open_id = user.id; + let password_open = self.chat.pending_builder_password == Some(open_id); + let rename_open = self.chat.pending_builder_rename == Some(open_id); + let timeout_open = self.chat.pending_builder_timeout == Some(open_id); + let ban_open = self.chat.pending_builder_ban == Some(open_id); let account_actions = [ manage.then(|| rename_button.into_any_element()), @@ -969,7 +942,7 @@ impl Yumush { let sessions: Vec = sessions .iter() .map(|session| { - self.builder_session_row(&user.id, session, entity, palette) + self.builder_session_row(user.id, session, entity, palette) .into_any_element() }) .collect(); @@ -989,16 +962,16 @@ impl Yumush { account_actions.into_iter().flatten().collect(), )) .children( - password_open.then(|| self.builder_password_row(&user.id, entity, palette)), + password_open.then(|| self.builder_password_row(user.id, entity, palette)), ) - .children(rename_open.then(|| self.builder_rename_row(&user.id, entity, palette))) + .children(rename_open.then(|| self.builder_rename_row(user.id, entity, palette))) .children(action_group( "Moderation", palette, moderation_actions.into_iter().flatten().collect(), )) - .children(timeout_open.then(|| self.builder_timeout_row(&user.id, entity, palette))) - .children(ban_open.then(|| self.builder_ban_row(&user.id, entity, palette))) + .children(timeout_open.then(|| self.builder_timeout_row(user.id, entity, palette))) + .children(ban_open.then(|| self.builder_ban_row(user.id, entity, palette))) .children(action_group( "Danger", palette, diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs index 58f2ef0..d8405c1 100644 --- a/crates/client/src/gui/builder/voice.rs +++ b/crates/client/src/gui/builder/voice.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::future::Future; use common::{ @@ -50,12 +51,11 @@ impl Yumush { pub(super) fn set_server_mute( &mut self, - user_id: &str, + user_id: Id, muted: bool, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); self.voice_action(window, cx, move |network| async move { network.call(ServerMute { user_id, muted }).await }); @@ -63,11 +63,10 @@ impl Yumush { pub(super) fn kick_from_voice( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { - let user_id = user_id.to_string(); self.voice_action(window, cx, move |network| async move { network.call(KickFromVoice { user_id }).await }); @@ -95,7 +94,7 @@ impl Yumush { entity: &Entity, palette: Palette, ) -> Div { - let id = room.community_id.clone(); + let id = room.community_id; let voice = self .chat .builder_communities @@ -103,8 +102,8 @@ impl Yumush { .find(|summary| summary.community.id == id) .map(|summary| summary.community.voice_enabled); - let joined = self.chat.in_voice(&id); - let join_id = id.clone(); + let joined = self.chat.in_voice(id); + let join_id = id; let mut actions = vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()]; if !joined { @@ -116,7 +115,7 @@ impl Yumush { palette.ok, palette, entity_action(entity, move |yumush, window, cx| { - yumush.jump_to(join_id.clone(), true, window, cx) + yumush.jump_to(join_id, true, window, cx) }), ) .into_any_element(), @@ -135,7 +134,7 @@ impl Yumush { palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.set_builder_community_voice(&id, !enabled, window, cx) + yumush.set_builder_community_voice(id, !enabled, window, cx) }), ) .into_any_element(), @@ -169,9 +168,9 @@ impl Yumush { entity: &Entity, palette: Palette, ) -> Div { - let id = user.id.clone(); - let mute_id = id.clone(); - let kick_id = id.clone(); + let id = user.id; + let mute_id = id; + let kick_id = id; div() .min_h(px(44.)) @@ -219,7 +218,7 @@ impl Yumush { palette.muted, palette, entity_action(entity, move |yumush, window, cx| { - yumush.set_server_mute(&mute_id, !muted, window, cx) + yumush.set_server_mute(mute_id, !muted, window, cx) }), )) .child(icon_button( @@ -229,7 +228,7 @@ impl Yumush { palette.danger, palette, entity_action(entity, move |yumush, window, cx| { - yumush.kick_from_voice(&kick_id, window, cx) + yumush.kick_from_voice(kick_id, window, cx) }), )) } diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index fda324d..c11caac 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::sync::Arc; use common::share::{Fps, Kind, Quality, Resolution}; @@ -27,17 +28,17 @@ pub(super) struct CameraTile { } impl Yumush { - fn camera_users(&self) -> Vec { + fn camera_users(&self) -> Vec { let Some(community_id) = self.chat.voice_community() else { return Vec::new(); }; self.chat .shares - .get(community_id) + .get(&community_id) .into_iter() .flatten() .filter(|share| share.kind == Kind::Camera) - .map(|share| share.user_id.clone()) + .map(|share| share.user_id) .collect() } @@ -46,35 +47,34 @@ impl Yumush { let viewing = self.viewing_camera(); let mut changed = false; - for user_id in &wanted { - if self.chat.cameras.contains_key(user_id) { + for &user_id in &wanted { + if self.chat.cameras.contains_key(&user_id) { continue; } self.chat.cameras.insert( - user_id.clone(), + user_id, CameraTile { generation: None, frame: None, }, ); let network = self.network.clone(); - let user_id = user_id.clone(); let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); spawn_warn(cx, "camera watch", async move { network - .watch_share(&user_id, Kind::Camera, CAMERA_TILE, volume, choice) + .watch_share(user_id, Kind::Camera, CAMERA_TILE, volume, choice) .await }); changed = true; } - let gone: Vec = self + let gone: Vec = self .chat .cameras .keys() - .filter(|user_id| !wanted.contains(*user_id)) - .cloned() + .filter(|user_id| !wanted.contains(user_id)) + .copied() .collect(); for user_id in gone { if let Some(frame) = self @@ -85,10 +85,10 @@ impl Yumush { { cx.drop_image(frame, None); } - if viewing.as_deref() != Some(user_id.as_str()) { + if viewing != Some(user_id) { let network = self.network.clone(); cx.spawn(async move |_, _| { - let _ = network.unwatch_share(&user_id, Kind::Camera).await; + let _ = network.unwatch_share(user_id, Kind::Camera).await; }) .detach(); } @@ -96,7 +96,7 @@ impl Yumush { } for (user_id, tile) in self.chat.cameras.iter_mut() { - let Some(frame) = self.network.share_frame(user_id, Kind::Camera) else { + let Some(frame) = self.network.share_frame(*user_id, Kind::Camera) else { continue; }; if tile.generation == Some(frame.generation) { @@ -146,9 +146,9 @@ impl Yumush { .map(|(user_id, tile)| { let name = self .chat - .author(user_id) + .author(*user_id) .map_or("Someone", |user| user.username.as_str()); - camera_tile(entity, user_id, name, tile, palette) + camera_tile(entity, *user_id, name, tile, palette) }) .collect(); @@ -208,18 +208,16 @@ pub(super) fn camera_toggle( fn camera_tile( entity: &Entity, - user_id: &str, + user_id: Id, name: &str, tile: &CameraTile, palette: Palette, ) -> impl IntoElement { let entity = entity.clone(); - let id = user_id.to_string(); clickable(format!("camera_{user_id}"), palette, move |window, cx| { - let id = id.clone(); entity.update(cx, |yumush, cx| { - yumush.toggle_viewer(id, Kind::Camera, window, cx) + yumush.toggle_viewer(user_id, Kind::Camera, window, cx) }); }) .tip("Watch") diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 64f5dc7..9798ed7 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -16,9 +16,9 @@ use crate::gui::{ clickable, community_name, community_settings::{BanSort, LogSort}, composer::{self, Composer}, - entity_action, hoverable, id_time, + entity_action, hoverable, media_view::{self, Media}, - message_actions, new_input, notify_error, palette, poll, pop_in, presence_avatar, + message_actions, millis_time, new_input, notify_error, palette, poll, pop_in, presence_avatar, primary_button, profile::profile_popover, rank_tag, @@ -42,9 +42,9 @@ use common::{ event::Event, model::{ Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community, - CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, - LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, - ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, + CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Id, Invitation, + InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, + ReportStatus, ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, }, permission, share::{Kind, Share}, @@ -87,7 +87,7 @@ pub enum DeleteStep { pub enum VoiceState { Off, In { - community_id: String, + community_id: Id, muted: bool, deafened: bool, }, @@ -111,8 +111,8 @@ impl History { #[derive(Debug, Clone, PartialEq, Eq)] pub enum ReportTarget { - Message(String), - User(String), + Message(Id), + User(Id), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -124,17 +124,17 @@ pub enum CardMenu { pub struct Chat { pub(super) communities: Vec, - pub(super) selected_community_id: Option, + pub(super) selected_community_id: Option, pub(super) opened: Option, pub(super) ghost: bool, members: Vec, pub(super) messages: Vec, pub(super) pins: Vec, history: History, - pub(super) unread: HashMap, - pub(super) unread_anchor: Option<(String, u32)>, + pub(super) unread: HashMap, + pub(super) unread_anchor: Option<(Id, u32)>, unseen: u32, - pub(super) muted: HashSet, + pub(super) muted: HashSet, pub(super) message_input: Entity, pub(super) search_input: Entity, pub(super) community_search: Entity, @@ -144,23 +144,23 @@ pub struct Chat { pub(super) tab: SidebarTab, pub(super) sidebar_collapsed: bool, pub(super) composer: Composer, - pub(super) drafts: HashMap, + pub(super) drafts: HashMap, pub(super) poll_question: Entity, pub(super) poll_options: Vec>, pub(super) poll_multiple: bool, pub(super) poll_expanded: bool, scroll: ScrollHandle, - pub(super) jump: Option, - highlight: Option<(String, Instant)>, + pub(super) jump: Option, + highlight: Option<(Id, Instant)>, pub(super) view: View, pub(super) username_input: Entity, pub(super) community_name_input: Entity, pub(super) status_input: Entity, - pub(super) avatars: HashMap>, - pub(super) hues: HashMap, - pub(super) avatar_requests: HashSet, - pub(super) users: HashMap, - user_requests: HashSet, + pub(super) avatars: HashMap>, + pub(super) hues: HashMap, + pub(super) avatar_requests: HashSet, + pub(super) users: HashMap, + user_requests: HashSet, pub(super) delete_step: DeleteStep, pub(super) bans: Vec, pub(super) ban_search: Entity, @@ -170,16 +170,16 @@ pub struct Chat { pub(super) log_sort: LogSort, pub(super) friends: Friends, pub(super) invitations: Vec, - pub(super) pending_user_delete: Option, + pub(super) pending_user_delete: Option, pub(super) card_menu: CardMenu, - pub(super) presences: HashMap, + pub(super) presences: HashMap, pub(super) slowed_until: Option, - pub(super) pending_builder_delete: Option, + pub(super) pending_builder_delete: Option, pub(super) builder_users: Vec, - pub(super) pending_builder_password: Option, + pub(super) pending_builder_password: Option, pub(super) builder_password: Entity, - pub(super) builder_sessions: Option<(String, Vec)>, - pub(super) pending_builder_rename: Option, + pub(super) builder_sessions: Option<(Id, Vec)>, + pub(super) pending_builder_rename: Option, pub(super) builder_rename: Entity, pub(super) server_name: Entity, pub(super) server_limit: Entity, @@ -195,9 +195,9 @@ pub struct Chat { pub(super) server_logins_per_minute: Entity, pub(super) server_registration_open: bool, pub(super) server_maintenance: bool, - pub(super) pending_builder_timeout: Option, + pub(super) pending_builder_timeout: Option, pub(super) builder_timeout: Entity, - pub(super) pending_builder_ban: Option, + pub(super) pending_builder_ban: Option, pub(super) builder_ban_reason: Entity, pub(super) builder_ban_scope: BanScope, pub(super) builder_bans: Vec, @@ -223,7 +223,7 @@ pub struct Chat { pub(super) open_reports: usize, pub(super) report: Option, pub(super) report_reason: Entity, - pub(super) pending_community_delete: Option, + pub(super) pending_community_delete: Option, pub(super) builder_message_text: Entity, pub(super) builder_message_user: Entity, pub(super) builder_message_community: Entity, @@ -235,30 +235,30 @@ pub struct Chat { pub(super) builder_usage_users: Vec, pub(super) builder_usage_communities: Vec, pub(super) builder_attachments: Vec, - pub(super) pending_attachment_delete: Option, - pub(super) pending_message_delete: Option, - pub(super) pending_builder_purge: Option, + pub(super) pending_attachment_delete: Option, + pub(super) pending_message_delete: Option, + pub(super) pending_builder_purge: Option, pub(super) transfer: Option, - pub(super) voice: HashMap>, + pub(super) voice: HashMap>, pub(super) voice_state: VoiceState, pub(super) waves: Waves, - pub(super) server_muted: HashSet, + pub(super) server_muted: HashSet, pub(super) builder_voice_rooms: Vec, pub(super) voice_task: Option>, pub(super) user_volume: Option, pub(super) voice_samples: VecDeque, pub(super) share_sample: ShareSample, - pub(super) share_loss: HashMap>, + pub(super) share_loss: HashMap>, pub(super) stats_tab: StatsTab, - pub(super) ringing: HashSet, + pub(super) ringing: HashSet, pub(super) ring_task: Option>, pub(super) media: Media, - pub(super) shares: HashMap>, + pub(super) shares: HashMap>, pub(super) viewer: Option, - pub(super) cameras: BTreeMap, + pub(super) cameras: BTreeMap, pub(super) camera_task: Option>, - pub(super) typing: HashMap>, - pub(super) typing_sent: HashMap, + pub(super) typing: HashMap>, + pub(super) typing_sent: HashMap, } const RING_LIMIT: usize = 15; @@ -268,7 +268,7 @@ const WAVE_INTERVAL: Duration = Duration::from_millis(33); const DEFAULT_USER_VOLUME: f32 = 100.0; pub struct UserVolume { - pub user_id: String, + pub user_id: Id, pub slider: Entity, _subscription: Subscription, } @@ -530,18 +530,18 @@ impl Chat { (remaining > 0).then(|| remaining.div_ceil(1000)) } - pub fn apply_event(&mut self, event: Event, me: Option<&str>) { + pub fn apply_event(&mut self, event: Event, me: Option) { match event { Event::MessageCreated(message) => { if let Some(users) = self.typing.get_mut(&message.community_id) { users.remove(&message.user_id); } - if self.is_selected(&message.community_id) { + if self.is_selected(message.community_id) { self.insert_messages([message], me); } } Event::MessageUpdated(message) => { - if self.is_selected(&message.community_id) { + if self.is_selected(message.community_id) { self.update_pin(&message); if let Some(existing) = self .messages @@ -553,8 +553,8 @@ impl Chat { } } Event::MessagesDeleted { community_id, ids } => { - if self.is_selected(&community_id) { - for id in &ids { + if self.is_selected(community_id) { + for id in ids { self.forget_message(id); } } @@ -563,7 +563,7 @@ impl Chat { community_id, member, } => { - if self.is_selected(&community_id) { + if self.is_selected(community_id) { self.insert_member(member); } } @@ -571,8 +571,8 @@ impl Chat { community_id, user_id, } => { - if self.is_selected(&community_id) { - self.remove_member(&user_id); + if self.is_selected(community_id) { + self.remove_member(user_id); } } Event::RankChanged { @@ -580,8 +580,8 @@ impl Chat { user_id, rank, } => { - if self.is_selected(&community_id) { - self.set_rank(&user_id, rank); + if self.is_selected(community_id) { + self.set_rank(user_id, rank); } } Event::CommunityUpdated(community) | Event::CommunityAdded(community) => { @@ -590,10 +590,10 @@ impl Chat { Event::FriendsUpdated(friends) => self.friends = friends, Event::InvitationsUpdated(invitations) => self.invitations = invitations, Event::CommunityDeleted { community_id } | Event::Removed { community_id, .. } => { - self.remove_community(&community_id) + self.remove_community(community_id) } Event::UserDeleted { user_id } => { - self.remove_member(&user_id); + self.remove_member(user_id); self.messages.retain(|message| message.user_id != user_id); } Event::UserUpdated(user) => self.update_member(&user), @@ -659,8 +659,8 @@ impl Chat { } } - pub(super) fn is_selected(&self, community_id: &str) -> bool { - self.selected_community_id.as_deref() == Some(community_id) + pub(super) fn is_selected(&self, community_id: Id) -> bool { + self.selected_community_id == Some(community_id) } pub fn typing_label(&self) -> Option { @@ -671,7 +671,7 @@ impl Chat { .iter() .filter(|(_, at)| at.elapsed() < TYPING_TTL) .map(|(user_id, _)| { - self.author(user_id) + self.author(*user_id) .map_or("Someone", |user| user.username.as_str()) }) .collect(); @@ -682,7 +682,7 @@ impl Chat { } } - fn select(&mut self, community_id: Option) { + fn select(&mut self, community_id: Option) { if community_id != self.selected_community_id { self.unread_anchor = community_id .as_ref() @@ -691,7 +691,6 @@ impl Chat { .and_then(|unread| { unread .last_read - .clone() .map(|last_read| (last_read, unread.messages)) }); self.unseen = 0; @@ -718,21 +717,21 @@ impl Chat { self.composer = Composer::Compose { reply: None }; } - pub fn joined(&self, community_id: &str) -> bool { + pub fn joined(&self, community_id: Id) -> bool { self.communities .iter() .any(|community| community.id == community_id) } - fn forget_message(&mut self, message_id: &str) { + fn forget_message(&mut self, message_id: Id) { self.messages.retain(|existing| existing.id != message_id); match &mut self.composer { - Composer::Select { ids } => ids.retain(|id| id != message_id), - Composer::Compose { reply } if reply.as_deref() == Some(message_id) => { + Composer::Select { ids } => ids.retain(|id| *id != message_id), + Composer::Compose { reply } if *reply == Some(message_id) => { self.composer = Composer::Compose { reply: None }; } - Composer::Edit { message_id: edited } if edited.as_str() == message_id => { + Composer::Edit { message_id: edited } if *edited == message_id => { self.composer = Composer::Compose { reply: None }; } _ => {} @@ -749,18 +748,18 @@ impl Chat { .find(|community| matches!(community.kind, CommunityKind::Notes)) } - fn insert_messages(&mut self, messages: impl IntoIterator, me: Option<&str>) { - let newest = self.messages.last().map(|message| message.id.clone()); + fn insert_messages(&mut self, messages: impl IntoIterator, me: Option) { + let newest = self.messages.last().map(|message| message.id); for message in messages { self.messages.retain(|existing| existing.id != message.id); self.messages.push(message); } - self.messages.sort_by(|left, right| left.id.cmp(&right.id)); - if self.messages.last().map(|message| &message.id) != newest.as_ref() { + self.messages.sort_by_key(|message| message.id); + if self.messages.last().map(|message| message.id) != newest { let mine = self .messages .last() - .is_some_and(|message| Some(message.user_id.as_str()) == me); + .is_some_and(|message| Some(message.user_id) == me); if newest.is_none() { match self.unread_divider(me) { Some(index) => self.scroll_to_index(index), @@ -821,53 +820,49 @@ impl Chat { } } - fn unread_divider(&self, me: Option<&str>) -> Option { - let (anchor, _) = self.unread_anchor.as_ref()?; + fn unread_divider(&self, me: Option) -> Option { + let (anchor, _) = self.unread_anchor?; if !self.unread_covered() { return None; } self.messages .iter() - .position(|message| message.id > *anchor && Some(message.user_id.as_str()) != me) + .position(|message| message.id > anchor && Some(message.user_id) != me) } - pub(super) fn mark_read(&mut self, community_id: &str, message_id: &str) { - let unread = self - .unread - .entry(community_id.to_string()) - .or_insert_with(|| Unread { - community_id: community_id.to_string(), - ..Default::default() - }); + pub(super) fn mark_read(&mut self, community_id: Id, message_id: Id) { + let unread = self.unread.entry(community_id).or_insert_with(|| Unread { + community_id, + ..Default::default() + }); unread.messages = 0; unread.mentions = 0; - unread.last_read = Some(message_id.to_string()); + unread.last_read = Some(message_id); } - fn add_page(&mut self, page: Vec, me: Option<&str>) { + fn add_page(&mut self, page: Vec, me: Option) { self.history = History::of_page(page.len()); self.insert_messages(page, me); } fn insert_member(&mut self, member: Member) { - self.remove_member(&member.user.id); + self.remove_member(member.user.id); self.members.push(member); - self.members - .sort_by(|left, right| left.user.id.cmp(&right.user.id)); + self.members.sort_by_key(|member| member.user.id); } - pub(super) fn remove_member(&mut self, user_id: &str) { + pub(super) fn remove_member(&mut self, user_id: Id) { if let Some(index) = self .members .iter() .position(|member| member.user.id == user_id) { let member = self.members.remove(index); - self.users.insert(member.user.id.clone(), member.user); + self.users.insert(member.user.id, member.user); } } - fn set_rank(&mut self, user_id: &str, rank: Rank) { + fn set_rank(&mut self, user_id: Id, rank: Rank) { if let Some(member) = self .members .iter_mut() @@ -877,7 +872,7 @@ impl Chat { } } - fn community(&self, community_id: &str) -> Option<&Community> { + fn community(&self, community_id: Id) -> Option<&Community> { self.communities .iter() .chain(self.opened.as_ref()) @@ -885,34 +880,33 @@ impl Chat { } pub fn selected_community(&self) -> Option<&Community> { - self.community(self.selected_community_id.as_deref()?) + self.community(self.selected_community_id?) } - fn member_entry(&self, user_id: &str) -> Option<&Member> { + fn member_entry(&self, user_id: Id) -> Option<&Member> { self.members.iter().find(|member| member.user.id == user_id) } - pub fn member(&self, user_id: &str) -> Option<&User> { + pub fn member(&self, user_id: Id) -> Option<&User> { self.member_entry(user_id).map(|member| &member.user) } - pub fn author(&self, user_id: &str) -> Option<&User> { - self.member(user_id).or_else(|| self.users.get(user_id)) + pub fn author(&self, user_id: Id) -> Option<&User> { + self.member(user_id).or_else(|| self.users.get(&user_id)) } - fn missing_authors(&self) -> Vec { + fn missing_authors(&self) -> Vec { if self.members.is_empty() { return vec![]; } - let mut missing: Vec = self + let mut missing: Vec = self .messages .iter() .flat_map(|message| { - std::iter::once(&message.user_id) - .chain(message.reply.as_ref().map(|quote| "e.user_id)) + std::iter::once(message.user_id) + .chain(message.reply.as_ref().map(|quote| quote.user_id)) }) - .filter(|id| self.author(id).is_none() && !self.user_requests.contains(*id)) - .cloned() + .filter(|id| self.author(*id).is_none() && !self.user_requests.contains(id)) .collect(); missing.sort(); missing.dedup(); @@ -920,12 +914,12 @@ impl Chat { } pub fn rank_of(&self, user: &User) -> Option { - let rank = self.member_entry(&user.id).map(|member| member.rank); + let rank = self.member_entry(user.id).map(|member| member.rank); permission::effective_rank(user.role, rank) } - pub fn rank_of_id(&self, user_id: &str) -> Option { + pub fn rank_of_id(&self, user_id: Id) -> Option { self.member(user_id).and_then(|user| self.rank_of(user)) } @@ -940,14 +934,14 @@ impl Chat { self.pins.retain(|pin| pin.id != message.id); if message.pinned { self.pins.push(message.clone()); - self.pins.sort_by(|left, right| right.id.cmp(&left.id)); + self.pins.sort_by_key(|pin| std::cmp::Reverse(pin.id)); } } pub fn can_delete(&self, message: &Message, me: &User) -> bool { permission::can_delete_message( self.rank_of(me), - self.rank_of_id(&message.user_id), + self.rank_of_id(message.user_id), message.user_id == me.id, ) } @@ -983,15 +977,14 @@ impl Chat { self.communities .retain(|existing| existing.id != community.id); self.communities.push(community); - self.communities - .sort_by(|left, right| left.id.cmp(&right.id)); + self.communities.sort_by_key(|community| community.id); } - pub(super) fn remove_community(&mut self, community_id: &str) { + pub(super) fn remove_community(&mut self, community_id: Id) { self.communities .retain(|community| community.id != community_id); - self.unread.remove(community_id); - self.voice.remove(community_id); + self.unread.remove(&community_id); + self.voice.remove(&community_id); if self.in_voice(community_id) { self.set_voice_off(); } @@ -1006,7 +999,7 @@ impl Chat { let selected_present = self .communities .iter() - .any(|community| self.is_selected(&community.id)); + .any(|community| self.is_selected(community.id)); if !selected_present { self.select(None); } @@ -1074,10 +1067,10 @@ impl Chat { self.set_voice_off(); } - pub fn voice_community(&self) -> Option<&str> { + pub fn voice_community(&self) -> Option { match &self.voice_state { VoiceState::Off => None, - VoiceState::In { community_id, .. } => Some(community_id), + VoiceState::In { community_id, .. } => Some(*community_id), } } @@ -1085,7 +1078,7 @@ impl Chat { self.community(self.voice_community()?) } - pub fn in_voice(&self, community_id: &str) -> bool { + pub fn in_voice(&self, community_id: Id) -> bool { self.voice_community() == Some(community_id) } @@ -1098,25 +1091,25 @@ impl Chat { } } - pub fn voice_enabled(&self, community_id: &str) -> bool { + pub fn voice_enabled(&self, community_id: Id) -> bool { self.community(community_id) .is_some_and(|community| community.voice_enabled) } - pub fn share_of(&self, community_id: &str, user_id: &str, kind: Kind) -> Option<&Share> { + pub fn share_of(&self, community_id: Id, user_id: Id, kind: Kind) -> Option<&Share> { self.shares - .get(community_id)? + .get(&community_id)? .iter() .find(|share| share.user_id == user_id && share.kind == kind) } - pub fn is_sharing(&self, community_id: &str, user_id: &str) -> bool { + pub fn is_sharing(&self, community_id: Id, user_id: Id) -> bool { self.share_of(community_id, user_id, Kind::Screen).is_some() } - pub fn voice_ids(&self, community_id: &str) -> &[String] { + pub fn voice_ids(&self, community_id: Id) -> &[Id] { self.voice - .get(community_id) + .get(&community_id) .map(Vec::as_slice) .unwrap_or_default() } @@ -1134,7 +1127,7 @@ impl Chat { self.share_loss .retain(|user_id, _| sample.watching.iter().any(|(id, _)| id == user_id)); for (user_id, stats) in &sample.watching { - let history = self.share_loss.entry(user_id.clone()).or_default(); + let history = self.share_loss.entry(*user_id).or_default(); history.push_back(stats.loss); while history.len() > SAMPLE_HISTORY { history.pop_front(); @@ -1190,7 +1183,7 @@ pub(super) fn create_community( struct MembersTrigger { palette: Palette, members: Vec, - avatars: HashMap>, + avatars: HashMap>, } impl Selectable for MembersTrigger { @@ -1341,7 +1334,7 @@ impl Yumush { .children(self.voice_button(entity, palette)) .children( community - .is_some_and(|community| self.chat.joined(&community.id)) + .is_some_and(|community| self.chat.joined(community.id)) .then(|| message_actions::search_popover(&self.chat, entity, palette)), ) .children( @@ -1363,7 +1356,7 @@ impl Yumush { } fn unread_bar(&self, entity: &Entity, palette: Palette) -> Option { - let (anchor, count) = self.chat.unread_anchor.clone()?; + let (anchor, count) = self.chat.unread_anchor?; if self.chat.unread_covered() { return None; } @@ -1379,7 +1372,7 @@ impl Yumush { "jump_unread", palette, entity_action(entity, move |yumush, window, cx| { - yumush.go_to_message(anchor.clone(), window, cx) + yumush.go_to_message(anchor, window, cx) }), ) .child("↑"), @@ -1445,7 +1438,7 @@ impl Yumush { fn message_list(&self, entity: &Entity, palette: Palette) -> impl IntoElement { let divider = self .chat - .unread_divider(self.user.as_ref().map(|user| user.id.as_str())); + .unread_divider(self.user.as_ref().map(|user| user.id)); let entity_scroll = entity.clone(); div() .id("chat_messages") @@ -1593,18 +1586,18 @@ impl Yumush { pub(super) fn select_community( &mut self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { self.stop_playing(cx); self.save_draft(cx); - self.chat.select(Some(community_id.clone())); - self.restore_draft(&community_id, window, cx); + self.chat.select(Some(community_id)); + self.restore_draft(community_id, window, cx); self.chat.focus(window, cx); self.load_members(window, cx); self.load_pins(window, cx); - self.load_voice(community_id.clone(), cx); + self.load_voice(community_id, cx); self.load_shares(community_id, cx); self.load_messages(None, window, cx); cx.notify(); @@ -1616,7 +1609,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let community_id = community.id.clone(); + let community_id = community.id; self.chat.insert_community(community); self.request_social_avatars(cx); self.select_community(community_id, window, cx); @@ -1628,11 +1621,11 @@ impl Yumush { self.load_communities(window, cx); self.load_social(window, cx); - if let Some(community_id) = self.chat.selected_community_id.clone() { + if let Some(community_id) = self.chat.selected_community_id { self.load_members(window, cx); self.chat.messages.clear(); self.load_messages(None, window, cx); - self.load_voice(community_id.clone(), cx); + self.load_voice(community_id, cx); self.load_shares(community_id, cx); } } @@ -1650,7 +1643,7 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.unread = unreads .into_iter() - .map(|unread| (unread.community_id.clone(), unread)) + .map(|unread| (unread.community_id, unread)) .collect(); yumush.chat.replace_communities(communities); yumush.request_social_avatars(cx); @@ -1660,7 +1653,7 @@ impl Yumush { .chat .communities .first() - .map(|community| community.id.clone()); + .map(|community| community.id); if let Some(community_id) = first { yumush.select_community(community_id, window, cx); } @@ -1672,7 +1665,7 @@ impl Yumush { } fn search_community(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let text = search_text(&self.chat.community_search, cx); @@ -1683,12 +1676,7 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { let Some(hits) = ok_or_notify( - network - .call(SearchCommunity { - community_id: community_id.clone(), - text, - }) - .await, + network.call(SearchCommunity { community_id, text }).await, &this, cx, ) else { @@ -1696,7 +1684,7 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { - if yumush.chat.is_selected(&community_id) { + if yumush.chat.is_selected(community_id) { yumush.chat.community_hits = hits; cx.notify(); } @@ -1706,26 +1694,19 @@ impl Yumush { } fn load_pins(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(pins) = ok_or_notify( - network - .call(ListPins { - community_id: community_id.clone(), - }) - .await, - &this, - cx, - ) else { + let Some(pins) = ok_or_notify(network.call(ListPins { community_id }).await, &this, cx) + else { return; }; let _ = this.update(cx, |yumush, cx| { - if yumush.chat.is_selected(&community_id) { + if yumush.chat.is_selected(community_id) { yumush.chat.pins = pins; cx.notify(); } @@ -1735,32 +1716,26 @@ impl Yumush { } fn load_members(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(members) = ok_or_notify( - network - .call(ListMembers { - community_id: community_id.clone(), - }) - .await, - &this, - cx, - ) else { + let Some(members) = + ok_or_notify(network.call(ListMembers { community_id }).await, &this, cx) + else { return; }; let _ = this.update_in(cx, |yumush, window, cx| { - if yumush.chat.is_selected(&community_id) { + if yumush.chat.is_selected(community_id) { for member in &members { yumush.request_user_avatar(&member.user, cx); yumush .chat .users - .insert(member.user.id.clone(), member.user.clone()); + .insert(member.user.id, member.user.clone()); } yumush.chat.members = members; yumush.load_bans(window, cx); @@ -1777,7 +1752,7 @@ impl Yumush { if missing.is_empty() { return; } - self.chat.user_requests.extend(missing.iter().cloned()); + self.chat.user_requests.extend(missing.iter().copied()); let network = self.network.clone(); cx.spawn(async move |this, cx| { @@ -1787,7 +1762,7 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { yumush.request_user_avatar(&user, cx); - yumush.chat.users.insert(user.id.clone(), user); + yumush.chat.users.insert(user.id, user); cx.notify(); }); } @@ -1799,26 +1774,19 @@ impl Yumush { if !permission::can_unban(self.actor_rank()) { return; } - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let Some(bans) = ok_or_notify( - network - .call(ListBans { - community_id: community_id.clone(), - }) - .await, - &this, - cx, - ) else { + let Some(bans) = ok_or_notify(network.call(ListBans { community_id }).await, &this, cx) + else { return; }; let _ = this.update(cx, |yumush, cx| { - if yumush.chat.is_selected(&community_id) { + if yumush.chat.is_selected(community_id) { for ban in &bans { yumush.request_user_avatar(&ban.user, cx); } @@ -1832,7 +1800,7 @@ impl Yumush { pub(super) fn go_to_message( &mut self, - message_id: String, + message_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -1861,14 +1829,14 @@ impl Yumush { } fn load_older_messages(&self, window: &mut Window, cx: &mut Context) { - let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else { + let Some(oldest_id) = self.chat.messages.first().map(|message| message.id) else { return; }; self.load_messages(Some(oldest_id), window, cx); } - fn load_messages(&self, before: Option, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + fn load_messages(&self, before: Option, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); @@ -1878,14 +1846,14 @@ impl Yumush { if before.is_none() { let _ = network .call(WatchCommunity { - community_id: Some(community_id.clone()), + community_id: Some(community_id), }) .await; } let Some(page) = ok_or_notify( network .call(ListMessages { - community_id: community_id.clone(), + community_id, before, }) .await, @@ -1896,17 +1864,17 @@ impl Yumush { }; let _ = this.update_in(cx, |yumush, window, cx| { - if yumush.chat.is_selected(&community_id) { - let newest = page.last().map(|message| message.id.clone()); + if yumush.chat.is_selected(community_id) { + let newest = page.last().map(|message| message.id); let seeking = yumush.chat.jump.is_some(); yumush .chat - .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str())); + .add_page(page, yumush.user.as_ref().map(|user| user.id)); if seeking { yumush.continue_jump(window, cx); } if let Some(message_id) = newest.filter(|_| latest) { - yumush.mark_read(&community_id, &message_id, cx); + yumush.mark_read(community_id, message_id, cx); } yumush.request_media(cx); yumush.request_authors(cx); @@ -1919,15 +1887,15 @@ impl Yumush { pub(super) fn request_message_delete( &mut self, - message_id: String, + message_id: Id, window: &mut Window, cx: &mut Context, ) { if self.chat.pending_message_delete.as_ref() == Some(&message_id) { self.chat.pending_message_delete = None; - self.delete_message(&message_id, window, cx); + self.delete_message(message_id, window, cx); } else { - self.chat.pending_message_delete = Some(message_id.clone()); + self.chat.pending_message_delete = Some(message_id); cx.spawn(async move |this, cx| { cx.background_executor().timer(DELETE_CONFIRM).await; let _ = this.update(cx, |yumush, cx| { @@ -1944,13 +1912,11 @@ impl Yumush { pub(super) fn delete_message( &self, - message_id: &str, + message_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); - let message_id = message_id.to_string(); - spawn_done(window, cx, async move { network.call(DeleteMessage { message_id }).await }); @@ -1958,41 +1924,32 @@ impl Yumush { pub(super) fn leave_community( &self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network - .call(LeaveCommunity { - community_id: community_id.clone(), - }) - .await - { + if let Err(error) = network.call(LeaveCommunity { community_id }).await { notify_error(&this, cx, error); return; } let _ = this.update(cx, |yumush, cx| { - yumush.leave_voice_in(&community_id, cx); - yumush.chat.remove_community(&community_id); + yumush.leave_voice_in(community_id, cx); + yumush.chat.remove_community(community_id); cx.notify(); }); }) .detach(); } - fn load_voice(&self, community_id: String, cx: &mut Context) { + fn load_voice(&self, community_id: Id, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { - let Ok(participants) = network - .call(ListVoiceParticipants { - community_id: community_id.clone(), - }) - .await + let Ok(participants) = network.call(ListVoiceParticipants { community_id }).await else { return; }; @@ -2007,11 +1964,11 @@ impl Yumush { pub(super) fn toggle_voice( &mut self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { - if self.chat.in_voice(&community_id) { + if self.chat.in_voice(community_id) { self.end_voice(cx); return; } @@ -2026,7 +1983,7 @@ impl Yumush { fn join_voice( &mut self, - community_id: String, + community_id: Id, (muted, deafened): (bool, bool), was_in: bool, window: &mut Window, @@ -2040,15 +1997,15 @@ impl Yumush { let _ = network.leave_voice().await; } - match network.join_voice(&community_id, &voice_settings).await { + match network.join_voice(community_id, &voice_settings).await { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { let muted = - muted || yumush.is_server_muted() || yumush.hidden_in(&community_id); + muted || yumush.is_server_muted() || yumush.hidden_in(community_id); yumush.network.set_muted(muted); - yumush.chat.voice.insert(community_id.clone(), participants); - yumush.load_shares(community_id.clone(), cx); + yumush.chat.voice.insert(community_id, participants); + yumush.load_shares(community_id, cx); yumush.chat.voice_state = VoiceState::In { community_id, muted, @@ -2084,14 +2041,14 @@ impl Yumush { } pub(super) fn refresh_voice(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.voice_community().map(str::to_string) else { + let Some(community_id) = self.chat.voice_community() else { return; }; - self.load_voice(community_id.clone(), cx); + self.load_voice(community_id, cx); self.load_shares(community_id, cx); } - pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context) { + pub(super) fn leave_voice_in(&mut self, community_id: Id, cx: &mut Context) { if self.chat.in_voice(community_id) { self.end_voice(cx); } @@ -2103,7 +2060,7 @@ impl Yumush { .is_some_and(|me| self.chat.server_muted.contains(&me.id)) } - fn hidden_in(&self, community_id: &str) -> bool { + fn hidden_in(&self, community_id: Id) -> bool { self.chat.ghost || !self.chat.joined(community_id) } @@ -2238,13 +2195,11 @@ impl Yumush { })); } - pub(super) fn open_user_volume(&mut self, user_id: &str, cx: &mut Context) { - let in_call = self.chat.voice_community().is_some_and(|community_id| { - self.chat - .voice_ids(community_id) - .iter() - .any(|id| id == user_id) - }); + pub(super) fn open_user_volume(&mut self, user_id: Id, cx: &mut Context) { + let in_call = self + .chat + .voice_community() + .is_some_and(|community_id| self.chat.voice_ids(community_id).contains(&user_id)); if !in_call || self.is_me(user_id) { self.chat.user_volume = None; return; @@ -2256,30 +2211,29 @@ impl Yumush { .max(*VOLUME.end()) .default_value(volume) }); - let id = user_id.to_string(); let subscription = cx.subscribe(&slider, move |this, _, event: &SliderEvent, cx| { let SliderEvent::Change(value) = event else { return; }; let volumes = &mut this.settings.voice.user_volumes; match value.start() { - volume if volume == DEFAULT_USER_VOLUME => volumes.remove(&id), - volume => volumes.insert(id.clone(), volume), + volume if volume == DEFAULT_USER_VOLUME => volumes.remove(&user_id), + volume => volumes.insert(user_id, volume), }; this.commit_settings(cx); }); self.chat.user_volume = Some(UserVolume { - user_id: user_id.to_string(), + user_id, slider, _subscription: subscription, }); } - pub(super) fn user_volume(&self, user_id: &str) -> f32 { + pub(super) fn user_volume(&self, user_id: Id) -> f32 { self.settings .voice .user_volumes - .get(user_id) + .get(&user_id) .copied() .unwrap_or(DEFAULT_USER_VOLUME) } @@ -2289,19 +2243,19 @@ impl Yumush { .chat .voice_flags() .is_some_and(|(muted, deafened)| muted || deafened); - let me = self.user.as_ref().map(|user| user.id.as_str()); + let me = self.user.as_ref().map(|user| user.id); if self.chat.waves.update(levels, me, silent) { cx.notify(); } } fn voice_button(&self, entity: &Entity, palette: Palette) -> Option { - let community_id = self.chat.selected_community_id.clone()?; - let direct = self.is_direct(&community_id); - let in_voice = self.chat.in_voice(&community_id); + let community_id = self.chat.selected_community_id?; + let direct = self.is_direct(community_id); + let in_voice = self.chat.in_voice(community_id); if !in_voice && (!permission::can_join_voice(self.actor_rank()) - || !(self.is_builder() || self.chat.voice_enabled(&community_id)) + || !(self.is_builder() || self.chat.voice_enabled(community_id)) || self .chat .notes() @@ -2313,7 +2267,7 @@ impl Yumush { let entity = entity.clone(); let on_click = move |window: &mut Window, cx: &mut App| { entity.update(cx, |yumush, cx| { - yumush.toggle_voice(community_id.clone(), window, cx) + yumush.toggle_voice(community_id, window, cx) }) }; let (icon, tip) = match (direct, in_voice) { @@ -2343,13 +2297,13 @@ impl Yumush { fn calling_hint(&self, palette: Palette) -> Option
{ let community = self.chat.selected_community()?; - let direct = self.is_direct(&community.id); - let alone = self.chat.in_voice(&community.id) + let direct = self.is_direct(community.id); + let alone = self.chat.in_voice(community.id) && self .chat - .voice_ids(&community.id) + .voice_ids(community.id) .iter() - .all(|id| self.is_me(id)); + .all(|id| self.is_me(*id)); (direct && alone).then(|| { div() @@ -2361,7 +2315,7 @@ impl Yumush { fn call_banner(&self, entity: &Entity, palette: Palette) -> Option
{ let (community_id, caller) = self.incoming_call()?; - let accept_id = community_id.clone(); + let accept_id = community_id; Some( accent_bar(palette) @@ -2382,7 +2336,7 @@ impl Yumush { "accept_call", palette, entity_action(entity, move |yumush, window, cx| { - yumush.accept_call(accept_id.clone(), window, cx) + yumush.accept_call(accept_id, window, cx) }), ) .bg(palette.ok) @@ -2395,7 +2349,7 @@ impl Yumush { "decline_call", palette, entity_action(entity, move |yumush, window, cx| { - yumush.decline_call(community_id.clone(), window, cx) + yumush.decline_call(community_id, window, cx) }), ) .bg(palette.danger) @@ -2408,7 +2362,7 @@ impl Yumush { ) } - fn incoming_call(&self) -> Option<(String, User)> { + fn incoming_call(&self) -> Option<(Id, User)> { self.chat.communities().iter().find_map(|community| { let CommunityKind::Direct { peer } = &community.kind else { return None; @@ -2416,21 +2370,21 @@ impl Yumush { let calling = self.user.is_some() && self .chat - .voice_ids(&community.id) + .voice_ids(community.id) .iter() - .any(|id| !self.is_me(id)); + .any(|id| !self.is_me(*id)); let ringing = calling - && !self.chat.in_voice(&community.id) + && !self.chat.in_voice(community.id) && self.chat.ringing.contains(&community.id); - ringing.then(|| (community.id.clone(), peer.clone())) + ringing.then(|| (community.id, peer.clone())) }) } - fn ring_allowed(&self, community_id: &str) -> bool { + fn ring_allowed(&self, community_id: Id) -> bool { self.user .as_ref() - .is_some_and(|me| self.presence_of(&me.id) == Presence::Online) - && !self.chat.muted.contains(community_id) + .is_some_and(|me| self.presence_of(me.id) == Presence::Online) + && !self.chat.muted.contains(&community_id) } pub(super) fn update_ringing(&mut self, cx: &mut Context) { @@ -2446,7 +2400,7 @@ impl Yumush { for _ in 0..RING_LIMIT { let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { Some((community_id, _)) => { - if yumush.ring_allowed(&community_id) { + if yumush.ring_allowed(community_id) { yumush.network.play_ring(&yumush.settings.voice); } true @@ -2461,14 +2415,14 @@ impl Yumush { })); } - fn accept_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { + fn accept_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context) { self.chat.ringing.remove(&community_id); - self.select_community(community_id.clone(), window, cx); + self.select_community(community_id, window, cx); self.toggle_voice(community_id, window, cx); self.update_ringing(cx); } - fn decline_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { + fn decline_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context) { self.chat.ringing.remove(&community_id); self.update_ringing(cx); cx.notify(); @@ -2480,20 +2434,20 @@ impl Yumush { } fn voice_stack(&self, entity: &Entity, palette: Palette) -> Option { - let community_id = self.chat.selected_community_id.as_deref()?; + let community_id = self.chat.selected_community_id?; let users: Vec<&User> = self .chat .voice_ids(community_id) .iter() - .filter_map(|id| self.chat.member(id)) + .filter_map(|id| self.chat.member(*id)) .collect(); if users.is_empty() { return None; } - let sharers: Vec = users + let sharers: Vec = users .iter() - .filter(|user| self.chat.is_sharing(community_id, &user.id)) - .map(|user| user.id.clone()) + .filter(|user| self.chat.is_sharing(community_id, user.id)) + .map(|user| user.id) .collect(); Some( @@ -2523,8 +2477,8 @@ impl Yumush { .children(sharers.iter().map(|user_id| { share_view::share_badge( entity, - user_id, - self.chat.waves.share(user_id), + *user_id, + self.chat.waves.share(*user_id), palette, ) })), @@ -2614,7 +2568,6 @@ fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) - let entity = entity.clone(); let voice = chat .selected_community_id - .as_deref() .map(|community_id| chat.voice_ids(community_id)) .unwrap_or_default(); let members: Vec = chat @@ -2625,7 +2578,7 @@ fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) - rank: chat.rank_of(&member.user), in_voice: voice.contains(&member.user.id), muted: chat.server_muted.contains(&member.user.id), - presence: yumush.presence_of(&member.user.id), + presence: yumush.presence_of(member.user.id), }) .collect(); let avatars = chat.avatars.clone(); @@ -2787,7 +2740,7 @@ fn render_call( ) -> AnyElement { let mine = me.is_some_and(|me| me.id == message.user_id); let author = chat - .author(&message.user_id) + .author(message.user_id) .map_or("unknown", |user| user.username.as_str()); let who = if mine { "You" } else { author }; let (icon, color) = match call { @@ -2828,7 +2781,7 @@ fn render_message( if let Some(call) = message.call { return render_call(message, call, chat, me, palette); } - let author = chat.author(&message.user_id); + let author = chat.author(message.user_id); let username = author.map_or("unknown", |user| user.username.as_str()); let name = div() .flex() @@ -2836,13 +2789,13 @@ fn render_message( .gap(px(8.)) .child(match author { Some(user) => avatar(palette, user, px(20.), text(10.), &chat.avatars), - None => badge(palette, &message.user_id, username, px(20.), text(10.)).rounded_full(), + None => badge(palette, message.user_id, username, px(20.), text(10.)).rounded_full(), }) .child( div() .id(format!("author_name_{}", message.id)) .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.tinted(&message.user_id)) + .text_color(palette.tinted(message.user_id)) .when(author.is_some(), |this| { this.hover(|style| style.underline()) }) @@ -2894,7 +2847,7 @@ fn render_message( div() .text_size(text(12.)) .text_color(palette.muted) - .child(id_time(&message.id, CLOCK)), + .child(millis_time(message.created_at, CLOCK)), ), ) }) @@ -2978,7 +2931,7 @@ fn render_message( })), ) .children( - (chat.report == Some(ReportTarget::Message(message.id.clone()))) + (chat.report == Some(ReportTarget::Message(message.id))) .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)), ); @@ -2986,7 +2939,7 @@ fn render_message( return row.into_any_element(); } - let message_id = message.id.clone(); + let message_id = message.id; let select_entity = entity.clone(); let mark_line = if first { div().h(px(20.)) @@ -3006,7 +2959,7 @@ fn render_message( .hover(|style| style.bg(palette.hover.opacity(0.5))) .when(selected, |this| this.bg(palette.hover)) .on_click(move |_, _, cx| { - select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx)); + select_entity.update(cx, |yumush, cx| yumush.toggle_select(message_id, cx)); }) .child( mark_line diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index ca21a23..554fe87 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::{collections::HashMap, sync::Arc}; use crate::net::Fail; @@ -25,7 +26,7 @@ use gpui_kit::{ use super::{ Palette, STAMP, Yumush, avatar, chat::View, - clickable, community_icon, entity_action, id_time, notify_error, + clickable, community_icon, entity_action, millis_time, notify_error, profile::user_link, settings_page::{ Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, @@ -140,12 +141,7 @@ impl Yumush { palette, vec![row( "Voice", - voice_control( - entity, - community.id.clone(), - community.voice_enabled, - palette, - ), + voice_control(entity, community.id, community.voice_enabled, palette), )], ) .into_any_element(), @@ -186,7 +182,7 @@ impl Yumush { if let Some(community) = community.filter(|_| permission::can_leave(actor)) { danger.push(row( "Leave community", - leave_control(entity, community.id.clone(), palette), + leave_control(entity, community.id, palette), )); } if permission::can_delete_community(actor) { @@ -210,7 +206,7 @@ impl Yumush { fn set_community_voice( &mut self, - community_id: String, + community_id: Id, enabled: bool, window: &mut Window, cx: &mut Context, @@ -230,7 +226,7 @@ impl Yumush { } pub(super) fn save_community_name(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let name = self @@ -257,7 +253,7 @@ impl Yumush { } fn upload_community_picture(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let picked = picked_avatar(cx, self.max_avatar_bytes()); @@ -284,7 +280,7 @@ impl Yumush { } fn remove_community_picture(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); @@ -305,19 +301,17 @@ impl Yumush { if !self.confirm_delete(cx) { return; } - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let call = DeleteCommunity { - community_id: community_id.clone(), - }; + let call = DeleteCommunity { community_id }; match network.call(call).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.remove_community(&community_id); + yumush.chat.remove_community(community_id); yumush.show_view(View::Chat, window, cx); }); } @@ -327,17 +321,16 @@ impl Yumush { .detach(); } - pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + pub(super) fn unban(&self, user_id: Id, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { let call = Unban { community_id, - user_id: user_id.clone(), + user_id, }; match network.call(call).await { Ok(()) => { @@ -382,7 +375,7 @@ impl Yumush { } fn open_logs(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; self.show_logs(community_id, window, cx); @@ -390,7 +383,7 @@ impl Yumush { pub(super) fn show_logs( &mut self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -434,7 +427,7 @@ impl Yumush { cx.notify(); } - fn load_logs(&self, community_id: String, window: &mut Window, cx: &mut Context) { + fn load_logs(&self, community_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { @@ -466,7 +459,7 @@ impl Yumush { fn voice_control( entity: &Entity, - community_id: String, + community_id: Id, enabled: bool, palette: Palette, ) -> impl IntoElement { @@ -478,7 +471,7 @@ fn voice_control( palette.text, move |window, cx| { entity.update(cx, |yumush, cx| { - yumush.set_community_voice(community_id.clone(), !enabled, window, cx) + yumush.set_community_voice(community_id, !enabled, window, cx) }); }, ) @@ -622,7 +615,7 @@ fn log_text(entry: &LogEntry) -> String { } } -fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap>) -> Div { +fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap>) -> Div { div() .min_h(px(40.)) .px(px(12.)) @@ -641,15 +634,11 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap, - community_id: String, - palette: Palette, -) -> impl IntoElement { +fn leave_control(entity: &Entity, community_id: Id, palette: Palette) -> impl IntoElement { let entity = entity.clone(); small_button( @@ -658,7 +647,7 @@ fn leave_control( palette.danger, move |window, cx| { entity.update(cx, |yumush, cx| { - yumush.leave_community(community_id.clone(), window, cx) + yumush.leave_community(community_id, window, cx) }); }, ) @@ -671,11 +660,11 @@ fn ban_row( ban: &Ban, entity: &Entity, palette: Palette, - avatars: &HashMap>, + avatars: &HashMap>, ) -> Div { let entity = entity.clone(); let user = &ban.user; - let user_id = user.id.clone(); + let user_id = user.id; div() .h(px(48.)) @@ -711,7 +700,7 @@ fn ban_row( ) .child( clickable(format!("unban_{}", user.id), palette, move |window, cx| { - entity.update(cx, |yumush, cx| yumush.unban(&user_id, window, cx)); + entity.update(cx, |yumush, cx| yumush.unban(user_id, window, cx)); }) .h(px(28.)) .px(px(8.)) diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index b5c124d..1ce4fce 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -1,5 +1,6 @@ use super::text; use super::widget::{compact_field, icon_button, panel, spawn_done}; +use common::model::Id; use std::time::{Duration, Instant}; use crate::net::Fail; @@ -57,9 +58,9 @@ fn shortcut_label(keys: &str) -> String { #[derive(Debug, Clone, PartialEq, Eq)] pub enum Composer { - Compose { reply: Option }, - Edit { message_id: String }, - Select { ids: Vec }, + Compose { reply: Option }, + Edit { message_id: Id }, + Select { ids: Vec }, } const SLOW_TICK: Duration = Duration::from_secs(1); @@ -72,17 +73,13 @@ pub fn mode_bar(chat: &Chat, entity: &Entity, palette: Palette) -> Optio match &chat.composer { Composer::Compose { reply: Some(message_id), - } => Some(reply_bar(chat, message_id, entity, palette).into_any_element()), + } => Some(reply_bar(chat, *message_id, entity, palette).into_any_element()), Composer::Edit { .. } => Some(edit_bar(entity, palette).into_any_element()), Composer::Compose { reply: None } | Composer::Select { .. } => None, } } -pub fn selection_bar( - ids: &[String], - entity: &Entity, - palette: Palette, -) -> impl IntoElement { +pub fn selection_bar(ids: &[Id], entity: &Entity, palette: Palette) -> impl IntoElement { let count = ids.len(); let selected = ids.to_vec(); let forward_entity = entity.clone(); @@ -131,7 +128,7 @@ fn bar(palette: Palette) -> Div { fn reply_bar( chat: &Chat, - message_id: &str, + message_id: Id, entity: &Entity, palette: Palette, ) -> impl IntoElement { @@ -140,11 +137,13 @@ fn reply_bar( .iter() .find(|message| message.id == message_id); let author = message - .and_then(|message| chat.author(&message.user_id)) + .and_then(|message| chat.author(message.user_id)) .map_or("unknown", |user| user.username.as_str()) .to_string(); let quote = message - .map(|message| super::message_actions::quote_text(&message.body, message.attachments.len())) + .map(|message| { + super::message_actions::quote_text(&message.body, message.attachments.len() as u32) + }) .unwrap_or_default(); bar(palette) @@ -210,7 +209,7 @@ impl Yumush { } pub(super) fn send_typing(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; if self @@ -228,9 +227,7 @@ impl Yumush { { return; } - self.chat - .typing_sent - .insert(community_id.clone(), Instant::now()); + self.chat.typing_sent.insert(community_id, Instant::now()); let network = self.network.clone(); cx.spawn(async move |_, _| { let _ = network.call(Typing { community_id }).await; @@ -240,18 +237,18 @@ impl Yumush { fn create_message( &mut self, - reply: Option, + reply: Option, body: String, input: &Entity, window: &mut Window, cx: &mut Context, ) { - let attachments: Vec = self + let attachments: Vec = self .chat .media .pending .iter() - .map(|attachment| attachment.id.clone()) + .map(|attachment| attachment.id) .collect(); if self.chat.slow_seconds().is_some() { @@ -262,7 +259,7 @@ impl Yumush { window.push_notification(Notification::error(error.to_string()), cx); return; } - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { window.push_notification(Notification::error("No Community Selected"), cx); return; }; @@ -274,7 +271,7 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { match network .call(CreateMessage { - community_id: community_id.clone(), + community_id, body: body.clone(), attachments, reply_to: reply, @@ -286,13 +283,13 @@ impl Yumush { retry_after_seconds, })) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.restore_message(&restore, &community_id, body, pending, window, cx); + yumush.restore_message(&restore, community_id, body, pending, window, cx); yumush.slow_down(retry_after_seconds, window, cx) }); } Err(error) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.restore_message(&restore, &community_id, body, pending, window, cx) + yumush.restore_message(&restore, community_id, body, pending, window, cx) }); notify_error(&this, cx, error); } @@ -308,14 +305,14 @@ impl Yumush { fn restore_message( &mut self, input: &Entity, - community_id: &str, + community_id: Id, body: String, pending: Vec, window: &mut Window, cx: &mut Context, ) { - if self.chat.selected_community_id.as_deref() != Some(community_id) { - self.chat.drafts.insert(community_id.to_string(), body); + if self.chat.selected_community_id != Some(community_id) { + self.chat.drafts.insert(community_id, body); return; } if input.read(cx).text().len() == 0 { @@ -347,7 +344,7 @@ impl Yumush { fn update_message( &mut self, - message_id: String, + message_id: Id, body: String, input: &Entity, window: &mut Window, @@ -363,7 +360,7 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { if let Err(error) = network .call(UpdateMessage { - message_id: message_id.clone(), + message_id, body: body.clone(), }) .await @@ -386,7 +383,7 @@ impl Yumush { } pub(super) fn save_draft(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let text = self.chat.message_input.read(cx).text().to_string(); @@ -399,14 +396,14 @@ impl Yumush { pub(super) fn restore_draft( &mut self, - community_id: &str, + community_id: Id, window: &mut Window, cx: &mut Context, ) { let text = self .chat .drafts - .get(community_id) + .get(&community_id) .cloned() .unwrap_or_default(); self.chat @@ -414,12 +411,7 @@ impl Yumush { .update(cx, |input, cx| input.set_value(text, window, cx)); } - pub(super) fn reply( - &mut self, - message_id: String, - window: &mut Window, - cx: &mut Context, - ) { + pub(super) fn reply(&mut self, message_id: Id, window: &mut Window, cx: &mut Context) { self.chat.composer = Composer::Compose { reply: Some(message_id), }; @@ -427,7 +419,7 @@ impl Yumush { cx.notify(); } - pub(super) fn edit(&mut self, message_id: String, window: &mut Window, cx: &mut Context) { + pub(super) fn edit(&mut self, message_id: Id, window: &mut Window, cx: &mut Context) { let Some(body) = self .chat .messages @@ -448,7 +440,7 @@ impl Yumush { pub(super) fn start_select( &mut self, - message_id: String, + message_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -459,14 +451,14 @@ impl Yumush { cx.notify(); } - pub(super) fn toggle_select(&mut self, message_id: &str, cx: &mut Context) { + pub(super) fn toggle_select(&mut self, message_id: Id, cx: &mut Context) { let Composer::Select { ids } = &mut self.chat.composer else { return; }; - if let Some(index) = ids.iter().position(|id| id == message_id) { + if let Some(index) = ids.iter().position(|id| *id == message_id) { ids.remove(index); } else if ids.len() < MAXIMUM_FORWARD_MESSAGES { - ids.push(message_id.to_string()); + ids.push(message_id); } cx.notify(); } @@ -690,7 +682,7 @@ impl Yumush { } pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context) -> bool { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return false; }; let question = self.chat.poll_question.read(cx).text().to_string(); diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index f7c3158..6c6a273 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -1,5 +1,6 @@ use super::text; use common::call::ForwardMessages; +use common::model::Id; use gpui_kit::{ AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, @@ -20,7 +21,7 @@ use super::{ pub struct Forward { yumush: Entity, - selected: Vec, + selected: Vec, filter: Entity, keep_authors: bool, } @@ -28,7 +29,7 @@ pub struct Forward { impl Forward { fn new( yumush: Entity, - selected: Vec, + selected: Vec, window: &mut Window, cx: &mut Context, ) -> Self { @@ -69,12 +70,11 @@ impl Render for Forward { .filter(|community| community_name(community).to_lowercase().contains(&query)) .enumerate() .map(|(index, community)| { - let community_id = community.id.clone(); + let community_id = community.id; let selected = self.selected.clone(); let forward_entity = self.yumush.clone(); clickable(("forward_to", index), palette, move |window, cx| { - let community_id = community_id.clone(); let selected = selected.clone(); forward_entity.update(cx, |yumush, cx| { yumush.forward_to(selected, community_id, keep_authors, window, cx) @@ -130,7 +130,7 @@ impl Render for Forward { impl Yumush { pub(super) fn open_forward( &mut self, - selected: Vec, + selected: Vec, window: &mut Window, cx: &mut Context, ) { @@ -147,8 +147,8 @@ impl Yumush { pub(super) fn forward_to( &mut self, - selected: Vec, - community_id: String, + selected: Vec, + community_id: Id, keep_authors: bool, window: &mut Window, cx: &mut Context, @@ -158,12 +158,12 @@ impl Yumush { self.chat.composer = Composer::Compose { reply: None }; } - let ids: Vec = self + let ids: Vec = self .chat .messages .iter() .filter(|message| selected.contains(&message.id)) - .map(|message| message.id.clone()) + .map(|message| message.id) .collect(); let network = self.network.clone(); diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index 9600ed4..8af7e1a 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -1,4 +1,5 @@ use super::text; +use common::model::Id; use std::{ collections::{HashMap, HashSet}, path::PathBuf, @@ -55,7 +56,7 @@ pub enum PlayState { } pub struct Playing { - attachment_id: String, + attachment_id: Id, state: PlayState, } @@ -64,10 +65,11 @@ pub struct Media { pub pending: Vec, pub(super) uploading: usize, pub(super) voice_note: VoiceNote, - thumbnails: HashMap>, - waveforms: HashMap, + thumbnails: HashMap>, + waveforms: HashMap, embeds: HashMap, - requested: HashSet, + requested: HashSet, + requested_links: HashSet, playing: Option, } @@ -148,7 +150,7 @@ fn duration_secs(player: &Player) -> f32 { pub(super) async fn upload_file( this: &WeakEntity, network: &NetworkHandle, - community_id: &str, + community_id: Id, path: PathBuf, maximum: Option, cx: &mut AsyncWindowContext, @@ -179,8 +181,8 @@ impl Yumush { for message in &self.chat.messages { let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages); for item in forwarded.clone() { - if let Some(avatar_id) = &item.avatar_id { - avatars.push(avatar_id.clone()); + if let Some(avatar_id) = item.avatar_id { + avatars.push(avatar_id); } } for attachment in message @@ -189,31 +191,31 @@ impl Yumush { .chain(forwarded.flat_map(|item| &item.attachments)) { if attachment.kind == AttachmentKind::Image - && self.chat.media.requested.insert(attachment.id.clone()) + && self.chat.media.requested.insert(attachment.id) { - thumbnails.push(attachment.id.clone()); + thumbnails.push(attachment.id); } if note::is_voice_note(attachment) - && self.chat.media.requested.insert(attachment.id.clone()) + && self.chat.media.requested.insert(attachment.id) { voices.push(attachment.clone()); } } for url in embed::urls(&message.body) { - if self.chat.media.requested.insert(url.clone()) { + if self.chat.media.requested_links.insert(url.clone()) { links.push(url); } } } for avatar_id in avatars { - self.request_avatar(&avatar_id, cx); + self.request_avatar(avatar_id, cx); } for attachment_id in thumbnails { let network = self.network.clone(); cx.spawn(async move |this, cx| { - let Ok(bytes) = network.download_attachment(&attachment_id, true).await else { + let Ok(bytes) = network.download_attachment(attachment_id, true).await else { return; }; let _ = this.update(cx, |yumush, cx| { @@ -228,7 +230,7 @@ impl Yumush { for attachment in voices { let fetched = self.fetch_file(&attachment, cx); - let attachment_id = attachment.id.clone(); + let attachment_id = attachment.id; cx.spawn(async move |this, cx| { let Ok(path) = fetched.await else { return; @@ -275,7 +277,7 @@ impl Yumush { } pub(super) fn attach_files(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let picked = cx.prompt_for_paths(PathPromptOptions { @@ -295,7 +297,7 @@ impl Yumush { return; }; for path in paths { - let result = upload_file(&this, &network, &community_id, path, maximum, cx).await; + let result = upload_file(&this, &network, community_id, path, maximum, cx).await; let _ = this.update(cx, |yumush, cx| { if let Ok(attachment) = &result { yumush.chat.media.pending.push(attachment.clone()); @@ -310,7 +312,7 @@ impl Yumush { .detach(); } - fn remove_pending(&mut self, attachment_id: &str, cx: &mut Context) { + fn remove_pending(&mut self, attachment_id: Id, cx: &mut Context) { self.chat .media .pending @@ -330,7 +332,7 @@ impl Yumush { if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) { return Ok(path); } - let bytes = network.download_attachment(&attachment.id, false).await?; + let bytes = network.download_attachment(attachment.id, false).await?; cx.background_executor() .spawn({ let path = path.clone(); @@ -393,14 +395,14 @@ impl Yumush { } self.stop_playing(cx); self.chat.media.playing = Some(Playing { - attachment_id: attachment.id.clone(), + attachment_id: attachment.id, state: PlayState::Loading, }); cx.notify(); let fetched = self.fetch_file(attachment, cx); let choice = self.settings.voice.choice.clone(); - let attachment_id = attachment.id.clone(); + let attachment_id = attachment.id; cx.spawn_in(window, async move |this, cx| { let opened = match fetched.await { Ok(path) => cx @@ -435,7 +437,7 @@ impl Yumush { fn start_player( &mut self, - attachment_id: String, + attachment_id: Id, player: Player, window: &mut Window, cx: &mut Context, @@ -878,7 +880,7 @@ pub fn pending_row( .pb(px(8.)) .children(media.pending.iter().map(|attachment| { let entity = entity.clone(); - let attachment_id = attachment.id.clone(); + let attachment_id = attachment.id; div() .flex() .items_center() @@ -901,7 +903,7 @@ pub fn pending_row( palette, move |_, cx| { entity.update(cx, |yumush, cx| { - yumush.remove_pending(&attachment_id, cx) + yumush.remove_pending(attachment_id, cx) }) }, ) diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index 8a183d3..bf8d281 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -1,4 +1,5 @@ use super::text; +use common::model::Id; use common::{ call::{Pin, React, ReportMessage, ReportUser}, constant::REACTIONS, @@ -23,7 +24,7 @@ use super::{ chat::{Chat, ReportTarget}, clickable, composer::trigger_icon, - entity_action, id_time, notify_error, pop_in, primary_button, sidebar, + entity_action, millis_time, notify_error, pop_in, primary_button, sidebar, widget::{field, icon_button, panel, spawn_done}, }; @@ -33,7 +34,7 @@ pub fn reactions( entity: &Entity, palette: Palette, ) -> impl IntoElement { - let me_id = me.map(|me| me.id.clone()); + let me_id = me.map(|me| me.id); div() .flex() @@ -44,7 +45,7 @@ pub fn reactions( .as_ref() .is_some_and(|id| reaction.user_ids.contains(id)); let entity = entity.clone(); - let message_id = message.id.clone(); + let message_id = message.id; let emoji = reaction.emoji.clone(); let chip_emoji = reaction.emoji.clone(); let count = reaction.user_ids.len(); @@ -53,7 +54,6 @@ pub fn reactions( format!("reaction_{}_{}", message.id, reaction.emoji), palette, move |window, cx| { - let message_id = message_id.clone(); let emoji = emoji.clone(); entity.update(cx, |yumush, cx| { yumush.toggle_reaction(message_id, emoji, window, cx) @@ -84,7 +84,7 @@ pub fn react_popover( entity: &Entity, palette: Palette, ) -> impl IntoElement { - let message_id = message.id.clone(); + let message_id = message.id; let entity = entity.clone(); Popover::new(format!("react_{}", message.id)) @@ -106,14 +106,12 @@ pub fn react_popover( .p(px(4.)) .children(REACTIONS.map(|emoji| { let entity = entity.clone(); - let message_id = message_id.clone(); let popover = popover.clone(); clickable( format!("react_{emoji}_{message_id}"), palette, move |window, cx| { popover.update(cx, |state, cx| state.dismiss(window, cx)); - let message_id = message_id.clone(); entity.update(cx, |yumush, cx| { yumush.toggle_reaction( message_id, @@ -137,7 +135,7 @@ pub fn react_popover( }) } -pub fn quote_text(body: &str, attachments: usize) -> String { +pub fn quote_text(body: &str, attachments: u32) -> String { if body.is_empty() { format!("{attachments} attachments") } else { @@ -147,7 +145,7 @@ pub fn quote_text(body: &str, attachments: usize) -> String { pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option { let quote = message.reply.as_ref()?; - let author = chat.author("e.user_id); + let author = chat.author(quote.user_id); Some( div() @@ -164,7 +162,7 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option impl IntoElement { } struct Hit { - message_id: String, + message_id: Id, name: String, time: Option, body: String, @@ -227,7 +225,7 @@ fn jump_row( ) -> Stateful
{ let entity = entity.clone(); let popover = popover.clone(); - let message_id = hit.message_id.clone(); + let message_id = hit.message_id; clickable( format!("{prefix}_{message_id}"), @@ -235,7 +233,7 @@ fn jump_row( move |window, cx| { popover.update(cx, |state, cx| state.dismiss(window, cx)); entity.update(cx, |yumush, cx| { - yumush.go_to_message(message_id.clone(), window, cx) + yumush.go_to_message(message_id, window, cx) }); }, ) @@ -260,14 +258,14 @@ pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> .community_hits .iter() .map(|hit| Hit { - message_id: hit.message.id.clone(), + message_id: hit.message.id, name: hit .author .as_ref() .map(|user| user.username.clone()) .unwrap_or_default(), - time: Some(id_time(&hit.message.id, CLOCK)), - body: quote_text(&hit.message.body, hit.message.attachments.len()), + time: Some(millis_time(hit.message.created_at, CLOCK)), + body: quote_text(&hit.message.body, hit.message.attachments.len() as u32), }) .collect(); @@ -312,13 +310,13 @@ pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i .pins .iter() .map(|pin| Hit { - message_id: pin.id.clone(), + message_id: pin.id, name: chat - .author(&pin.user_id) + .author(pin.user_id) .map(|user| user.username.clone()) .unwrap_or_default(), time: None, - body: quote_text(&pin.body, pin.attachments.len()), + body: quote_text(&pin.body, pin.attachments.len() as u32), }) .collect(); @@ -364,8 +362,8 @@ pub fn actions( let deletable = me.is_some_and(|me| chat.can_delete(message, me)); let pinnable = me.is_some_and(|me| chat.can_pin(me)); let reportable = me.is_some_and(|me| me.id != message.user_id); - let id = message.id.as_str(); - let armed = chat.pending_message_delete.as_deref() == Some(id); + let id = message.id; + let armed = chat.pending_message_delete == Some(id); panel(palette) .flex() @@ -477,7 +475,7 @@ pub fn report_bar( impl Yumush { pub(super) fn toggle_pin( &mut self, - message_id: String, + message_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -500,7 +498,7 @@ impl Yumush { pub(super) fn toggle_reaction( &mut self, - message_id: String, + message_id: Id, emoji: String, window: &mut Window, cx: &mut Context, @@ -565,13 +563,12 @@ impl Yumush { fn action( entity: &Entity, palette: Palette, - message_id: &str, + message_id: Id, tip: &'static str, icon: IconName, - run: fn(&mut Yumush, String, &mut Window, &mut Context), + run: fn(&mut Yumush, Id, &mut Window, &mut Context), ) -> Stateful
{ let entity = entity.clone(); - let message_id = message_id.to_string(); icon_button( format!("{tip}_{message_id}"), @@ -579,7 +576,6 @@ fn action( icon, tip, move |window, cx| { - let message_id = message_id.clone(); entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); }, ) diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index 4cbb198..ae891cd 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::collections::HashSet; use common::call::{ClosePoll, Vote}; @@ -22,11 +23,11 @@ pub fn voter_count(poll: &Poll) -> usize { .len() } -fn my_positions(poll: &Poll, user_id: &str) -> Vec { +fn my_positions(poll: &Poll, user_id: Id) -> Vec { poll.options .iter() .enumerate() - .filter(|(_, option)| option.voter_ids.iter().any(|id| id == user_id)) + .filter(|(_, option)| option.voter_ids.contains(&user_id)) .map(|(position, _)| position as u32) .collect() } @@ -50,7 +51,7 @@ fn percent(count: usize, voters: usize) -> usize { pub enum PollMode<'a> { Live(&'a Message), - Snapshot(&'a str), + Snapshot(Id), } pub fn poll_card( @@ -62,15 +63,15 @@ pub fn poll_card( palette: Palette, ) -> impl IntoElement { let voters = voter_count(poll); - let me_id = me.map(|me| me.id.as_str()); + let me_id = me.map(|me| me.id); let mine = me_id.map(|id| my_positions(poll, id)).unwrap_or_default(); let (key, live) = match mode { - PollMode::Live(message) => (message.id.clone(), Some(message)), + PollMode::Live(message) => (message.id.to_string(), Some(message)), PollMode::Snapshot(id) => (format!("snapshot_{id}"), None), }; let vote_id = live .filter(|_| !poll.closed && me_id.is_some()) - .map(|message| message.id.clone()); + .map(|message| message.id); let close_id = live .filter(|message| { !poll.closed @@ -78,7 +79,7 @@ pub fn poll_card( me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator) }) }) - .map(|message| message.id.clone()); + .map(|message| message.id); let rows = poll.options.iter().enumerate().map(|(position, option)| { let count = option.voter_ids.len(); @@ -89,10 +90,9 @@ pub fn poll_card( .unwrap_or_default(); let entity = entity.clone(); let id = format!("poll_option_{key}_{position}"); - match vote_id.clone() { + match vote_id { Some(message_id) => clickable(id, palette, move |window, cx| { let next = next.clone(); - let message_id = message_id.clone(); entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx)); }), None => div().id(id), @@ -172,7 +172,6 @@ pub fn poll_card( IconName::CircleStop, "End poll", move |window, cx| { - let close_id = close_id.clone(); close_entity.update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); }, ) @@ -222,7 +221,7 @@ impl Yumush { let expanded = self.chat.poll_expanded; let toggle = entity.clone(); let jump = entity.clone(); - let message_id = message.id.clone(); + let message_id = message.id; Some( div() @@ -289,7 +288,6 @@ impl Yumush { IconName::ArrowUpRight, "Jump to message", move |window, cx| { - let message_id = message_id.clone(); jump.update(cx, |yumush, cx| { yumush.go_to_message(message_id, window, cx) }); @@ -311,7 +309,7 @@ impl Yumush { pub(super) fn vote( &mut self, - message_id: String, + message_id: Id, positions: Vec, window: &mut Window, cx: &mut Context, @@ -330,7 +328,7 @@ impl Yumush { pub(super) fn close_poll( &mut self, - message_id: String, + message_id: Id, window: &mut Window, cx: &mut Context, ) { diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index 44967b0..d5c247a 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::{collections::HashMap, sync::Arc}; use common::{ @@ -24,8 +25,8 @@ use super::message_actions::report_bar; use super::social::Relation; use super::widget::{panel, spawn_done}; use super::{ - DAY_YEAR, Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, - notify_error, palette, pop_in, presence_color, rank_tag, swap_in, text, + DAY_YEAR, Palette, Trigger, Yumush, avatar, clickable, entity_action, input_dialog, + millis_time, notify_error, palette, pop_in, presence_color, rank_tag, swap_in, text, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -73,7 +74,7 @@ pub(super) fn profile_popover( let user = user.clone(); let entity = entity.clone(); let notify_entity = entity.clone(); - let volume_user_id = user.id.clone(); + let volume_user_id = user.id; Popover::new(id) .anchor(anchor) @@ -82,7 +83,7 @@ pub(super) fn profile_popover( notify_entity.update(cx, |yumush, cx| { yumush.chat.card_menu = CardMenu::Main; yumush.chat.pending_user_delete = None; - yumush.open_user_volume(&volume_user_id, cx); + yumush.open_user_volume(volume_user_id, cx); cx.notify() }) }) @@ -93,23 +94,23 @@ pub(super) fn profile_popover( viewer: yumush.user.clone(), actor: yumush.actor_rank(), target: yumush.chat.rank_of(&user), - relation: yumush.relation(&user.id), + relation: yumush.relation(user.id), card_menu: yumush.chat.card_menu, - presence: yumush.presence_of(&user.id), - confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()), - reporting: yumush.chat.report == Some(ReportTarget::User(user.id.clone())), + presence: yumush.presence_of(user.id), + confirming: yumush.chat.pending_user_delete == Some(user.id), + reporting: yumush.chat.report == Some(ReportTarget::User(user.id)), reason: yumush.chat.report_reason.clone(), others: yumush .accounts .others() - .map(|account| (account.user_id.clone(), account.username.clone())) + .map(|account| (account.user_id, account.username.clone())) .collect(), volume: yumush .chat .user_volume .as_ref() .filter(|volume| volume.user_id == user.id) - .map(|volume| (volume.slider.clone(), yumush.user_volume(&user.id))), + .map(|volume| (volume.slider.clone(), yumush.user_volume(user.id))), user: user.clone(), }; @@ -132,7 +133,7 @@ struct Card { confirming: bool, reporting: bool, reason: Entity, - others: Vec<(String, String)>, + others: Vec<(Id, String)>, volume: Option<(Entity, f32)>, } @@ -143,8 +144,8 @@ impl Card { popover: &Entity, palette: Palette, ) -> Vec { - let user_id = self.user.id.clone(); - let message_id = user_id.clone(); + let user_id = self.user.id; + let message_id = user_id; let mut rows = vec![ menu_row( "profile_message", @@ -153,13 +154,13 @@ impl Card { palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { - yumush.open_direct(message_id.clone(), window, cx) + yumush.open_direct(message_id, window, cx) }), ) .into_any_element(), ]; - let report_user_id = self.user.id.clone(); + let report_user_id = self.user.id; rows.push( menu_row( "profile_report", @@ -168,7 +169,7 @@ impl Card { palette.danger, palette, entity_action(entity, move |yumush, window, cx| { - yumush.start_report(ReportTarget::User(report_user_id.clone()), window, cx) + yumush.start_report(ReportTarget::User(report_user_id), window, cx) }), ) .into_any_element(), @@ -184,7 +185,7 @@ impl Card { palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { - yumush.friend_action(relation, user_id.clone(), window, cx) + yumush.friend_action(relation, user_id, window, cx) }), ) .into_any_element(), @@ -199,7 +200,7 @@ impl Card { entity: &Entity, popover: Entity, palette: Palette, - avatars: &HashMap>, + avatars: &HashMap>, ) -> Div { let is_self = self .viewer @@ -261,7 +262,10 @@ impl Card { div() .text_size(text(12.)) .text_color(palette.muted) - .child(format!("Joined {}", id_time(&self.user.id, DAY_YEAR))), + .child(format!( + "Joined {}", + millis_time(self.user.created_at, DAY_YEAR) + )), ) .children(self.volume.map(|(slider, volume)| { div() @@ -294,12 +298,11 @@ impl Card { ) -> Vec { let actor = self.actor; let target = self.target; - let user_id = self.user.id.clone(); + let user_id = self.user.id; let mut rows = Vec::new(); for rank in [Rank::Member, Rank::Moderator, Rank::Admin] { if target != Some(rank) && permission::can_set_rank(actor, target, rank) { - let user_id = user_id.clone(); let label = format!("Make {}", rank.label().to_lowercase()); rows.push( menu_row( @@ -309,7 +312,7 @@ impl Card { palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { - yumush.set_member_rank(&user_id, rank, window, cx) + yumush.set_member_rank(user_id, rank, window, cx) }), ) .into_any_element(), @@ -318,8 +321,8 @@ impl Card { } if permission::can_moderate(actor, target) { - let kick_id = user_id.clone(); - let ban_id = user_id.clone(); + let kick_id = user_id; + let ban_id = user_id; rows.push( menu_row( "kick", @@ -328,7 +331,7 @@ impl Card { palette.danger, palette, yumush_action(entity, popover, move |yumush, window, cx| { - yumush.open_removal(kick_id.clone(), Removal::Kick, window, cx) + yumush.open_removal(kick_id, Removal::Kick, window, cx) }), ) .into_any_element(), @@ -341,7 +344,7 @@ impl Card { palette.danger, palette, yumush_action(entity, popover, move |yumush, window, cx| { - yumush.open_removal(ban_id.clone(), Removal::Ban, window, cx) + yumush.open_removal(ban_id, Removal::Ban, window, cx) }), ) .into_any_element(), @@ -366,7 +369,7 @@ impl Card { menu_icon(IconName::Trash), palette.danger, palette, - delete_user_action(&user_id, self.confirming, entity, popover), + delete_user_action(user_id, self.confirming, entity, popover), ) .into_any_element(), ); @@ -377,7 +380,7 @@ impl Card { } fn self_rows( - others: &[(String, String)], + others: &[(Id, String)], card_menu: CardMenu, presence: Presence, entity: &Entity, @@ -440,13 +443,12 @@ fn main_self_rows( } fn accounts_rows( - others: &[(String, String)], + others: &[(Id, String)], entity: &Entity, popover: &Entity, palette: Palette, ) -> Vec { - let accounts = others.iter().map(|(user_id, username)| { - let user_id = user_id.clone(); + let accounts = others.iter().map(|&(user_id, ref username)| { menu_row( format!("switch_{user_id}"), username.clone(), @@ -454,7 +456,7 @@ fn accounts_rows( palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { - yumush.switch_account(user_id.clone(), window, cx) + yumush.switch_account(user_id, window, cx) }), ) }); @@ -553,12 +555,11 @@ fn yumush_action( } fn delete_user_action( - user_id: &str, + user_id: Id, confirming: bool, entity: &Entity, popover: &Entity, ) -> impl Fn(&mut Window, &mut App) + 'static { - let user_id = user_id.to_string(); let entity = entity.clone(); let popover = popover.clone(); @@ -566,10 +567,10 @@ fn delete_user_action( if confirming { popover.update(cx, |state, cx| state.dismiss(window, cx)); entity.update(cx, |yumush, cx| { - yumush.delete_member_account(&user_id, window, cx) + yumush.delete_member_account(user_id, window, cx) }); } else { - entity.update(cx, |yumush, cx| yumush.request_member_delete(&user_id, cx)); + entity.update(cx, |yumush, cx| yumush.request_member_delete(user_id, cx)); } } } @@ -607,12 +608,12 @@ fn drill_row(row: Stateful
) -> AnyElement { impl Yumush { fn open_removal( &self, - user_id: String, + user_id: Id, removal: Removal, window: &mut Window, cx: &mut Context, ) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; input_dialog( @@ -624,23 +625,21 @@ impl Yumush { move |this, text, window, cx| { let reason = text.trim().to_string(); let reason = (!reason.is_empty()).then_some(reason); - this.remove_member(&community_id, &user_id, removal, reason, window, cx); + this.remove_member(community_id, user_id, removal, reason, window, cx); }, ); } fn remove_member( &self, - community_id: &str, - user_id: &str, + community_id: Id, + user_id: Id, removal: Removal, reason: Option, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); - let community_id = community_id.to_string(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { let result = match removal { @@ -680,16 +679,15 @@ impl Yumush { pub(super) fn set_member_rank( &self, - user_id: &str, + user_id: Id, rank: Rank, window: &mut Window, cx: &mut Context, ) { - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); - let user_id = user_id.to_string(); spawn_done(window, cx, async move { network @@ -709,7 +707,7 @@ impl Yumush { cx: &mut Context, ) { if let Some(me) = &self.user { - self.chat.presences.insert(me.id.clone(), presence); + self.chat.presences.insert(me.id, presence); } self.chat.card_menu = CardMenu::Main; cx.notify(); @@ -721,31 +719,25 @@ impl Yumush { }); } - pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context) { - self.chat.pending_user_delete = Some(user_id.to_string()); + pub(super) fn request_member_delete(&mut self, user_id: Id, cx: &mut Context) { + self.chat.pending_user_delete = Some(user_id); cx.notify(); } pub(super) fn delete_member_account( &mut self, - user_id: &str, + user_id: Id, window: &mut Window, cx: &mut Context, ) { self.chat.pending_user_delete = None; let network = self.network.clone(); - let user_id = user_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network - .call(DeleteUser { - user_id: user_id.clone(), - }) - .await - { + match network.call(DeleteUser { user_id }).await { Ok(()) => { let _ = this.update(cx, |yumush, cx| { - yumush.chat.remove_member(&user_id); + yumush.chat.remove_member(user_id); cx.notify(); }); } diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 66fbd2a..a43e562 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -222,7 +222,7 @@ impl Yumush { if !self.confirm_delete(cx) { return; } - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { + let Some(user_id) = self.user.as_ref().map(|user| user.id) else { return; }; let network = self.network.clone(); diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index ebf4217..dd6fbdc 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::{collections::VecDeque, sync::Arc, time::Duration}; use common::share::{Codec, Fps, Kind, Quality, Resolution, Source, options}; @@ -77,7 +78,7 @@ impl AudioMode { } pub(super) struct Viewer { - user_id: String, + user_id: Id, kind: Kind, generation: Option, frame: Option>, @@ -88,11 +89,11 @@ pub(super) struct Viewer { } impl Yumush { - pub(super) fn load_shares(&self, community_id: String, cx: &mut Context) { + pub(super) fn load_shares(&self, community_id: Id, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { - let Ok(shares) = network.shares(&community_id).await else { + let Ok(shares) = network.shares(community_id).await else { return; }; let _ = this.update(cx, |yumush, cx| { @@ -195,29 +196,29 @@ impl Yumush { self.update_share(cx, |settings| settings.watch = watch); } - pub(super) fn is_watching(&self, user_id: &str, kind: Kind) -> bool { + pub(super) fn is_watching(&self, user_id: Id, kind: Kind) -> bool { self.chat .viewer .as_ref() .is_some_and(|viewer| viewer.user_id == user_id && viewer.kind == kind) } - pub(super) fn viewing_camera(&self) -> Option { + pub(super) fn viewing_camera(&self) -> Option { self.chat .viewer .as_ref() .filter(|viewer| viewer.kind == Kind::Camera) - .map(|viewer| viewer.user_id.clone()) + .map(|viewer| viewer.user_id) } pub(super) fn toggle_viewer( &mut self, - user_id: String, + user_id: Id, kind: Kind, window: &mut Window, cx: &mut Context, ) { - let watching = self.is_watching(&user_id, kind); + let watching = self.is_watching(user_id, kind); self.close_viewer(cx); if watching { return; @@ -249,7 +250,7 @@ impl Yumush { }); self.chat.viewer = Some(Viewer { - user_id: user_id.clone(), + user_id, kind, generation: None, frame: None, @@ -264,15 +265,15 @@ impl Yumush { let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); if kind == Kind::Camera && self.chat.cameras.contains_key(&user_id) { - network.set_watch_quality(&user_id, kind, watch); + network.set_watch_quality(user_id, kind, watch); } else { cx.spawn_in(window, async move |this, cx| { if let Err(error) = network - .watch_share(&user_id, kind, watch, volume, choice) + .watch_share(user_id, kind, watch, volume, choice) .await { let _ = this.update(cx, |yumush, cx| { - if yumush.is_watching(&user_id, kind) { + if yumush.is_watching(user_id, kind) { yumush.close_viewer(cx); } }); @@ -293,12 +294,12 @@ impl Yumush { } let network = self.network.clone(); if viewer.kind == Kind::Camera && self.chat.cameras.contains_key(&viewer.user_id) { - network.set_watch_quality(&viewer.user_id, viewer.kind, camera_view::CAMERA_TILE); + network.set_watch_quality(viewer.user_id, viewer.kind, camera_view::CAMERA_TILE); } else { - let user_id = viewer.user_id.clone(); + let user_id = viewer.user_id; let kind = viewer.kind; cx.spawn(async move |_, _| { - let _ = network.unwatch_share(&user_id, kind).await; + let _ = network.unwatch_share(user_id, kind).await; }) .detach(); } @@ -309,7 +310,7 @@ impl Yumush { let Some(viewer) = self.chat.viewer.as_mut() else { return; }; - let Some(frame) = self.network.share_frame(&viewer.user_id, viewer.kind) else { + let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else { return; }; if viewer.generation == Some(frame.generation) { @@ -421,7 +422,7 @@ impl Yumush { ) } - fn share_top(&self, user_id: &str, kind: Kind) -> Quality { + fn share_top(&self, user_id: Id, kind: Kind) -> Quality { self.chat .voice_community() .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) @@ -434,7 +435,7 @@ impl Yumush { } else { (IconName::Maximize, "Fullscreen") }; - let top = self.share_top(&viewer.user_id, viewer.kind); + let top = self.share_top(viewer.user_id, viewer.kind); let audio = viewer.kind == Kind::Screen; div() @@ -477,7 +478,7 @@ impl Yumush { .then(|| { self.chat .waves - .share(&viewer.user_id) + .share(viewer.user_id) .map(|history| wave(history, 14., palette.alert)) }) .flatten(), @@ -561,18 +562,16 @@ fn quality_chips( pub(super) fn share_badge( entity: &Entity, - user_id: &str, + user_id: Id, sound: Option<&VecDeque>, palette: Palette, ) -> impl IntoElement { let entity = entity.clone(); - let user_id = user_id.to_string(); clickable( format!("share_badge_{user_id}"), palette, move |window, cx| { - let user_id = user_id.clone(); entity.update(cx, |yumush, cx| { yumush.toggle_viewer(user_id, Kind::Screen, window, cx) }); diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 0f44d5e..36dcfed 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -1,4 +1,5 @@ use super::text; +use common::model::Id; use common::{ model::{Community, CommunityKind, Invitation, Role, Unread, User}, permission, @@ -146,10 +147,10 @@ impl Yumush { let stats_entity = entity.clone(); let members: Vec<_> = self .chat - .voice_ids(&community.id) + .voice_ids(community.id) .iter() - .filter_map(|id| self.chat.author(id)) - .map(|user| self.voice_member(entity, &community.id, user, palette)) + .filter_map(|id| self.chat.author(*id)) + .map(|user| self.voice_member(entity, community.id, user, palette)) .collect(); let controls = div() @@ -230,13 +231,13 @@ impl Yumush { fn voice_member( &self, entity: &Entity, - community_id: &str, + community_id: Id, user: &User, palette: Palette, ) -> impl IntoElement { let speaking = self.chat.waves.speaking.contains(&user.id); - let share = self.chat.waves.share(&user.id); - let sharing = share.is_none() && self.chat.is_sharing(community_id, &user.id); + let share = self.chat.waves.share(user.id); + let sharing = share.is_none() && self.chat.is_sharing(community_id, user.id); profile_popover( format!("voice_member_{}", user.id), @@ -282,7 +283,7 @@ impl Yumush { .children( self.chat .waves - .voice(&user.id) + .voice(user.id) .map(|history| wave(history, 12., palette.ok)), ), ) @@ -317,12 +318,12 @@ impl Yumush { pub(super) fn go_to_community( &mut self, - community_id: String, + community_id: Id, direct: bool, window: &mut Window, cx: &mut Context, ) { - if self.chat.view == View::Chat && self.chat.is_selected(&community_id) { + if self.chat.view == View::Chat && self.chat.is_selected(community_id) { return; } self.chat.tab = if direct { @@ -408,7 +409,7 @@ impl Yumush { .chat .found .as_ref() - .filter(|user| !self.is_listed(&user.id)); + .filter(|user| !self.is_listed(user.id)); div() .flex() @@ -438,7 +439,7 @@ impl Yumush { fn notes_row(&self, entity: &Entity, palette: Palette) -> AnyElement { let notes = self.chat.notes(); - let active = notes.is_some_and(|notes| self.chat.is_selected(¬es.id)); + let active = notes.is_some_and(|notes| self.chat.is_selected(notes.id)); let unread = notes.and_then(|notes| self.chat.unread.get(¬es.id)); let open = entity.clone(); @@ -460,7 +461,7 @@ impl Yumush { .into_any_element() } - fn is_listed(&self, user_id: &str) -> bool { + fn is_listed(&self, user_id: Id) -> bool { self.chat .friends .friends @@ -469,7 +470,7 @@ impl Yumush { || self.has_direct(user_id) } - fn has_direct(&self, user_id: &str) -> bool { + fn has_direct(&self, user_id: Id) -> bool { self.chat.communities.iter().any(|community| { matches!(&community.kind, CommunityKind::Direct { peer } if peer.id == user_id) }) @@ -483,7 +484,7 @@ impl Yumush { .chain(self.chat.opened.as_ref()) .filter(|community| matches!(community.kind, CommunityKind::Group)) .map(|community| { - let active = self.chat.is_selected(&community.id); + let active = self.chat.is_selected(community.id); let muted = self.chat.muted.contains(&community.id); let can_leave = !active || permission::can_leave(self.actor_rank()); @@ -493,7 +494,7 @@ impl Yumush { palette, px(16.), "community", - community_menu(entity, community.id.clone(), can_leave, muted), + community_menu(entity, community.id, can_leave, muted), ) }), ) @@ -508,10 +509,10 @@ impl Yumush { key: &str, menu: impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static, ) -> AnyElement { - let active = self.chat.is_selected(&community.id); + let active = self.chat.is_selected(community.id); let muted = self.chat.muted.contains(&community.id); let unread = self.chat.unread.get(&community.id); - let community_id = community.id.clone(); + let community_id = community.id; let select = entity.clone(); let themed = palette.for_community(Some(community), &self.chat.hues); @@ -528,7 +529,7 @@ impl Yumush { ) .on_click(move |_, window, cx| { select.update(cx, |yumush, cx| { - yumush.select_community(community_id.clone(), window, cx) + yumush.select_community(community_id, window, cx) }) }) .context_menu(menu) @@ -567,7 +568,7 @@ impl Yumush { .map(|community| { let muted = self.chat.muted.contains(&community.id); let menu_entity = entity.clone(); - let menu_id = community.id.clone(); + let menu_id = community.id; self.sidebar_community_row( entity, @@ -575,7 +576,7 @@ impl Yumush { palette, px(20.), "direct", - move |menu, _, _| mute_item(menu, &menu_entity, menu_id.clone(), muted), + move |menu, _, _| mute_item(menu, &menu_entity, menu_id, muted), ) }) .collect() @@ -586,12 +587,12 @@ impl Yumush { .friends .friends .iter() - .filter(|user| matches_query(&user.username, query) && !self.has_direct(&user.id)) + .filter(|user| matches_query(&user.username, query) && !self.has_direct(user.id)) .map(|user| { - let user_id = user.id.clone(); + let user_id = user.id; let open = entity.clone(); let remove = entity.clone(); - let remove_id = user.id.clone(); + let remove_id = user.id; hoverable( format!("friend_{}", user.id), @@ -599,16 +600,14 @@ impl Yumush { palette, ) .on_click(move |_, window, cx| { - open.update(cx, |yumush, cx| { - yumush.open_direct(user_id.clone(), window, cx) - }) + open.update(cx, |yumush, cx| yumush.open_direct(user_id, window, cx)) }) .context_menu(move |menu, _, _| { menu_action( menu, "Remove friend", &remove, - remove_id.clone(), + remove_id, |yumush, id, window, cx| yumush.remove_friend(id, window, cx), ) }) @@ -618,14 +617,14 @@ impl Yumush { } fn found_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { - let relation = self.relation(&user.id); + let relation = self.relation(user.id); let mut trailing = Vec::new(); if relation != Relation::Myself { trailing.push(row_button( entity, "message", - &user.id, + user.id, palette, IconName::MessageSquare, "Message", @@ -640,7 +639,7 @@ impl Yumush { trailing.push(row_button( entity, "friend_action", - &user.id, + user.id, palette, icon, label, @@ -662,7 +661,7 @@ impl Yumush { false, presence_avatar( avatar(palette, user, px(20.), text(10.), &self.chat.avatars), - self.presence_of(&user.id), + self.presence_of(user.id), px(20.), palette, ), @@ -679,7 +678,7 @@ impl Yumush { row_button( entity, "accept_friend", - &user.id, + user.id, palette, IconName::Check, "Accept", @@ -688,7 +687,7 @@ impl Yumush { row_button( entity, "decline_friend", - &user.id, + user.id, palette, IconName::X, "Decline", @@ -706,7 +705,7 @@ impl Yumush { [row_button( entity, "cancel_friend", - &user.id, + user.id, palette, IconName::X, "Cancel", @@ -739,7 +738,7 @@ impl Yumush { row_button( entity, "accept_invitation", - &community.id, + community.id, palette, IconName::Check, "Accept", @@ -748,7 +747,7 @@ impl Yumush { row_button( entity, "decline_invitation", - &community.id, + community.id, palette, IconName::X, "Decline", @@ -806,7 +805,7 @@ impl Yumush { .rounded(px(6.)) .child(presence_avatar( avatar(palette, user, px(24.), text(12.), &self.chat.avatars), - self.presence_of(&user.id), + self.presence_of(user.id), px(24.), palette, )) @@ -837,7 +836,7 @@ impl Yumush { pub(super) fn open_community_settings( &mut self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -851,10 +850,10 @@ fn go_to_call( community: &Community, ) -> impl Fn(&mut Window, &mut App) + 'static { let direct = community.kind.is_direct(); - let go_id = community.id.clone(); + let go_id = community.id; entity_action(entity, move |yumush, window, cx| { - yumush.go_to_community(go_id.clone(), direct, window, cx) + yumush.go_to_community(go_id, direct, window, cx) }) } @@ -905,25 +904,20 @@ pub(super) fn unread_badge( ) } -fn mute_item( - menu: PopupMenu, - entity: &Entity, - community_id: String, - muted: bool, -) -> PopupMenu { +fn mute_item(menu: PopupMenu, entity: &Entity, community_id: Id, muted: bool) -> PopupMenu { let entity = entity.clone(); let label = if muted { "Unmute" } else { "Mute" }; menu.item(PopupMenuItem::new(label).on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| { - yumush.toggle_community_mute(community_id.clone(), cx) + yumush.toggle_community_mute(community_id, cx) }) })) } fn community_menu( entity: &Entity, - community_id: String, + community_id: Id, can_leave: bool, muted: bool, ) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { @@ -934,17 +928,17 @@ fn community_menu( menu, "Invite", &entity, - community_id.clone(), + community_id, |yumush, id, window, cx| yumush.open_invite(id, window, cx), ); let menu = menu_action( menu, "Settings", &entity, - community_id.clone(), + community_id, |yumush, id, window, cx| yumush.open_community_settings(id, window, cx), ); - let menu = mute_item(menu, &entity, community_id.clone(), muted); + let menu = mute_item(menu, &entity, community_id, muted); if !can_leave { return menu; @@ -954,7 +948,7 @@ fn community_menu( menu, "Leave", &entity, - community_id.clone(), + community_id, |yumush, id, window, cx| yumush.leave_community(id, window, cx), ) } @@ -1043,21 +1037,19 @@ fn entry( fn row_button( entity: &Entity, key: &str, - id: &str, + id: Id, palette: Palette, icon: IconName, tip: &'static str, - run: impl Fn(&mut Yumush, String, &mut Window, &mut Context) + 'static, + run: impl Fn(&mut Yumush, Id, &mut Window, &mut Context) + 'static, ) -> AnyElement { - let id = id.to_string(); - icon_button( format!("{key}_{id}"), palette, icon, tip, entity_action(entity, move |yumush, window, cx| { - run(yumush, id.clone(), window, cx) + run(yumush, id, window, cx) }), ) .into_any_element() @@ -1067,12 +1059,14 @@ fn menu_action( menu: PopupMenu, label: &'static str, entity: &Entity, - id: String, - run: impl Fn(&mut Yumush, String, &mut Window, &mut Context) + 'static, + id: Id, + run: impl Fn(&mut Yumush, Id, &mut Window, &mut Context) + 'static, ) -> PopupMenu { let entity = entity.clone(); - menu.item(PopupMenuItem::new(label).on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| run(yumush, id.clone(), window, cx)) - })) + menu.item( + PopupMenuItem::new(label).on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| run(yumush, id, window, cx)) + }), + ) } diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs index 318e28a..71f220f 100644 --- a/crates/client/src/gui/snippet.rs +++ b/crates/client/src/gui/snippet.rs @@ -7,7 +7,7 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link, + Palette, Yumush, avatar, chat::Chat, media_view, millis_time, poll, profile::user_link, widget::panel, }; @@ -50,12 +50,13 @@ fn snippet_row( entity: &Entity, palette: Palette, ) -> impl IntoElement { - let user = chat.author(&item.user_id).cloned().unwrap_or_else(|| User { - id: item.user_id.clone(), + let user = chat.author(item.user_id).cloned().unwrap_or_else(|| User { + id: item.user_id, username: item.username.clone(), role: Role::User, status: String::new(), - avatar_id: item.avatar_id.clone(), + avatar_id: item.avatar_id, + created_at: item.created_at, }); div() @@ -85,14 +86,14 @@ fn snippet_row( entity, div() .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.tinted(&item.user_id)) + .text_color(palette.tinted(item.user_id)) .child(item.username.clone()), )) .child( div() .text_size(text(11.)) .text_color(palette.muted) - .child(id_time(&item.id, CLOCK)), + .child(millis_time(item.created_at, CLOCK)), ), ) .when(!item.body.is_empty(), |this| { @@ -112,7 +113,7 @@ fn snippet_row( .children(item.poll.as_ref().map(|poll| { poll::poll_card( poll, - poll::PollMode::Snapshot(&item.id), + poll::PollMode::Snapshot(item.id), None, chat, entity, diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index 4aea6b2..adf8503 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -1,3 +1,4 @@ +use common::model::Id; use std::{fmt::Display, future::Future}; use common::{ @@ -71,7 +72,7 @@ fn spawn_community( } impl Yumush { - pub(super) fn relation(&self, user_id: &str) -> Relation { + pub(super) fn relation(&self, user_id: Id) -> Relation { let friends = &self.chat.friends; if self.is_me(user_id) { @@ -108,17 +109,17 @@ impl Yumush { CommunityKind::Group | CommunityKind::Notes => None, }), ); - let avatar_ids: Vec = users - .filter_map(|user| user.avatar_id.clone()) + let avatar_ids: Vec = users + .filter_map(|user| user.avatar_id) .chain( chat.communities .iter() - .filter_map(|community| community.avatar_id.clone()), + .filter_map(|community| community.avatar_id), ) .collect(); for avatar_id in avatar_ids { - self.request_avatar(&avatar_id, cx); + self.request_avatar(avatar_id, cx); } } @@ -181,13 +182,13 @@ impl Yumush { pub(super) fn open_found(&self, window: &mut Window, cx: &mut Context) { if let Some(user) = &self.chat.found { - self.open_direct(user.id.clone(), window, cx); + self.open_direct(user.id, window, cx); } } pub(super) fn open_notes(&mut self, window: &mut Window, cx: &mut Context) { if let Some(notes) = self.chat.notes() { - let community_id = notes.id.clone(); + let community_id = notes.id; self.select_community(community_id, window, cx); return; } @@ -196,7 +197,7 @@ impl Yumush { spawn_community(window, cx, async move { network.call(OpenNotes).await }); } - pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context) { + pub(super) fn open_direct(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); spawn_community(window, cx, async move { @@ -207,7 +208,7 @@ impl Yumush { pub(super) fn friend_action( &self, relation: Relation, - user_id: String, + user_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -219,7 +220,7 @@ impl Yumush { } } - pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context) { + pub(super) fn add_friend(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); spawn_done(window, cx, async move { @@ -227,12 +228,7 @@ impl Yumush { }); } - pub(super) fn accept_friend( - &self, - user_id: String, - window: &mut Window, - cx: &mut Context, - ) { + pub(super) fn accept_friend(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); spawn_done(window, cx, async move { @@ -240,12 +236,7 @@ impl Yumush { }); } - pub(super) fn remove_friend( - &self, - user_id: String, - window: &mut Window, - cx: &mut Context, - ) { + pub(super) fn remove_friend(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); spawn_done(window, cx, async move { @@ -255,7 +246,7 @@ impl Yumush { pub(super) fn accept_invitation( &self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -268,7 +259,7 @@ impl Yumush { pub(super) fn decline_invitation( &self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { @@ -281,21 +272,21 @@ impl Yumush { pub(super) fn open_invite( &mut self, - community_id: String, + community_id: Id, window: &mut Window, cx: &mut Context, ) { self.chat.invite = InviteLookup::Idle; let input = new_input("Username...", window, cx); - let enter_id = community_id.clone(); - let lookup_id = community_id.clone(); + let enter_id = community_id; + let lookup_id = community_id; cx.subscribe_in( &input, window, move |this, input, event, window, cx| match event { - InputEvent::Change => this.lookup_invite(lookup_id.clone(), input, window, cx), - InputEvent::PressEnter { .. } => this.send_invite(enter_id.clone(), window, cx), + InputEvent::Change => this.lookup_invite(lookup_id, input, window, cx), + InputEvent::PressEnter { .. } => this.send_invite(enter_id, window, cx), _ => {} }, ) @@ -306,8 +297,7 @@ impl Yumush { window.open_dialog(cx, move |dialog, _, cx| { let yumush = entity.read(cx); let palette = yumush.themed(cx); - let result = - invite_result(&yumush.chat.invite, &community_id, &entity, yumush, palette); + let result = invite_result(&yumush.chat.invite, community_id, &entity, yumush, palette); dialog.title("Invite").child( div() @@ -325,7 +315,7 @@ impl Yumush { fn lookup_invite( &mut self, - community_id: String, + community_id: Id, input: &Entity, window: &mut Window, cx: &mut Context, @@ -348,9 +338,7 @@ impl Yumush { { Ok(user) => { let members = network - .call(ListMembers { - community_id: community_id.clone(), - }) + .call(ListMembers { community_id }) .await .unwrap_or_default(); if members.iter().any(|member| member.user.id == user.id) { @@ -375,12 +363,12 @@ impl Yumush { .detach(); } - fn send_invite(&self, community_id: String, window: &mut Window, cx: &mut Context) { + fn send_invite(&self, community_id: Id, window: &mut Window, cx: &mut Context) { let InviteLookup::Found(user) = &self.chat.invite else { return; }; let network = self.network.clone(); - let user_id = user.id.clone(); + let user_id = user.id; cx.spawn_in(window, async move |this, cx| { match network @@ -402,7 +390,7 @@ impl Yumush { fn invite_result( lookup: &InviteLookup, - community_id: &str, + community_id: Id, entity: &Entity, yumush: &Yumush, palette: Palette, @@ -428,14 +416,13 @@ fn invite_result( ), InviteLookup::Found(user) => { let entity = entity.clone(); - let community_id = community_id.to_string(); Some( user_row(user, yumush, palette) .child( primary_button("invite_send", palette, move |window, cx| { entity.update(cx, |yumush, cx| { - yumush.send_invite(community_id.clone(), window, cx) + yumush.send_invite(community_id, window, cx) }) }) .h(px(30.)) diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index 832d7bd..e55568f 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -257,7 +257,7 @@ impl Yumush { return; }; drain(&mut consumer, &mut samples); - let Some(community_id) = self.chat.selected_community_id.clone() else { + let Some(community_id) = self.chat.selected_community_id else { return; }; let network = self.network.clone(); @@ -276,7 +276,7 @@ impl Yumush { return; }; let uploaded = - upload_file(&this, &network, &community_id, path.clone(), maximum, cx).await; + upload_file(&this, &network, community_id, path.clone(), maximum, cx).await; let _ = std::fs::remove_file(&path); let attachment = match uploaded { Ok(attachment) => attachment, diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index 6bd461d..9387ae3 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -1,6 +1,6 @@ use std::collections::VecDeque; -use common::share::Layer; +use common::{model::Id, share::Layer}; use gpui_kit::{ Context, Div, Entity, FontWeight, Hsla, ParentElement, Styled, div, hsla, prelude::FluentBuilder as _, px, @@ -224,12 +224,11 @@ fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div { })) } -fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palette) -> Div { +fn watching_body(watching: &[(Id, WatchStats)], chat: &Chat, palette: Palette) -> Div { column().children(watching.iter().map(|(user_id, stats)| { - let name = chat.author(user_id).map_or_else( - || user_id.chars().take(8).collect(), - |user| user.username.clone(), - ); + let name = chat + .author(*user_id) + .map_or_else(|| user_id.to_string(), |user| user.username.clone()); let tiles = [ ("Bitrate", format!("{} kbps", stats.kbps)), ("FPS", format!("{:.0}", stats.fps)), diff --git a/crates/client/src/gui/wave.rs b/crates/client/src/gui/wave.rs index 437e931..c6ec039 100644 --- a/crates/client/src/gui/wave.rs +++ b/crates/client/src/gui/wave.rs @@ -1,5 +1,6 @@ use std::collections::{HashMap, HashSet, VecDeque}; +use common::model::Id; use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px}; use crate::net::Levels; @@ -35,17 +36,17 @@ impl Wave { #[derive(Default)] pub struct Waves { - pub speaking: HashSet, - voice: HashMap, - share: HashMap, + pub speaking: HashSet, + voice: HashMap, + share: HashMap, } -fn advance(waves: &mut HashMap, levels: Vec<(String, Vec)>) -> bool { - let mut levels: HashMap> = levels.into_iter().collect(); - let ids: HashSet = waves.keys().chain(levels.keys()).cloned().collect(); +fn advance(waves: &mut HashMap, levels: Vec<(Id, Vec)>) -> bool { + let mut levels: HashMap> = levels.into_iter().collect(); + let ids: HashSet = waves.keys().chain(levels.keys()).copied().collect(); for id in ids { let bands = levels.remove(&id).unwrap_or_default(); - let wave = waves.entry(id.clone()).or_insert_with(Wave::new); + let wave = waves.entry(id).or_insert_with(Wave::new); wave.push(&bands); if wave.silent() { waves.remove(&id); @@ -55,22 +56,19 @@ fn advance(waves: &mut HashMap, levels: Vec<(String, Vec)>) - } impl Waves { - pub fn update(&mut self, levels: Levels, me: Option<&str>, silent: bool) -> bool { + pub fn update(&mut self, levels: Levels, me: Option, silent: bool) -> bool { let mut voice = levels.voice; if silent { - voice.retain(|(id, _)| Some(id.as_str()) != me); + voice.retain(|(id, _)| Some(*id) != me); } - let speaking: HashSet = voice.iter().map(|(id, _)| id.clone()).collect(); + let speaking: HashSet = voice.iter().map(|(id, _)| *id).collect(); let mut changed = speaking != self.speaking; self.speaking = speaking; let had = !self.voice.is_empty() || !self.share.is_empty(); changed |= advance(&mut self.voice, voice); let mut share = levels.watching; - share.extend( - me.zip(levels.sharing) - .map(|(id, levels)| (id.to_string(), levels)), - ); + share.extend(me.zip(levels.sharing)); changed |= advance(&mut self.share, share); changed || had } @@ -79,13 +77,13 @@ impl Waves { *self = Self::default(); } - pub fn voice(&self, id: &str) -> Option<&VecDeque> { - self.voice.get(id).map(|wave| &wave.bars) + pub fn voice(&self, id: Id) -> Option<&VecDeque> { + self.voice.get(&id).map(|wave| &wave.bars) } - pub fn share(&self, id: &str) -> Option<&VecDeque> { + pub fn share(&self, id: Id) -> Option<&VecDeque> { self.share - .get(id) + .get(&id) .filter(|wave| wave.bars.iter().any(|bar| *bar >= AUDIBLE)) .map(|wave| &wave.bars) } diff --git a/crates/client/src/mutes.rs b/crates/client/src/mutes.rs index 83b8454..ff428a9 100644 --- a/crates/client/src/mutes.rs +++ b/crates/client/src/mutes.rs @@ -1,12 +1,14 @@ use std::collections::HashSet; +use common::model::Id; + use crate::{read_config, write_config}; -fn prefix(account_user_id: &str) -> String { +fn prefix(account_user_id: Id) -> String { format!("{account_user_id}\t") } -pub fn load(account_user_id: &str) -> HashSet { +pub fn load(account_user_id: Id) -> HashSet { let Some(content) = read_config("mutes") else { return HashSet::new(); }; @@ -15,11 +17,11 @@ pub fn load(account_user_id: &str) -> HashSet { content .lines() .filter_map(|line| line.strip_prefix(&prefix)) - .map(String::from) + .filter_map(|community_id| community_id.parse().ok()) .collect() } -pub fn save(account_user_id: &str, muted: &HashSet) { +pub fn save(account_user_id: Id, muted: &HashSet) { let prefix = prefix(account_user_id); let mut content: String = read_config("mutes") .unwrap_or_default() diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index e988528..d3d119f 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -5,19 +5,19 @@ use common::{ constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, error::Error, frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX}, - model::{Attachment, User}, + model::{Attachment, Id, User}, open::{Blob, Open, Upload}, session::{Hello, Welcome}, transport::{ALPN, Close, transport}, validate::{validate_attachment_name, validate_attachment_size}, }; -use quinn::{Endpoint, crypto::rustls::QuicClientConfig, rustls}; #[cfg(debug_assertions)] use quinn::rustls::{ DigitallySignedStruct, SignatureScheme, client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, pki_types::{CertificateDer, ServerName, UnixTime}, }; +use quinn::{Endpoint, crypto::rustls::QuicClientConfig, rustls}; #[cfg(debug_assertions)] use rustls_platform_verifier as _; use tokio::{ @@ -266,7 +266,7 @@ async fn hello(connection: &quinn::Connection, token: Option) -> Result< pub(super) async fn upload( connection: &quinn::Connection, - community_id: &str, + community_id: Id, path: &Path, maximum: Option, ) -> Result { @@ -285,7 +285,7 @@ pub(super) async fn upload( let (send_stream, mut receive_stream) = connection.open_bi().await?; let mut send_stream = Sending::new(send_stream); let header = Upload { - community_id: community_id.to_string(), + community_id, name, size, }; @@ -476,7 +476,7 @@ async fn actor( Some(Command::Upload { community_id, path, maximum, reply }) => { let connection = connection.clone(); - answer(reply, async move { upload(&connection, &community_id, &path, maximum).await }); + answer(reply, async move { upload(&connection, community_id, &path, maximum).await }); } Some(Command::Download { blob, reply }) => { let connection = connection.clone(); diff --git a/crates/client/src/net/media.rs b/crates/client/src/net/media.rs index 793851c..0f742b1 100644 --- a/crates/client/src/net/media.rs +++ b/crates/client/src/net/media.rs @@ -12,12 +12,12 @@ use common::{ }, datagram::{Packet, RELAY_PREFIX}, event::{Event, Media as Down}, + model::Id, share::{Fps, Kind, Quality, Resolution, Source}, }; use quinn::Connection; use tokio::{runtime::Handle, sync::mpsc}; use tracing::warn; -use uuid::Uuid; use crate::{ settings::{ShareSettings, VoiceSettings}, @@ -43,7 +43,7 @@ const CAMERA_TOP: Quality = Quality { #[derive(Clone)] struct Want { - community_id: String, + community_id: Id, settings: VoiceSettings, muted: bool, deafened: bool, @@ -58,7 +58,7 @@ struct Inner { joining: u32, mic_test: Option, sharing: HashMap, - watching: HashMap<(String, Kind), Watching>, + watching: HashMap<(Id, Kind), Watching>, } impl Inner { @@ -86,12 +86,12 @@ impl Inner { self.want_voice = Some(want); } - fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> { + fn watch_requests(&self) -> Vec<((Id, Kind), WatchShare)> { self.watching .iter() .map(|((user_id, kind), watching)| { - let request = watch_request(user_id.clone(), *kind, watching.wanted()); - ((user_id.clone(), *kind), request) + let request = watch_request(*user_id, *kind, watching.wanted()); + ((*user_id, *kind), request) }) .collect() } @@ -177,7 +177,7 @@ impl Media { want: Want, events: mpsc::Sender, ) { - let joined = join(&connection, &want.community_id).await; + let joined = join(&connection, want.community_id).await; let next = { let mut inner = self.lock(); if !inner.current(epoch) { @@ -247,7 +247,7 @@ impl Media { pub(super) fn pushed(&self, event: &Event) { if let Event::ShareStopped { user_id, kind, .. } = event { - self.lock().watching.remove(&(user_id.clone(), *kind)); + self.lock().watching.remove(&(*user_id, *kind)); } } @@ -285,7 +285,7 @@ impl Media { Packet::ScreenAudio { .. } => Kind::Screen, Packet::Video { kind, .. } => kind, }; - let key = (Uuid::from_bytes(*from).to_string(), kind); + let key = (Id::from_be_bytes(*from), kind); if let Some(watching) = inner.watching.get(&key) { watching.receive(datagram, &packet); } @@ -293,9 +293,9 @@ impl Media { async fn join_voice( self: Arc, - community_id: String, + community_id: Id, settings: VoiceSettings, - ) -> Result, Fail> { + ) -> Result, Fail> { self.lock().joining += 1; let result = self.join_voice_inner(community_id, settings).await; self.lock().joining -= 1; @@ -305,11 +305,11 @@ impl Media { async fn join_voice_inner( &self, - community_id: String, + community_id: Id, settings: VoiceSettings, - ) -> Result, Fail> { + ) -> Result, Fail> { let (connection, epoch) = self.current_wait().await?; - let participants = join(&connection, &community_id).await?; + let participants = join(&connection, community_id).await?; let voice = voice::start(Some(connection), &settings); let mut inner = self.lock(); if !inner.current(epoch) { @@ -397,7 +397,7 @@ impl Media { } } -fn watch_request(user_id: String, kind: Kind, quality: Quality) -> WatchShare { +fn watch_request(user_id: Id, kind: Kind, quality: Quality) -> WatchShare { WatchShare { user_id, kind, @@ -412,10 +412,8 @@ enum Rejoin { Skip, } -async fn join(connection: &Connection, community_id: &str) -> Result, Fail> { - let request = JoinVoice { - community_id: community_id.to_string(), - }; +async fn join(connection: &Connection, community_id: Id) -> Result, Fail> { + let request = JoinVoice { community_id }; call(connection, request).await } @@ -440,12 +438,12 @@ async fn tick_loop(media: Arc) { match tick { Tick::Quality(quality) => tokio::spawn(send_quietly( connection, - watch_request(user_id.clone(), *kind, quality), + watch_request(*user_id, *kind, quality), )), Tick::Keyframe => tokio::spawn(send_quietly( connection, RequestKeyframe { - user_id: user_id.clone(), + user_id: *user_id, kind: *kind, }, )), @@ -462,14 +460,14 @@ impl NetworkHandle { pub async fn join_voice( &self, - community_id: &str, + community_id: Id, settings: &VoiceSettings, - ) -> Result, Fail> { + ) -> Result, Fail> { self.media() .run( self.media() .clone() - .join_voice(community_id.to_string(), settings.clone()), + .join_voice(community_id, settings.clone()), ) .await } @@ -566,7 +564,7 @@ impl NetworkHandle { .watching .iter() .filter(|((_, kind), _)| *kind == Kind::Screen) - .map(|((user_id, _), watching)| (user_id.clone(), watching.level())) + .map(|((user_id, _), watching)| (*user_id, watching.level())) .collect(), sharing: inner.sharing.get(&Kind::Screen).map(Sharing::level), } @@ -622,23 +620,20 @@ impl NetworkHandle { .map(Sharing::source) } - pub async fn shares(&self, community_id: &str) -> Result, Fail> { - self.call(ListShares { - community_id: community_id.to_string(), - }) - .await + pub async fn shares(&self, community_id: Id) -> Result, Fail> { + self.call(ListShares { community_id }).await } pub async fn watch_share( &self, - user_id: &str, + user_id: Id, kind: Kind, watch: WatchQuality, volume: f32, choice: Choice, ) -> Result<(), Fail> { let media = self.media().clone(); - let key = (user_id.to_string(), kind); + let key = (user_id, kind); let watching = Watching::new(kind, watch, volume, choice); let quality = watching.wanted(); @@ -650,9 +645,9 @@ impl NetworkHandle { if !inner.current(epoch) { return Err(Fail::Offline); } - inner.watching.insert(key.clone(), watching); + inner.watching.insert(key, watching); } - let result = call(&connection, watch_request(key.0.clone(), kind, quality)).await; + let result = call(&connection, watch_request(key.0, kind, quality)).await; if result.is_err() { media.lock().watching.remove(&key); } @@ -662,26 +657,14 @@ impl NetworkHandle { .await } - pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> { - self.media() - .lock() - .watching - .remove(&(user_id.to_string(), kind)); + pub async fn unwatch_share(&self, user_id: Id, kind: Kind) -> Result<(), Fail> { + self.media().lock().watching.remove(&(user_id, kind)); - self.call(UnwatchShare { - user_id: user_id.to_string(), - kind, - }) - .await + self.call(UnwatchShare { user_id, kind }).await } - pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { - if let Some(watching) = self - .media() - .lock() - .watching - .get_mut(&(user_id.to_string(), kind)) - { + pub fn set_watch_quality(&self, user_id: Id, kind: Kind, quality: WatchQuality) { + if let Some(watching) = self.media().lock().watching.get_mut(&(user_id, kind)) { watching.set_quality(quality); } } @@ -707,17 +690,13 @@ impl NetworkHandle { .watching .iter_mut() .filter(|((_, kind), _)| *kind == Kind::Screen) - .map(|((user_id, _), watching)| (user_id.clone(), watching.stats())) + .map(|((user_id, _), watching)| (*user_id, watching.stats())) .collect(), } } - pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option { - self.media() - .lock() - .watching - .get(&(user_id.to_string(), kind))? - .frame() + pub fn share_frame(&self, user_id: Id, kind: Kind) -> Option { + self.media().lock().watching.get(&(user_id, kind))?.frame() } pub fn audio_apps(&self) -> Vec { diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index f2f7c6e..d2e9d9b 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -3,7 +3,7 @@ use std::{path::PathBuf, sync::Arc}; use common::{ call::{Call, GetStorageUsage, Login, Logout, Register, Session}, event::Event, - model::{Attachment, CommunityUsage, Usage, User}, + model::{Attachment, CommunityUsage, Id, Usage, User}, open::Blob, }; use tokio::sync::{mpsc, oneshot}; @@ -41,8 +41,8 @@ struct Shared { #[derive(Default)] pub struct Levels { - pub voice: Vec<(String, Vec)>, - pub watching: Vec<(String, Vec)>, + pub voice: Vec<(Id, Vec)>, + pub watching: Vec<(Id, Vec)>, pub sharing: Option>, } @@ -63,7 +63,7 @@ enum Command { reply: oneshot::Sender, Fail>>, }, Upload { - community_id: String, + community_id: Id, path: PathBuf, maximum: Option, reply: oneshot::Sender>, @@ -176,12 +176,12 @@ impl NetworkHandle { pub async fn upload_attachment( &self, - community_id: &str, + community_id: Id, path: PathBuf, maximum: Option, ) -> Result { self.ask(|reply| Command::Upload { - community_id: community_id.to_string(), + community_id, path, maximum, reply, @@ -191,14 +191,13 @@ impl NetworkHandle { pub async fn download_attachment( &self, - attachment_id: &str, + attachment_id: Id, thumbnail: bool, ) -> Result, Fail> { - let id = attachment_id.to_string(); let blob = if thumbnail { - Blob::Thumbnail(id) + Blob::Thumbnail(attachment_id) } else { - Blob::Attachment(id) + Blob::Attachment(attachment_id) }; self.ask(|reply| Command::Download { blob, reply }).await } diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index bc9f456..969373d 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -2,6 +2,7 @@ use std::{collections::BTreeMap, fmt::Display, ops::RangeInclusive}; use common::{ config::Config, + model::Id, share::{Codec, Fps, Quality, Resolution}, string_enum, }; @@ -107,7 +108,7 @@ pub struct VoiceSettings { pub activation: Activation, pub profile: Profile, pub push_to_talk_key: String, - pub user_volumes: BTreeMap, + pub user_volumes: BTreeMap, } impl Default for VoiceSettings { @@ -267,7 +268,7 @@ pub fn load() -> Settings { .split(',') .filter_map(|pair| pair.split_once('=')) .filter_map(|(user_id, volume)| { - Some((user_id.to_string(), volume.parse().ok()?)) + Some((user_id.parse().ok()?, volume.parse().ok()?)) }) .filter(|(_, volume)| VOLUME.contains(volume)) .collect() diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index 795fa06..dc9454c 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -16,6 +16,7 @@ use common::{ VOICE_SAMPLE_RATE, }, datagram::{self, Packet, RELAY_PREFIX, fragments, split, warn_if_small}, + model::Id, share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options}, }; use ec_opus::{Application, Decoder, Encoder}; @@ -91,7 +92,7 @@ pub struct WatchStats { #[derive(Default)] pub struct ShareSample { pub sending: Vec, - pub watching: Vec<(String, WatchStats)>, + pub watching: Vec<(Id, WatchStats)>, } struct Tally { diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index 91c5c00..e02b5d4 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -8,9 +8,9 @@ use common::{ MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, }, datagram::{Packet, RELAY_PREFIX, VOICE_HEADER}, + model::Id, }; use ec_opus::{Application, Bandwidth, Decoder, Encoder}; -use uuid::Uuid; use crate::{ media::meter::{Spectrum, rms}, @@ -182,8 +182,8 @@ pub struct Engine { sending: bool, level_db: f32, sent: Spectrum, - volumes: HashMap, - speakers: HashMap, + volumes: HashMap, + speakers: HashMap, sent_bytes: usize, received_bytes: usize, expected: u32, @@ -291,7 +291,7 @@ impl Engine { } pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) { - let user_id = Uuid::from_bytes(*from).to_string(); + let user_id = Id::from_be_bytes(*from); let now = Instant::now(); self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len(); @@ -349,13 +349,13 @@ impl Engine { } } - pub fn levels(&mut self) -> Vec<(String, Vec)> { + pub fn levels(&mut self) -> Vec<(Id, Vec)> { let now = Instant::now(); self.speakers .iter_mut() .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW) - .map(|(user_id, speaker)| (user_id.clone(), speaker.spectrum.take())) + .map(|(user_id, speaker)| (*user_id, speaker.spectrum.take())) .collect() } @@ -415,11 +415,11 @@ impl Engine { output_volume: f32, activation: Activation, profile: Profile, - volumes: &BTreeMap, + volumes: &BTreeMap, ) { self.volumes = volumes .iter() - .map(|(user_id, volume)| (user_id.clone(), volume / 100.0)) + .map(|(user_id, volume)| (*user_id, volume / 100.0)) .collect(); self.gate = 10f32.powf(sensitivity_db / 20.0); self.input_gain = input_volume / 100.0; diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index ec83908..fab65f5 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -10,6 +10,7 @@ use bytes::Bytes; use common::{ constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, datagram::{self, Packet, RELAY_PREFIX}, + model::Id, }; use quinn::Connection; use rtrb::{Consumer, Producer, RingBuffer}; @@ -293,7 +294,7 @@ impl Voice { self.with_engine((), |engine| engine.receive(from, seq, opus)); } - pub fn levels(&self) -> Vec<(String, Vec)> { + pub fn levels(&self) -> Vec<(Id, Vec)> { self.with_engine(Vec::new(), Engine::levels) } diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index a8f9071..f1b7219 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -9,7 +9,6 @@ quinn.workspace = true bytes = "1.12.2" tracing = "0.1.44" thiserror = "2.0.21" -uuid = { version = "1.29.3", features = ["v7"] } reed-solomon-simd = "3.1.0" [lints] diff --git a/crates/common/src/call.rs b/crates/common/src/call.rs index 5cecf97..5c68a87 100644 --- a/crates/common/src/call.rs +++ b/crates/common/src/call.rs @@ -4,10 +4,10 @@ use crate::{ constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, error::Error, model::{ - Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community, - CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, - Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, - ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, + Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, + Community, CommunitySummary, CommunityUsage, DayStat, Friends, Id, Invitation, InviteCode, + LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, + Role, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, share::{Codec, Kind, Quality, Share, Source}, validate::{ @@ -67,7 +67,7 @@ pub struct GetSettings; #[derive(Debug, Clone, Encode, Decode)] pub struct GetUser { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -98,18 +98,18 @@ pub struct RemoveAvatar; #[derive(Debug, Clone, Encode, Decode)] pub struct GetAvatar { - pub avatar_id: String, + pub avatar_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListSessions { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct RevokeSession { - pub user_id: String, - pub session_id: String, + pub user_id: Id, + pub session_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -119,29 +119,29 @@ pub struct CreateCommunity { #[derive(Debug, Clone, Encode, Decode)] pub struct GetCommunity { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct UpdateCommunity { - pub community_id: String, + pub community_id: Id, pub name: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct UpdateCommunityAvatar { - pub community_id: String, + pub community_id: Id, pub image: Option>, } #[derive(Debug, Clone, Encode, Decode)] pub struct DeleteCommunity { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct LeaveCommunity { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -149,75 +149,75 @@ pub struct ListCommunities; #[derive(Debug, Clone, Encode, Decode)] pub struct ListMembers { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct Kick { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, pub reason: Option, } #[derive(Debug, Clone, Encode, Decode)] pub struct BanMember { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, pub reason: Option, } #[derive(Debug, Clone, Encode, Decode)] pub struct Unban { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListBans { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct SetRank { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, pub rank: Rank, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListLogs { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct CreateMessage { - pub community_id: String, + pub community_id: Id, pub body: String, - pub attachments: Vec, - pub reply_to: Option, + pub attachments: Vec, + pub reply_to: Option, } #[derive(Debug, Clone, Encode, Decode)] pub struct ForwardMessages { - pub message_ids: Vec, - pub community_id: String, + pub message_ids: Vec, + pub community_id: Id, pub snippet: bool, } #[derive(Debug, Clone, Encode, Decode)] pub struct UpdateMessage { - pub message_id: String, + pub message_id: Id, pub body: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct DeleteMessage { - pub message_id: String, + pub message_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct CreatePoll { - pub community_id: String, + pub community_id: Id, pub question: String, pub options: Vec, pub multiple: bool, @@ -225,36 +225,36 @@ pub struct CreatePoll { #[derive(Debug, Clone, Encode, Decode)] pub struct Vote { - pub message_id: String, + pub message_id: Id, pub positions: Vec, } #[derive(Debug, Clone, Encode, Decode)] pub struct ClosePoll { - pub message_id: String, + pub message_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct React { - pub message_id: String, + pub message_id: Id, pub emoji: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct Pin { - pub message_id: String, + pub message_id: Id, pub pinned: bool, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListPins { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListMessages { - pub community_id: String, - pub before: Option, + pub community_id: Id, + pub before: Option, } #[derive(Debug, Clone, Encode, Decode)] @@ -262,13 +262,13 @@ pub struct ListUnreads; #[derive(Debug, Clone, Encode, Decode)] pub struct MarkRead { - pub community_id: String, - pub message_id: String, + pub community_id: Id, + pub message_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct Typing { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -278,7 +278,7 @@ pub struct FindUser { #[derive(Debug, Clone, Encode, Decode)] pub struct OpenDirect { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -289,23 +289,23 @@ pub struct ListFriends; #[derive(Debug, Clone, Encode, Decode)] pub struct AddFriend { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct AcceptFriend { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct RemoveFriend { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct Invite { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -313,23 +313,23 @@ pub struct ListInvitations; #[derive(Debug, Clone, Encode, Decode)] pub struct AcceptInvitation { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct DeclineInvitation { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ReportMessage { - pub message_id: String, + pub message_id: Id, pub reason: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct ReportUser { - pub user_id: String, + pub user_id: Id, pub reason: String, } @@ -340,13 +340,13 @@ pub struct ListReports { #[derive(Debug, Clone, Encode, Decode)] pub struct HandleReport { - pub report_id: String, + pub report_id: Id, pub status: ReportStatus, } #[derive(Debug, Clone, Encode, Decode)] pub struct JoinVoice { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -365,12 +365,12 @@ pub struct StopShare { #[derive(Debug, Clone, Encode, Decode)] pub struct ListShares { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct WatchShare { - pub user_id: String, + pub user_id: Id, pub kind: Kind, pub quality: Quality, pub decode: Vec, @@ -378,24 +378,24 @@ pub struct WatchShare { #[derive(Debug, Clone, Encode, Decode)] pub struct UnwatchShare { - pub user_id: String, + pub user_id: Id, pub kind: Kind, } #[derive(Debug, Clone, Encode, Decode)] pub struct RequestKeyframe { - pub user_id: String, + pub user_id: Id, pub kind: Kind, } #[derive(Debug, Clone, Encode, Decode)] pub struct DeclineCall { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListVoiceParticipants { - pub community_id: String, + pub community_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -403,12 +403,12 @@ pub struct ListVoiceRooms; #[derive(Debug, Clone, Encode, Decode)] pub struct KickFromVoice { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ServerMute { - pub user_id: String, + pub user_id: Id, pub muted: bool, } @@ -430,12 +430,12 @@ pub struct Logout; #[derive(Debug, Clone, Encode, Decode)] pub struct DeleteUser { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct WatchCommunity { - pub community_id: Option, + pub community_id: Option, } #[derive(Debug, Clone, Encode, Decode)] @@ -443,15 +443,15 @@ pub struct ListUsers; #[derive(Debug, Clone, Encode, Decode)] pub struct SetRole { - pub user_id: String, + pub user_id: Id, pub role: Role, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListAdminLogs { - pub actor_id: Option, - pub target_id: Option, - pub action: Option, + pub actor_id: Option, + pub target_id: Option, + pub action: Option, pub after_ms: Option, pub before_ms: Option, } @@ -461,24 +461,24 @@ pub struct GetOverview; #[derive(Debug, Clone, Encode, Decode)] pub struct SuspendUser { - pub user_id: String, + pub user_id: Id, pub suspended: bool, } #[derive(Debug, Clone, Encode, Decode)] pub struct RevokeSessions { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct ResetPassword { - pub user_id: String, + pub user_id: Id, pub password: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct ClearProfile { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -486,8 +486,8 @@ pub struct ListAllCommunities; #[derive(Debug, Clone, Encode, Decode)] pub struct TransferOwnership { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -503,19 +503,19 @@ pub struct CreateUser { #[derive(Debug, Clone, Encode, Decode)] pub struct RenameUser { - pub user_id: String, + pub user_id: Id, pub username: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct TimeoutUser { - pub user_id: String, + pub user_id: Id, pub minutes: u32, } #[derive(Debug, Clone, Encode, Decode)] pub struct BanUser { - pub user_id: String, + pub user_id: Id, pub reason: Option, pub scope: BanScope, } @@ -525,7 +525,7 @@ pub struct ListServerBans; #[derive(Debug, Clone, Encode, Decode)] pub struct RemoveServerBan { - pub id: String, + pub id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -545,38 +545,38 @@ pub struct DeleteInviteCode { #[derive(Debug, Clone, Encode, Decode)] pub struct SearchMessages { pub text: Option, - pub user_id: Option, - pub community_id: Option, + pub user_id: Option, + pub community_id: Option, pub after_ms: Option, pub before_ms: Option, } #[derive(Debug, Clone, Encode, Decode)] pub struct SearchCommunity { - pub community_id: String, + pub community_id: Id, pub text: String, } #[derive(Debug, Clone, Encode, Decode)] pub struct PurgeUser { - pub user_id: String, + pub user_id: Id, } #[derive(Debug, Clone, Encode, Decode)] pub struct SetCommunityVoice { - pub community_id: String, + pub community_id: Id, pub enabled: bool, } #[derive(Debug, Clone, Encode, Decode)] pub struct ListAttachments { - pub user_id: Option, - pub community_id: Option, + pub user_id: Option, + pub community_id: Option, } #[derive(Debug, Clone, Encode, Decode)] pub struct DeleteAttachment { - pub attachment_id: String, + pub attachment_id: Id, } #[derive(Debug, Clone, Encode, Decode)] @@ -621,7 +621,7 @@ calls! { UpdateUser: User -> User, |c| validate_username(&c.username); UpdateStatus: User -> User, |c| validate_status(&c.status); UpdatePresence: User -> (); - ListPresences: User -> Vec<(String, Presence)>; + ListPresences: User -> Vec<(Id, Presence)>; UpdateAvatar: User -> User, |c| validate_avatar_size(&c.image, MAXIMUM_AVATAR_BYTES as u64); RemoveAvatar: User -> User; GetAvatar: User -> Vec; @@ -670,7 +670,7 @@ calls! { ReportUser: User -> (), |c| validate_reason(Some(&c.reason)); ListReports: Builder -> Vec; HandleReport: User -> (); - JoinVoice: User -> Vec; + JoinVoice: User -> Vec; LeaveVoice: User -> (); StartShare: User -> (); StopShare: User -> (); @@ -679,7 +679,7 @@ calls! { UnwatchShare: User -> (); RequestKeyframe: User -> (); DeclineCall: User -> (); - ListVoiceParticipants: User -> Vec; + ListVoiceParticipants: User -> Vec; ListVoiceRooms: Builder -> Vec; KickFromVoice: User -> (); ServerMute: User -> (); diff --git a/crates/common/src/datagram.rs b/crates/common/src/datagram.rs index 4171cfd..78e8e22 100644 --- a/crates/common/src/datagram.rs +++ b/crates/common/src/datagram.rs @@ -11,7 +11,7 @@ use crate::{ share::{Kind, Layer}, }; -pub const RELAY_PREFIX: usize = 16; +pub const RELAY_PREFIX: usize = 8; const MAX_DATAGRAM: usize = 1200 - 48; pub const VOICE_HEADER: usize = 5; @@ -257,7 +257,11 @@ pub fn send(connection: &Connection, bytes: Bytes) { pub fn warn_if_small(connection: &Connection) { let max = connection.max_datagram_size(); if max.is_none_or(|size| size < MAX_DATAGRAM) { - warn!(?max, needed = MAX_DATAGRAM, "datagram size limit below media packets"); + warn!( + ?max, + needed = MAX_DATAGRAM, + "datagram size limit below media packets" + ); } } diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs index 925db71..5d899f8 100644 --- a/crates/common/src/event.rs +++ b/crates/common/src/event.rs @@ -1,7 +1,8 @@ use bitcode::{Decode, Encode}; use crate::model::{ - Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, ServerSettings, User, + Community, Friends, Id, Invitation, Member, Message, Presence, Rank, Sanction, ServerSettings, + User, }; use crate::share::{Kind, Layer, Share}; @@ -10,26 +11,26 @@ pub enum Event { MessageCreated(Message), MessageUpdated(Message), MessagesDeleted { - community_id: String, - ids: Vec, + community_id: Id, + ids: Vec, }, MemberJoined { - community_id: String, + community_id: Id, member: Member, }, MemberLeft { - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, }, RankChanged { - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, rank: Rank, }, CommunityUpdated(Community), CommunityAdded(Community), Removed { - community_id: String, + community_id: Id, community_name: String, sanction: Sanction, reason: Option, @@ -37,42 +38,42 @@ pub enum Event { FriendsUpdated(Friends), InvitationsUpdated(Vec), CommunityDeleted { - community_id: String, + community_id: Id, }, UserDeleted { - user_id: String, + user_id: Id, }, UserUpdated(User), PresenceChanged { - user_id: String, + user_id: Id, presence: Presence, }, VoiceJoined { - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, }, VoiceLeft { - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, }, ReportCreated, VoiceMuted { - community_id: Option, - user_id: String, + community_id: Option, + user_id: Id, muted: bool, }, SettingsUpdated(ServerSettings), Typing { - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, }, ShareStarted { - community_id: String, + community_id: Id, share: Share, }, ShareStopped { - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, kind: Kind, }, } diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index 742316e..a684b99 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -5,6 +5,13 @@ use crate::constant::{ MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH, }; +pub type Id = i64; + +pub trait Named: Sized + Copy { + fn as_str(self) -> &'static str; + fn parse(text: &str) -> Option; +} + #[macro_export] macro_rules! string_enum { ($(#[$meta:meta])* $name:ident { $($variant:ident => $text:literal),+ $(,)? }) => { @@ -26,6 +33,16 @@ macro_rules! string_enum { Self::ALL.into_iter().find(|item| item.as_str() == text) } } + + impl $crate::model::Named for $name { + fn as_str(self) -> &'static str { + $name::as_str(self) + } + + fn parse(text: &str) -> Option { + $name::parse(text) + } + } }; } @@ -90,11 +107,12 @@ impl Rank { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct User { - pub id: String, + pub id: Id, pub username: String, pub role: Role, pub status: String, - pub avatar_id: Option, + pub avatar_id: Option, + pub created_at: u64, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -108,7 +126,7 @@ pub struct Account { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct SessionInfo { - pub id: String, + pub id: Id, pub device: String, pub last_seen: Option, } @@ -146,19 +164,19 @@ pub enum BanScope { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Community { - pub id: String, + pub id: Id, pub name: String, pub kind: CommunityKind, - pub avatar_id: Option, + pub avatar_id: Option, pub voice_enabled: bool, } #[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)] pub struct Unread { - pub community_id: String, + pub community_id: Id, pub messages: u32, pub mentions: u32, - pub last_read: Option, + pub last_read: Option, } pub fn mentions(body: &str, username: &str) -> bool { @@ -172,11 +190,11 @@ pub fn mentions(body: &str, username: &str) -> bool { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct VoiceRoom { - pub community_id: String, + pub community_id: Id, pub community: String, pub users: Vec, - pub muted: Vec, - pub ghosts: Vec, + pub muted: Vec, + pub ghosts: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -210,7 +228,8 @@ pub enum LogAction { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct LogEntry { - pub id: String, + pub id: Id, + pub created_at: u64, pub actor: Option, pub target: Option, pub action: LogAction, @@ -252,7 +271,7 @@ pub enum AdminAction { } string_enum! { - #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] AdminActionKind { RoleChanged => "role_changed", UserDeleted => "user_deleted", @@ -324,35 +343,14 @@ impl AdminAction { AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, } } - - pub fn name(&self) -> &'static str { - self.kind().as_str() - } -} - -pub fn action_detail(action: &AdminAction) -> Option { - match action { - AdminAction::RoleChanged { role } => Some(role.as_str().to_string()), - AdminAction::UserRenamed { from } => Some(from.clone()), - AdminAction::UserTimedOut { minutes } => Some(minutes.to_string()), - AdminAction::UserBanned { reason } => reason.clone(), - AdminAction::ReportHandled { status } => Some(status.as_str().to_string()), - AdminAction::UserPurged { messages } => Some(messages.to_string()), - AdminAction::VoiceMuted { muted } => Some(muted.to_string()), - AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()), - AdminAction::GhostVoice { seconds } => Some(seconds.to_string()), - AdminAction::BackupCreated { name } - | AdminAction::BackupDeleted { name } - | AdminAction::BackupDownloaded { name } => Some(name.clone()), - _ => None, - } } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct AdminLogEntry { - pub id: String, + pub id: Id, pub actor: Option, pub target: Option, + pub created_at: u64, pub community: Option, pub action: AdminAction, } @@ -378,11 +376,12 @@ impl ReportStatus { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Report { - pub id: String, + pub id: Id, + pub created_at: u64, pub reporter: Option, pub target: Option, - pub message_id: Option, - pub community_id: Option, + pub message_id: Option, + pub community_id: Option, pub community: Option, pub body: Option, pub reason: String, @@ -452,7 +451,7 @@ pub struct Usage { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct CommunityUsage { - pub community_id: String, + pub community_id: Id, pub community: String, pub bytes: u64, pub count: u64, @@ -468,7 +467,7 @@ string_enum! { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct ServerBan { - pub id: String, + pub id: Id, pub kind: ServerBanKind, pub value: String, pub reason: Option, @@ -523,28 +522,30 @@ string_enum! { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Attachment { - pub id: String, + pub id: Id, pub name: String, pub size: u64, pub kind: AttachmentKind, + pub created_at: u64, pub width: Option, pub height: Option, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Quote { - pub message_id: String, - pub user_id: String, + pub message_id: Id, + pub user_id: Id, pub body: String, - pub attachments: usize, + pub attachments: u32, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct SnippetMessage { - pub id: String, - pub user_id: String, + pub id: Id, + pub user_id: Id, pub username: String, - pub avatar_id: Option, + pub avatar_id: Option, + pub created_at: u64, pub body: String, pub attachments: Vec, pub poll: Option, @@ -559,13 +560,13 @@ pub struct Snippet { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Reaction { pub emoji: String, - pub user_ids: Vec, + pub user_ids: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct PollOption { pub text: String, - pub voter_ids: Vec, + pub voter_ids: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -578,9 +579,10 @@ pub struct Poll { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Message { - pub id: String, - pub user_id: String, - pub community_id: String, + pub id: Id, + pub user_id: Id, + pub community_id: Id, + pub created_at: u64, pub body: String, pub attachments: Vec, pub reactions: Vec, diff --git a/crates/common/src/open.rs b/crates/common/src/open.rs index 03cd1cb..bb8a22e 100644 --- a/crates/common/src/open.rs +++ b/crates/common/src/open.rs @@ -1,6 +1,6 @@ use bitcode::{Decode, Encode}; -use crate::call::Request; +use crate::{call::Request, model::Id}; #[derive(Debug, Clone, Encode, Decode)] pub enum Open { @@ -11,14 +11,14 @@ pub enum Open { #[derive(Debug, Clone, Encode, Decode)] pub struct Upload { - pub community_id: String, + pub community_id: Id, pub name: String, pub size: u64, } #[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)] pub enum Blob { - Attachment(String), - Thumbnail(String), + Attachment(Id), + Thumbnail(Id), Backup(String), } diff --git a/crates/common/src/share.rs b/crates/common/src/share.rs index dad977b..05bc487 100644 --- a/crates/common/src/share.rs +++ b/crates/common/src/share.rs @@ -1,6 +1,6 @@ use bitcode::{Decode, Encode}; -use crate::constant::MAXIMUM_SHARE_LAYERS; +use crate::{constant::MAXIMUM_SHARE_LAYERS, model::Id}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] pub enum Codec { @@ -147,7 +147,7 @@ pub enum Kind { #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Share { - pub user_id: String, + pub user_id: Id, pub kind: Kind, pub source: Source, } diff --git a/crates/common/src/time.rs b/crates/common/src/time.rs index 42c2ef7..1f9fcd9 100644 --- a/crates/common/src/time.rs +++ b/crates/common/src/time.rs @@ -10,23 +10,3 @@ pub fn now_ms() -> u64 { .map(|elapsed| elapsed.as_millis() as u64) .unwrap_or_default() } - -pub fn created_at_ms(id: &str) -> Option { - let (seconds, nanos) = uuid::Uuid::parse_str(id).ok()?.get_timestamp()?.to_unix(); - - Some(seconds * 1000 + u64::from(nanos) / 1_000_000) -} - -pub fn id_bound(ms: u64) -> String { - format!("{:08x}-{:04x}", ms >> 16, ms & 0xffff) -} - -pub fn range_bounds( - after_ms: Option, - before_ms: Option, -) -> (Option, Option) { - ( - after_ms.map(id_bound), - before_ms.map(|before| id_bound(before.saturating_add(1))), - ) -} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index af629db..9a1991f 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -10,8 +10,8 @@ quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } rcgen = "0.14.10" bitcode.workspace = true rustls.workspace = true -turso = "0.9.0-pre.6" -uuid = { version = "1.29.3", features = ["v7"] } +turso = { version = "0.9.0-pre.6", default-features = false } +sha2 = "0.11.2" bytes = "1.12.2" argon2 = "0.6.0" getrandom = "0.4.3" diff --git a/crates/server/src/admin_log.rs b/crates/server/src/admin_log.rs deleted file mode 100644 index 924075a..0000000 --- a/crates/server/src/admin_log.rs +++ /dev/null @@ -1,117 +0,0 @@ -use common::{ - constant::LOG_PAGE_LIMIT, - model::{AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail}, - time, -}; -use turso::Connection; - -use crate::{database::new_id, error::ServerError, user}; - -fn action_of(text: &str, detail: Option) -> Option { - Some(match AdminActionKind::parse(text)? { - AdminActionKind::RoleChanged => AdminAction::RoleChanged { - role: Role::parse(&detail?)?, - }, - AdminActionKind::UserDeleted => AdminAction::UserDeleted, - AdminActionKind::UserSuspended => AdminAction::UserSuspended, - AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended, - AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked, - AdminActionKind::PasswordReset => AdminAction::PasswordReset, - AdminActionKind::ProfileCleared => AdminAction::ProfileCleared, - AdminActionKind::UserCreated => AdminAction::UserCreated, - AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted, - AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred, - AdminActionKind::SettingsChanged => AdminAction::SettingsChanged, - AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? }, - AdminActionKind::UserTimedOut => AdminAction::UserTimedOut { - minutes: detail?.parse().ok()?, - }, - AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail }, - AdminActionKind::BanRemoved => AdminAction::BanRemoved, - AdminActionKind::InviteCreated => AdminAction::InviteCreated, - AdminActionKind::InviteDeleted => AdminAction::InviteDeleted, - AdminActionKind::ReportHandled => AdminAction::ReportHandled { - status: ReportStatus::parse(&detail?)?, - }, - AdminActionKind::MessageDeleted => AdminAction::MessageDeleted, - AdminActionKind::UserPurged => AdminAction::UserPurged { - messages: detail?.parse().ok()?, - }, - AdminActionKind::VoiceKicked => AdminAction::VoiceKicked, - AdminActionKind::VoiceMuted => AdminAction::VoiceMuted { - muted: detail?.parse().ok()?, - }, - AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet { - enabled: detail?.parse().ok()?, - }, - AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted, - AdminActionKind::GhostEnabled => AdminAction::GhostEnabled, - AdminActionKind::GhostDisabled => AdminAction::GhostDisabled, - AdminActionKind::GhostVisit => AdminAction::GhostVisit, - AdminActionKind::GhostVoice => AdminAction::GhostVoice { - seconds: detail?.parse().ok()?, - }, - AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? }, - AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? }, - AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? }, - }) -} - -pub async fn record( - actor_id: Option<&str>, - target_id: Option<&str>, - community: Option<&str>, - action: &AdminAction, - conn: &Connection, -) -> Result<(), ServerError> { - let id = new_id(); - let detail = action_detail(action); - conn.execute( - "INSERT INTO admin_log (id, actor_id, target_id, community, action, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - ( - id.as_str(), - actor_id, - target_id, - community, - action.name(), - detail.as_deref(), - ), - ) - .await?; - - Ok(()) -} - -pub async fn list( - actor_id: Option<&str>, - target_id: Option<&str>, - action: Option<&str>, - after_ms: Option, - before_ms: Option, - conn: &Connection, -) -> Result, ServerError> { - let (after, before) = time::range_bounds(after_ms, before_ms); - let mut rows = conn - .query( - &format!("SELECT l.id, l.action, l.detail, {}, {}, l.community FROM admin_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.action = ?3) AND (?4 IS NULL OR l.id >= ?4) AND (?5 IS NULL OR l.id < ?5) ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")), - (actor_id, target_id, action, after, before), - ) - .await?; - - let mut entries = Vec::new(); - while let Some(row) = rows.next().await? { - let text: String = row.get(1)?; - let Some(action) = action_of(&text, row.get(2)?) else { - continue; - }; - entries.push(AdminLogEntry { - id: row.get(0)?, - actor: user::from_row_at(&row, 3)?, - target: user::from_row_at(&row, 8)?, - community: row.get(13)?, - action, - }); - } - - Ok(entries) -} diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs deleted file mode 100644 index e8d1b7e..0000000 --- a/crates/server/src/attachment.rs +++ /dev/null @@ -1,746 +0,0 @@ -use std::{ - collections::HashSet, - io::{BufReader, Cursor}, - path::{Path, PathBuf}, - time::{Duration, SystemTime}, -}; - -use common::{ - constant::{ - ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, MAXIMUM_ATTACHMENTS_PER_MESSAGE, - THUMBNAIL_SIZE, - }, - error::{Error as CommonError, Field, Problem}, - frame::{self, DOWN_MAX, Sending}, - model::{ - Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, - }, - open::{Blob, Upload}, - permission, - time::{self, HOUR_MILLIS}, - validate::{validate_attachment_name, validate_attachment_size}, -}; -use image::{ImageFormat, ImageReader, Limits}; -use quinn::{RecvStream, VarInt}; -use tokio::{ - fs::File, - io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, -}; -use tracing::error; -use turso::{Connection, Row}; - -use crate::{ - backup, community, - database::{self, DB, new_id}, - error::ServerError, - request::{actor_rank, ensure}, - server_settings, user, -}; - -const COLLECT_INTERVAL: Duration = Duration::from_secs(600); -const MAXIMUM_IMAGE_SIDE: u32 = 16384; -const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; -const LIST_LIMIT: i64 = 200; -const USAGE_LIMIT: i64 = 50; -const THUMB_SUFFIX: &str = ".thumb"; -const PART_SUFFIX: &str = ".part"; - -pub struct Stored { - pub attachment: Attachment, - pub uploader_id: String, - pub community_id: String, - pub message_id: Option, -} - -fn from_row(row: &Row) -> Result { - let size: i64 = row.get(2)?; - let kind: String = row.get(3)?; - let width: Option = row.get(4)?; - let height: Option = row.get(5)?; - - Ok(Attachment { - id: row.get(0)?, - name: row.get(1)?, - size: size as u64, - kind: AttachmentKind::parse(&kind).ok_or(CommonError::Server)?, - width: width.map(|value| value as u32), - height: height.map(|value| value as u32), - }) -} - -pub async fn of_message( - message_id: &str, - snippet_position: Option, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT id, name, size, kind, width, height FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id", - (message_id, snippet_position), - ) - .await?; - - let mut attachments = Vec::new(); - while let Some(row) = rows.next().await? { - attachments.push(from_row(&row)?); - } - - Ok(attachments) -} - -pub async fn bind( - message_id: &str, - user_id: &str, - community_id: &str, - attachment_ids: &[String], - conn: &Connection, -) -> Result<(), ServerError> { - if attachment_ids.len() > MAXIMUM_ATTACHMENTS_PER_MESSAGE { - return Err(CommonError::NotFound.into()); - } - - for attachment_id in attachment_ids { - let bound = conn - .execute( - "UPDATE attachment SET message_id = ?1 WHERE id = ?2 AND uploader_id = ?3 AND community_id = ?4 AND message_id IS NULL", - (message_id, attachment_id.as_str(), user_id, community_id), - ) - .await?; - database::expect_one(bound)?; - } - - Ok(()) -} - -fn thumb_path(directory: &Path, id: &str) -> PathBuf { - directory.join(format!("{id}{THUMB_SUFFIX}")) -} - -fn part_path(directory: &Path, id: &str) -> PathBuf { - directory.join(format!("{id}{PART_SUFFIX}")) -} - -fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> { - std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop)) -} - -async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { - tokio::task::spawn_blocking(move || link_or_copy(&source, &target)) - .await - .map_err(|_| CommonError::Server)? - .map_err(|_| CommonError::Server)?; - - Ok(()) -} - -async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { - if tokio::fs::try_exists(&source) - .await - .map_err(|_| CommonError::Server)? - { - duplicate(source, target).await?; - } - - Ok(()) -} - -pub async fn copy( - attachment: &Attachment, - message_id: &str, - user_id: &str, - community_id: &str, - snippet_position: Option, - directory: &Path, - conn: &Connection, -) -> Result<(), ServerError> { - let id = new_id(); - conn.execute( - "INSERT INTO attachment (id, uploader_id, community_id, message_id, name, size, kind, width, height, snippet_position) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", - ( - id.as_str(), - user_id, - community_id, - message_id, - attachment.name.as_str(), - attachment.size as i64, - attachment.kind.as_str(), - attachment.width.map(i64::from), - attachment.height.map(i64::from), - snippet_position, - ), - ) - .await?; - - duplicate(directory.join(&attachment.id), directory.join(&id)).await?; - duplicate_if_exists( - thumb_path(directory, &attachment.id), - thumb_path(directory, &id), - ) - .await -} - -pub async fn ids_of_message( - message_id: &str, - conn: &Connection, -) -> Result, ServerError> { - database::ids( - conn, - "SELECT id FROM attachment WHERE message_id = ?1", - (message_id,), - ) - .await -} - -pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), ServerError> { - conn.execute("DELETE FROM attachment WHERE id = ?1", (attachment_id,)) - .await?; - - Ok(()) -} - -pub async fn all( - user_id: Option<&str>, - community_id: Option<&str>, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT a.id, a.name, a.size, a.kind, a.width, a.height, a.community_id, {} FROM attachment a LEFT JOIN user u ON u.id = a.uploader_id WHERE (?1 IS NULL OR a.uploader_id = ?1) AND (?2 IS NULL OR a.community_id = ?2) ORDER BY a.size DESC LIMIT ?3", user::user_columns("u")), - (user_id, community_id, LIST_LIMIT), - ) - .await?; - - let mut raw = Vec::new(); - while let Some(row) = rows.next().await? { - let community_id: String = row.get(6)?; - raw.push((from_row(&row)?, user::from_row_at(&row, 7)?, community_id)); - } - drop(rows); - - let mut infos = Vec::new(); - for (attachment, uploader, community_id) in raw { - infos.push(AttachmentInfo { - attachment, - uploader, - community: community::label(&community_id, conn).await?, - }); - } - - Ok(infos) -} - -async fn totals(column: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!( - "SELECT {column}, SUM(size), COUNT(*) FROM attachment GROUP BY {column} ORDER BY SUM(size) DESC LIMIT ?1" - ), - (USAGE_LIMIT,), - ) - .await?; - - let mut totals = Vec::new(); - while let Some(row) = rows.next().await? { - let bytes: i64 = row.get(1)?; - let count: i64 = row.get(2)?; - totals.push((row.get(0)?, bytes as u64, count as u64)); - } - - Ok(totals) -} - -pub async fn usage(conn: &Connection) -> Result<(Vec, Vec), ServerError> { - let mut users = Vec::new(); - for (user_id, bytes, count) in totals("uploader_id", conn).await? { - users.push(Usage { - user: user::read(&user_id, conn).await?, - bytes, - count, - }); - } - - let mut communities = Vec::new(); - for (community_id, bytes, count) in totals("community_id", conn).await? { - communities.push(CommunityUsage { - community: community::label(&community_id, conn).await?, - community_id, - bytes, - count, - }); - } - - Ok((users, communities)) -} - -async fn over_quota( - sql: &str, - key: &str, - limit: u64, - size: u64, - conn: &Connection, -) -> Result { - if limit == 0 { - return Ok(false); - } - let used = database::scalar_i64(conn, sql, (key,)).await?; - - Ok(used as u64 + size > limit) -} - -async fn ensure_quota( - user_id: &str, - community_id: &str, - size: u64, - settings: &ServerSettings, - conn: &Connection, -) -> Result<(), ServerError> { - if over_quota( - "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1", - user_id, - settings.user_quota_bytes, - size, - conn, - ) - .await? - { - return Err(CommonError::QuotaExceeded.into()); - } - if over_quota( - "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?1", - community_id, - settings.community_quota_bytes, - size, - conn, - ) - .await? - { - return Err(CommonError::QuotaExceeded.into()); - } - - Ok(()) -} - -pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result, ServerError> { - database::ids( - conn, - "SELECT id FROM attachment WHERE uploader_id = ?1", - (user_id,), - ) - .await -} - -pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), ServerError> { - conn.execute("DELETE FROM attachment WHERE uploader_id = ?1", (user_id,)) - .await?; - - Ok(()) -} - -pub fn remove_files(attachment_ids: &[String], directory: &Path) { - for id in attachment_ids { - let _ = std::fs::remove_file(directory.join(id)); - let _ = std::fs::remove_file(thumb_path(directory, id)); - } -} - -pub async fn read(attachment_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id FROM attachment WHERE id = ?1", - (attachment_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(Stored { - attachment: from_row(&row)?, - uploader_id: row.get(6)?, - community_id: row.get(7)?, - message_id: row.get(8)?, - }) -} - -fn media_kind(head: &[u8]) -> AttachmentKind { - if is_video(head) { - AttachmentKind::Video - } else if is_audio(head) { - AttachmentKind::Audio - } else { - AttachmentKind::File - } -} - -fn is_image(head: &[u8]) -> bool { - matches!( - image::guess_format(head), - Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) - ) -} - -fn is_video(head: &[u8]) -> bool { - head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) -} - -fn is_audio(head: &[u8]) -> bool { - head.starts_with(b"OggS") - || head.starts_with(b"fLaC") - || head.starts_with(b"ID3") - || head.starts_with(&[0xFF, 0xFB]) - || head.starts_with(&[0xFF, 0xF3]) - || head.starts_with(&[0xFF, 0xF2]) - || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE")) -} - -fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> { - let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?)) - .with_guessed_format() - .ok()?; - let mut limits = Limits::default(); - limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE); - limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE); - limits.max_alloc = Some(MAXIMUM_DECODE_BYTES); - reader.limits(limits); - let image = reader.decode().ok()?; - let (width, height) = (image.width(), image.height()); - - let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE { - image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE) - } else { - image - }; - let mut bytes = Cursor::new(Vec::new()); - fitted - .to_rgb8() - .write_to(&mut bytes, ImageFormat::Jpeg) - .ok()?; - std::fs::write(thumbnail, bytes.into_inner()).ok()?; - - Some((width, height)) -} - -async fn receive_body( - reader: &mut R, - part: &Path, - size: u64, -) -> Result, ServerError> { - let mismatch = |actual: u64| CommonError::Invalid { - field: Field::Attachment, - problem: Problem::Length { - min: size, - max: size, - actual, - }, - }; - let mut file = File::create(part).await?; - - let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize]; - reader.read_exact(&mut head).await?; - file.write_all(&head).await?; - - let mut received = head.len() as u64; - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; - loop { - let read = reader.read(&mut buffer).await?; - if read == 0 { - break; - } - - received += read as u64; - if received > size { - return Err(mismatch(received).into()); - } - file.write_all(&buffer[..read]).await?; - } - - if received != size { - return Err(mismatch(received).into()); - } - file.flush().await?; - - Ok(head) -} - -pub async fn store( - user: &User, - header: &Upload, - reader: &mut R, - db: &DB, - directory: &Path, -) -> Result { - let conn = database::connect(db).await?; - let rank = actor_rank(user, &header.community_id, &conn).await?; - ensure(permission::can_post(rank))?; - validate_attachment_name(&header.name)?; - let settings = server_settings::read(&conn).await?; - validate_attachment_size(header.size, settings.max_attachment_bytes)?; - ensure_quota( - &user.id, - &header.community_id, - header.size, - &settings, - &conn, - ) - .await?; - - let id = new_id(); - let part = part_path(directory, &id); - let path = directory.join(&id); - let head = match receive_body(reader, &part, header.size).await { - Ok(head) => head, - Err(error) => { - let _ = tokio::fs::remove_file(&part).await; - return Err(error); - } - }; - tokio::fs::rename(&part, &path).await?; - - let described = if is_image(&head) { - let source = path.clone(); - let thumbnail = thumb_path(directory, &id); - tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)) - .await - .ok() - .flatten() - } else { - None - }; - let (kind, width, height) = match described { - Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)), - None => (media_kind(&head), None, None), - }; - - let mut rows = conn - .query( - "INSERT INTO attachment (id, uploader_id, community_id, name, size, kind, width, height) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) RETURNING id, name, size, kind, width, height", - ( - id.as_str(), - user.id.as_str(), - header.community_id.as_str(), - header.name.as_str(), - header.size as i64, - kind.as_str(), - width.map(i64::from), - height.map(i64::from), - ), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) -} - -pub async fn upload( - user: Option<&User>, - header: Upload, - mut receive_stream: RecvStream, - mut send_stream: Sending, - db: &DB, - directory: &Path, -) -> Result<(), ServerError> { - let stored = match user { - Some(user) => store(user, &header, &mut receive_stream, db, directory).await, - None => Err(CommonError::Unauthenticated.into()), - }; - let rejected = stored.is_err(); - let reply = stored.map_err(CommonError::from); - - frame::write(&mut send_stream, &reply, DOWN_MAX).await?; - send_stream.finish()?; - if rejected { - let _ = receive_stream.stop(VarInt::from_u32(0)); - } - - Ok(()) -} - -pub async fn locate( - user: Option<&User>, - attachment_id: &str, - thumbnail: bool, - db: &DB, - directory: &Path, -) -> Result<(PathBuf, u64), ServerError> { - let user = user.ok_or(CommonError::Unauthenticated)?; - let conn = database::connect(db).await?; - let stored = read(attachment_id, &conn).await?; - - let rank = actor_rank(user, &stored.community_id, &conn).await?; - ensure(permission::can_read(rank))?; - ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; - - let path = if thumbnail { - thumb_path(directory, &stored.attachment.id) - } else { - directory.join(&stored.attachment.id) - }; - let length = tokio::fs::metadata(&path) - .await - .map_err(|_| CommonError::NotFound)? - .len(); - - Ok((path, length)) -} - -pub async fn fetch( - user: Option<&User>, - blob: Blob, - mut send_stream: Sending, - db: &DB, - directory: &Path, - backups: &Path, -) -> Result<(), ServerError> { - let located = match &blob { - Blob::Attachment(id) => locate(user, id, false, db, directory).await, - Blob::Thumbnail(id) => locate(user, id, true, db, directory).await, - Blob::Backup(name) => backup::locate(user, name, db, backups).await, - }; - let located = located.map_err(CommonError::from); - let reply = located - .as_ref() - .map(|(_, length)| *length) - .map_err(Clone::clone); - frame::write(&mut send_stream, &reply, DOWN_MAX).await?; - - if let Ok((path, _)) = located { - let mut file = File::open(path).await?; - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; - loop { - let read = file.read(&mut buffer).await?; - if read == 0 { - break; - } - send_stream.get().write_all(&buffer[..read]).await?; - } - } - send_stream.finish()?; - - Ok(()) -} - -pub async fn collect(db: DB, directory: PathBuf) { - let mut interval = tokio::time::interval(COLLECT_INTERVAL); - loop { - interval.tick().await; - if let Err(error) = sweep(&db, &directory).await { - error!("attachment sweep: {error}"); - } - } -} - -async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { - let conn = database::connect(db).await?; - let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS); - let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); - let stale_id = time::id_bound(stale_ms); - - conn.execute( - "DELETE FROM attachment WHERE message_id IS NULL AND id < ?1", - (stale_id.as_str(),), - ) - .await?; - - let mut rows = conn.query("SELECT id FROM attachment", ()).await?; - let mut ids = HashSet::new(); - while let Some(row) = rows.next().await? { - ids.insert(row.get::(0)?); - } - drop(rows); - - for entry in std::fs::read_dir(directory)? { - let Ok(entry) = entry else { continue }; - let name = entry.file_name().to_string_lossy().into_owned(); - let id = name - .strip_suffix(THUMB_SUFFIX) - .or_else(|| name.strip_suffix(PART_SUFFIX)) - .unwrap_or(&name); - let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { - continue; - }; - let stale = modified < stale_at && id < stale_id.as_str(); - - if stale && !ids.contains(id) { - let _ = std::fs::remove_file(entry.path()); - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - use std::io::Cursor; - - use common::{ - call::CreateMessage, - model::{AttachmentKind, Rank}, - open::Upload, - }; - use image::{ImageFormat, RgbImage}; - - use crate::{ - attachment::{store, thumb_path}, - call::{Cx, Handle, Me}, - community, database, - hub::{Client, Signed}, - message, - network::{Services, Shared}, - test, user, user_community, - }; - - #[tokio::test] - async fn upload_then_read_in_message() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - user_community::join(&user.id, &community.id, Rank::Member, &conn) - .await - .unwrap(); - - let mut png = Cursor::new(Vec::new()); - RgbImage::new(2, 3) - .write_to(&mut png, ImageFormat::Png) - .unwrap(); - let png = png.into_inner(); - let directory = test::directory(); - let header = Upload { - community_id: community.id.clone(), - name: "pixel.png".to_string(), - size: png.len() as u64, - }; - let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) - .await - .unwrap(); - - let client = Client::detached(Some(Signed { - user_id: user.id.clone(), - token: "token".to_string(), - })); - let shared = Shared { - db: db.clone(), - services: Services::default(), - directory: test::directory(), - backups: test::directory(), - }; - let mut cx = Cx::new(&client, &shared, database::connect(&db).await.unwrap()); - CreateMessage { - community_id: community.id.clone(), - body: String::new(), - attachments: vec![attachment.id.clone()], - reply_to: None, - } - .handle(Me::User(user), &mut cx) - .await - .unwrap(); - - let messages = message::read_page(&community.id, None, &conn) - .await - .unwrap(); - assert_eq!(vec![attachment.clone()], messages[0].attachments); - assert_eq!(AttachmentKind::Image, attachment.kind); - assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); - - std::fs::remove_file(directory.join(&attachment.id)).unwrap(); - std::fs::remove_file(thumb_path(&directory, &attachment.id)).unwrap(); - } -} diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 245cdef..d7e5580 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -1,15 +1,19 @@ use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use common::{ + call::{Call, Login, Register, Session}, error::Error as CommonError, - model::{SessionInfo, User}, - permission, time, + model::{Id, Role, ServerSettings, User}, + permission, transport::Close, - validate::{validate_device, validate_password, validate_username}, }; -use turso::Connection; +use sha2::{Digest, Sha256}; use crate::{ - database::new_id, error::ServerError, hub::Hub, invite, server_ban, server_settings, user, + db::{self, Connection}, + error::{ServerError, ensure_with}, + hub::{Client, Hub}, + network::Shared, + request::limit_logins, }; const SALT_LENGTH: usize = 16; @@ -23,6 +27,10 @@ pub(crate) fn random_bytes() -> Result<[u8; N], ServerError> { Ok(bytes) } +pub fn token_hash(token: &str) -> Vec { + Sha256::digest(token.as_bytes()).to_vec() +} + fn hash(password: &str) -> Result { let salt = random_bytes::()?; let hash = Argon2::default() @@ -38,209 +46,166 @@ fn verify(password: &str, password_hash: &str) -> Result<(), ServerError> { .map_err(|_| ServerError::from(CommonError::WrongCredentials)) } -async fn open_session(user_id: &str, conn: &Connection) -> Result { +async fn hash_blocking(password: String) -> Result { + tokio::task::spawn_blocking(move || hash(&password)).await? +} + +async fn verify_blocking(password: String, password_hash: String) -> Result<(), ServerError> { + tokio::task::spawn_blocking(move || verify(&password, &password_hash)).await? +} + +async fn open_session(user_id: Id, db: &Connection) -> Result { let token: String = random_bytes::()? .iter() .map(|byte| format!("{byte:02x}")) .collect(); - - conn.execute( - "INSERT INTO session (token, user_id, id) VALUES (?1, ?2, ?3)", - (token.as_str(), user_id, new_id()), - ) - .await?; - seen(user_id, &token, conn).await?; + let session_id = db::session::insert(&token_hash(&token), user_id, db).await?; + db::session::seen(session_id, db).await?; Ok(token) } -pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), ServerError> { - if user::is_ghost(user_id, conn).await? { - return Ok(()); - } - let now = time::now_ms() as i64; - conn.execute( - "UPDATE user SET last_seen = ?2 WHERE id = ?1", - (user_id, now), - ) - .await?; - conn.execute( - "UPDATE session SET last_seen = ?2 WHERE token = ?1", - (token, now), - ) - .await?; - - Ok(()) -} - -pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<(), ServerError> { - validate_device(name)?; - conn.execute( - "UPDATE session SET device = ?2 WHERE token = ?1", - (token, name), - ) - .await?; - - Ok(()) -} - -pub async fn sessions(user_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT id, device, last_seen FROM session WHERE user_id = ?1 ORDER BY last_seen DESC", - (user_id,), - ) - .await?; - let mut sessions = Vec::new(); - while let Some(row) = rows.next().await? { - let last_seen: Option = row.get(2)?; - sessions.push(SessionInfo { - id: row.get(0)?, - device: row.get(1)?, - last_seen: last_seen.map(|millis| millis as u64), - }); - } - - Ok(sessions) -} - -async fn revoke_session( - user_id: &str, - session_id: &str, - conn: &Connection, -) -> Result { - let mut rows = conn - .query( - "DELETE FROM session WHERE id = ?1 AND user_id = ?2 RETURNING token", - (session_id, user_id), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(row.get(0)?) -} - pub async fn create_account( username: &str, password: &str, - conn: &Connection, + db: &Connection, ) -> Result { - validate_username(username)?; - validate_password(password)?; - - if user::is_taken(username, None, conn).await? { - return Err(CommonError::Taken.into()); - } - - user::create(username, &hash(password)?, conn).await + db::user::create(username, &hash(password)?, Role::User, db).await } -pub async fn register( - username: &str, - password: &str, - invite_code: Option<&str>, - conn: &mut Connection, -) -> Result<(User, String), ServerError> { - let tx = conn.transaction().await?; - if server_ban::username_banned(username, &tx).await? { - return Err(CommonError::Banned.into()); - } - if !server_settings::read(&tx).await?.registration_open && user::any(&tx).await? { - invite::consume(invite_code.ok_or(CommonError::RegistrationClosed)?, &tx).await?; - } - let user = create_account(username, password, &tx).await?; - admit(&user, &tx).await?; - let token = open_session(&user.id, &tx).await?; - tx.commit().await?; - - Ok((user, token)) +pub(crate) async fn register( + call: Register, + client: &Client, + shared: &Shared, +) -> Result { + call.validate()?; + shared + .db + .run(async |db| limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await) + .await?; + let password_hash = hash_blocking(call.password.clone()).await?; + + shared + .db + .run(async |db| { + if db::server_ban::username_banned(&call.username, db).await? { + return Err(CommonError::Banned.into()); + } + let settings = db::settings::read(db).await?; + let first = !db::user::any(db).await?; + if !settings.registration_open && !first { + let code = call + .invite + .as_deref() + .ok_or(CommonError::RegistrationClosed)?; + db::registration_code::consume(code, db).await?; + } + let role = if first { Role::Builder } else { Role::User }; + let user = db::user::create(&call.username, &password_hash, role, db).await?; + admit(&user, &settings, db).await?; + let token = open_session(user.id, db).await?; + + Ok(Session { user, token }) + }) + .await } -pub async fn login( - username: &str, - password: &str, - conn: &Connection, -) -> Result<(User, String), ServerError> { - let (user, password_hash) = user::credentials(username, conn) - .await? - .ok_or(CommonError::WrongCredentials)?; - verify(password, &password_hash)?; - admit(&user, conn).await?; - let token = open_session(&user.id, conn).await?; - - Ok((user, token)) +pub(crate) async fn login( + call: Login, + client: &Client, + shared: &Shared, +) -> Result { + call.validate()?; + let (user, password_hash) = shared + .db + .run(async |db| { + limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await?; + db::user::password_hash_of(&call.username, db) + .await? + .ok_or(CommonError::WrongCredentials.into()) + }) + .await?; + verify_blocking(call.password, password_hash).await?; + + shared + .db + .run(async |db| { + let settings = db::settings::read(db).await?; + admit(&user, &settings, db).await?; + let token = open_session(user.id, db).await?; + + Ok(Session { user, token }) + }) + .await } -async fn admit(user: &User, conn: &Connection) -> Result<(), ServerError> { - if server_ban::username_banned(&user.username, conn).await? { +async fn admit(user: &User, settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> { + if db::server_ban::username_banned(&user.username, db).await? { return Err(CommonError::Banned.into()); } - if let Some(until_ms) = user::suspended(&user.id, conn).await? { + if let Some(until_ms) = db::user::suspended(user.id, db).await? { return Err(CommonError::Suspended { until_ms }.into()); } - if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance { + if !permission::is_builder(user.role) && settings.maintenance { return Err(CommonError::Maintenance.into()); } Ok(()) } -pub async fn resume(token: &str, conn: &Connection) -> Result { - let user = match user::by_session_token(token, conn).await { - Err(ServerError::Wire(CommonError::WrongCredentials)) => { - return Err(CommonError::Unauthenticated.into()); - } - user => user?, - }; - admit(&user, conn).await?; - seen(&user.id, token, conn).await?; +pub async fn resume(token: &str, db: &Connection) -> Result<(Id, User), ServerError> { + let (session_id, user) = db::session::find(&token_hash(token), db) + .await? + .ok_or(CommonError::Unauthenticated)?; + admit(&user, &db::settings::read(db).await?, db).await?; + db::session::seen(session_id, db).await?; - Ok(user) + Ok((session_id, user)) } -pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> { - conn.execute("DELETE FROM session WHERE token = ?1", (token,)) - .await?; +pub async fn recheck(session_id: Id, db: &Connection) -> Result { + let user = db::session::user_of(session_id, db) + .await? + .ok_or(CommonError::Unauthenticated)?; + admit(&user, &db::settings::read(db).await?, db).await?; - Ok(()) + Ok(user) } -pub(crate) async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { - conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) - .await?; +pub async fn logout(session_id: Id, db: &Connection) -> Result<(), ServerError> { + db::session::delete(session_id, db).await +} - Ok(()) +pub(crate) async fn revoke_sessions(user_id: Id, db: &Connection) -> Result<(), ServerError> { + db::session::delete_all(user_id, db).await } pub async fn reset_password( - user_id: &str, + user_id: Id, password: &str, - conn: &Connection, + db: &Connection, ) -> Result<(), ServerError> { - validate_password(password)?; - user::set_password_hash(user_id, &hash(password)?, conn).await + db::user::set_password_hash(user_id, &hash(password)?, db).await } -pub enum Revoke<'a> { - User(&'a str), - Session { - user_id: &'a str, - session_id: &'a str, - }, +pub enum Revoke { + User(Id), + Session { user_id: Id, session_id: Id }, } -pub async fn revoke(hub: &Hub, target: Revoke<'_>, conn: &Connection) -> Result<(), ServerError> { +pub async fn revoke(hub: &Hub, target: Revoke, db: &Connection) -> Result<(), ServerError> { match target { Revoke::User(user_id) => { - revoke_sessions(user_id, conn).await?; + revoke_sessions(user_id, db).await?; hub.kick_user(user_id, Close::Revoked); } Revoke::Session { user_id, session_id, } => { - let token = revoke_session(user_id, session_id, conn).await?; - hub.kick_token(&token, Close::Revoked); + let deleted = db::session::delete_of(user_id, session_id, db).await?; + ensure_with(deleted == 1, CommonError::NotFound)?; + hub.kick_session(session_id, Close::Revoked); } } @@ -249,25 +214,61 @@ pub async fn revoke(hub: &Hub, target: Revoke<'_>, conn: &Connection) -> Result< #[cfg(test)] mod tests { - use common::error::Error as CommonError; + use common::{ + call::{Login, Register}, + error::Error as CommonError, + }; - use crate::{authentication, database, error::ServerError, test}; + use crate::{ + authentication, + error::ServerError, + hub::Client, + network::{Services, Shared}, + test, + }; #[tokio::test] async fn register_and_login() { - let db = test::get_database().await; - let mut conn = database::connect(&db).await.unwrap(); - - let (registered_user, _) = - authentication::register("Tahinli", "correct horse", None, &mut conn) - .await - .unwrap(); - let (logged_in_user, _) = authentication::login("Tahinli", "correct horse", &conn) - .await - .unwrap(); - let wrong_password = authentication::login("Tahinli", "wrong password", &conn).await; - - assert_eq!(registered_user, logged_in_user); + let shared = Shared { + db: test::db().await, + services: Services::default(), + directory: test::directory(), + backups: test::directory(), + }; + let client = Client::detached(None); + + let registered = authentication::register( + Register { + username: "Tahinli".to_string(), + password: "correct horse".to_string(), + invite: None, + }, + &client, + &shared, + ) + .await + .unwrap(); + let logged_in = authentication::login( + Login { + username: "tahinli".to_string(), + password: "correct horse".to_string(), + }, + &client, + &shared, + ) + .await + .unwrap(); + let wrong_password = authentication::login( + Login { + username: "Tahinli".to_string(), + password: "wrong password".to_string(), + }, + &client, + &shared, + ) + .await; + + assert_eq!(registered.user, logged_in.user); assert!(matches!( wrong_password, Err(ServerError::Wire(CommonError::WrongCredentials)) diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs index e70f546..21a7f4e 100644 --- a/crates/server/src/backup.rs +++ b/crates/server/src/backup.rs @@ -6,14 +6,10 @@ use common::{ permission, time, validate::validate_backup_name, }; -use turso::Connection; use crate::{ - admin_log, - database::{self, DB}, - error::ServerError, - request::ensure, - user, + db::{self, Db}, + error::{ServerError, ensure}, }; const PREFIX: &str = "yumush-"; @@ -44,14 +40,9 @@ fn path_of(directory: &Path, name: &str) -> Result { Ok(directory.join(name)) } -pub async fn create(conn: &Connection, directory: &Path) -> Result { +pub async fn create(db: &Db, directory: &Path) -> Result { let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); - let path = directory.join(&name); - let statement = format!( - "VACUUM INTO '{}'", - path.to_string_lossy().replace('\'', "''") - ); - conn.execute(&statement, ()).await?; + db.backup(&directory.join(&name).to_string_lossy()).await?; info(directory, &name) } @@ -78,29 +69,30 @@ pub fn delete(name: &str, directory: &Path) -> Result<(), ServerError> { pub async fn locate( user: Option<&User>, name: &str, - db: &DB, + db: &Db, directory: &Path, ) -> Result<(PathBuf, u64), ServerError> { let user = user.ok_or(CommonError::Unauthenticated)?; - let conn = database::connect(db).await?; - let me = user::read(&user.id, &conn).await?; - ensure(permission::is_builder(me.role))?; - - let path = path_of(directory, name)?; - let length = tokio::fs::metadata(&path) - .await - .map_err(|_| CommonError::NotFound)? - .len(); - admin_log::record( - Some(&me.id), - None, - None, - &AdminAction::BackupDownloaded { - name: name.to_string(), - }, - &conn, - ) - .await?; - - Ok((path, length)) + db.run(async |db| { + let me = db::user::read(user.id, db).await?; + ensure(permission::is_builder(me.role))?; + let path = path_of(directory, name)?; + let length = tokio::fs::metadata(&path) + .await + .map_err(|_| CommonError::NotFound)? + .len(); + db::log::record_admin( + Some(me.id), + None, + None, + &AdminAction::BackupDownloaded { + name: name.to_string(), + }, + db, + ) + .await?; + + Ok((path, length)) + }) + .await } diff --git a/crates/server/src/call/admin.rs b/crates/server/src/call/admin.rs index 7a12e61..c36047f 100644 --- a/crates/server/src/call/admin.rs +++ b/crates/server/src/call/admin.rs @@ -1,14 +1,12 @@ -use std::collections::BTreeMap; - use common::{ call::{ BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment, DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage, ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes, - ListServerBans, ListUsers, Login, Logout, PurgeUser, Register, RemoveServerBan, RenameUser, - ResetPassword, RevokeSessions, SearchCommunity, SearchMessages, Session, SetCommunityVoice, - SetGhost, SetRole, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, - UpdateServerSettings, WatchCommunity, + ListServerBans, ListUsers, Logout, PurgeUser, RemoveServerBan, RenameUser, ResetPassword, + RevokeSessions, SearchCommunity, SearchMessages, SetCommunityVoice, SetGhost, SetRole, + StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, UpdateServerSettings, + WatchCommunity, }, error::Error, event::Event, @@ -23,52 +21,40 @@ use common::{ }; use crate::{ - admin_log, attachment, authentication::{self, Revoke}, backup, call::user::user_updated, call::{Cx, Handle, Me}, - community, - error::ServerError, - invite, log, message, overview, + db::{ + attachment, avatar, community, log, member, message, registration_code, server_ban, + session, settings, stats, user, + }, + error::{ServerError, ensure}, publish::{Broadcast, To}, request::{ - allowed, call_ended, ensure, ensure_editable, is_outsider, leave_room_voice, - leave_user_voice, limit_logins, managed, message_event, record_ghost_voice, shares_ended, - voice_closed, voice_joined, voice_muted, + allowed, call_ended, delete_community, ensure_editable, is_outsider, leave_room_voice, + leave_user_voice, managed, message_event, messages_deleted, record_ghost_voice, + shares_ended, voice_joined, voice_muted, }, - server_ban, server_settings, stats, user, user_community, }; -impl Handle for Register { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?; - let (user, token) = authentication::register( - &self.username, - &self.password, - self.invite.as_deref(), - &mut cx.db, - ) - .await?; - - Ok(Session { user, token }) - } -} +const CODE_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +const CODE_LENGTH: usize = 8; -impl Handle for Login { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?; - let (user, token) = authentication::login(&self.username, &self.password, &cx.db).await?; +fn generate_code() -> Result { + let bytes = authentication::random_bytes::()?; - Ok(Session { user, token }) - } + Ok(bytes + .iter() + .map(|byte| char::from(CODE_ALPHABET[usize::from(*byte) % CODE_ALPHABET.len()])) + .collect()) } impl Handle for Logout { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { me.user()?; let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?; - authentication::logout(&signed.token, &cx.db).await?; + authentication::logout(signed.session_id, cx.db).await?; Ok(()) } @@ -78,17 +64,17 @@ impl Handle for UpdateServerSettings { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; let settings = self.settings; - server_settings::update(&settings, &cx.db).await?; - admin_log::record( - Some(&me.id), + settings::update(&settings, cx.db).await?; + log::record_admin( + Some(me.id), None, None, &AdminAction::SettingsChanged, - &cx.db, + cx.db, ) .await?; if settings.maintenance { - let builders = user::builder_ids(&cx.db).await?; + let builders = user::builder_ids(cx.db).await?; cx.sh .services .hub @@ -103,16 +89,16 @@ impl Handle for UpdateServerSettings { impl Handle for RenameUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let target = managed(&me, &self.user_id, &cx.db).await?; - let user = user::update(&self.user_id, &self.username, &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&self.user_id), + let target = managed(&me, self.user_id, cx.db).await?; + let user = user::update(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, + cx.db, ) .await?; user_updated(&user, cx); @@ -124,13 +110,13 @@ impl Handle for RenameUser { impl Handle for CreateUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let user = authentication::create_account(&self.username, &self.password, &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&user.id), + 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, + cx.db, ) .await?; @@ -140,19 +126,19 @@ impl Handle for CreateUser { impl Handle for ListUsers { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - user::all(&cx.db).await + user::all_accounts(cx.db).await } } impl Handle for ListAdminLogs { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - admin_log::list( - self.actor_id.as_deref(), - self.target_id.as_deref(), - self.action.as_deref(), + log::list_admin( + self.actor_id, + self.target_id, + self.action, self.after_ms, self.before_ms, - &cx.db, + cx.db, ) .await } @@ -160,30 +146,38 @@ impl Handle for ListAdminLogs { impl Handle for GetDailyStats { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - stats::daily(self.days, &cx.db).await + stats::daily(self.days, cx.db).await } } impl Handle for GetOverview { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - overview::read(&cx.sh.services.hub, &cx.sh.services.rooms, &cx.db).await + 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: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; - user::set_suspended(&self.user_id, self.suspended, &cx.db).await?; + managed(&me, self.user_id, cx.db).await?; + user::set_suspended(self.user_id, self.suspended, cx.db).await?; let action = if self.suspended { AdminAction::UserSuspended } else { AdminAction::UserUnsuspended }; - admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?; + log::record_admin(Some(me.id), Some(self.user_id), None, &action, cx.db).await?; if self.suspended { - authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db) - .await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; } Ok(()) @@ -193,14 +187,14 @@ impl Handle for SuspendUser { impl Handle for RevokeSessions { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; - authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&self.user_id), + managed(&me, self.user_id, cx.db).await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; + log::record_admin( + Some(me.id), + Some(self.user_id), None, &AdminAction::SessionsRevoked, - &cx.db, + cx.db, ) .await?; @@ -211,15 +205,15 @@ impl Handle for RevokeSessions { impl Handle for ResetPassword { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; - authentication::reset_password(&self.user_id, &self.password, &cx.db).await?; - authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&self.user_id), + managed(&me, self.user_id, cx.db).await?; + authentication::reset_password(self.user_id, &self.password, cx.db).await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; + log::record_admin( + Some(me.id), + Some(self.user_id), None, &AdminAction::PasswordReset, - &cx.db, + cx.db, ) .await?; @@ -230,15 +224,15 @@ impl Handle for ResetPassword { impl Handle for ClearProfile { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; - user::set_avatar(&self.user_id, None, &mut cx.db).await?; - let user = user::update_status(&self.user_id, "", &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&self.user_id), + managed(&me, self.user_id, cx.db).await?; + avatar::set_user(self.user_id, None, cx.db).await?; + let user = user::update_status(self.user_id, "", cx.db).await?; + log::record_admin( + Some(me.id), + Some(self.user_id), None, &AdminAction::ProfileCleared, - &cx.db, + cx.db, ) .await?; user_updated(&user, cx); @@ -252,24 +246,24 @@ impl Handle for SetRole { let me = me.user()?; let Self { user_id, role } = self; ensure(permission::can_set_role(me.role, me.id == user_id))?; - let user = user::set_role_by_id(&user_id, role, &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), + let user = user::set_role_by_id(user_id, role, cx.db).await?; + log::record_admin( + Some(me.id), + Some(user_id), None, &AdminAction::RoleChanged { role }, - &cx.db, + cx.db, ) .await?; user_updated(&user, cx); if permission::is_builder(role) { - if let Some(community_id) = cx.sh.services.rooms.set_muted(&user_id, false) { + if let Some(community_id) = cx.sh.services.rooms.set_muted(user_id, false) { cx.out - .push(voice_muted(Some(community_id), &user_id, false, &cx.db).await?); + .push(voice_muted(Some(community_id), user_id, false, cx.db).await?); } } else { - user::set_ghost(&user_id, false, &cx.db).await?; - cx.sh.services.hub.kick_user(&user_id, Close::Revoked); + user::set_ghost(user_id, false, cx.db).await?; + cx.sh.services.hub.kick_user(user_id, Close::Revoked); } Ok(user) @@ -280,49 +274,42 @@ impl Handle for DeleteUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; let user_id = self.user_id; - let rooms = &cx.sh.services.rooms; - let target = user::read(&user_id, &cx.db).await?; + let target = user::read(user_id, cx.db).await?; ensure(permission::can_delete_user( me.role, me.id == user_id, target.role, ))?; - let tx = cx.db.transaction().await?; - let mut broadcasts = Vec::new(); if permission::is_builder(me.role) && me.id != user_id { - admin_log::record( - Some(&me.id), - Some(&user_id), + log::record_admin( + Some(me.id), + Some(user_id), None, &AdminAction::UserDeleted, - &tx, + cx.db, ) .await?; } - for community_id in user_community::owned(&user_id, &tx).await? { - let member_ids = user_community::member_ids(&community_id, &tx).await?; - broadcasts.extend(voice_closed(rooms, &community_id, &tx).await?); - community::delete(&community_id, &user_id, &tx).await?; + let departed = leave_user_voice(&cx.sh.services.rooms, user_id, cx.db).await?; + cx.out.extend(departed); + for community_id in member::owned(user_id, cx.db).await? { + let member_ids = member::member_ids(community_id, cx.db).await?; + delete_community(community_id, cx).await?; let event = Event::CommunityDeleted { community_id }; - broadcasts.push(Broadcast::new(To::Users(member_ids), event)); + cx.out.push(Broadcast::new(To::Users(member_ids), event)); } - for community in community::communities_of(&user_id, &tx).await? { - let member_ids = user_community::member_ids(&community.id, &tx).await?; + for community in community::communities_of(user_id, cx.db).await? { + let member_ids = member::member_ids(community.id, cx.db).await?; if community.kind.is_direct() { - community::delete(&community.id, &user_id, &tx).await?; + delete_community(community.id, cx).await?; } - let event = Event::UserDeleted { - user_id: user_id.clone(), - }; - broadcasts.push(Broadcast::new(To::Users(member_ids), event)); + let event = Event::UserDeleted { user_id }; + cx.out.push(Broadcast::new(To::Users(member_ids), event)); } - broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?); - user::delete(&user_id, &tx).await?; - tx.commit().await?; + user::delete(user_id, cx.db).await?; if me.id != user_id { - cx.sh.services.hub.kick_user(&user_id, Close::Revoked); + cx.sh.services.hub.kick_user(user_id, Close::Revoked); } - cx.out.extend(broadcasts); Ok(()) } @@ -335,19 +322,19 @@ impl Handle for WatchCommunity { cx.client.watch(None); return Ok(()); }; - allowed(&me, &community_id, &cx.db, permission::can_read).await?; - let outsider = is_outsider(&me.id, &community_id, &cx.db).await?; - cx.client.watch(outsider.then_some(community_id.as_str())); + allowed(&me, community_id, cx.db, permission::can_read).await?; + let outsider = is_outsider(me.id, community_id, cx.db).await?; + cx.client.watch(outsider.then_some(community_id)); let visit = - permission::is_builder(me.role) && outsider && user::is_ghost(&me.id, &cx.db).await?; - if visit && cx.client.first_visit(&community_id) { - let community = community::label(&community_id, &cx.db).await?; - admin_log::record( - Some(&me.id), + 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, + cx.db, ) .await?; } @@ -359,8 +346,8 @@ impl Handle for WatchCommunity { impl Handle for ListAllCommunities { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let mut summaries = Vec::new(); - for community in community::groups(&cx.db).await? { - let members = user_community::members(&community.id, &cx.db).await?; + 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) @@ -383,60 +370,52 @@ impl Handle for TransferOwnership { community_id, user_id, } = self; - ensure_editable(&community_id, &cx.db).await?; - allowed( - &me, - &community_id, - &cx.db, - permission::can_transfer_ownership, - ) - .await?; - let tx = cx.db.transaction().await?; - let members = user_community::members(&community_id, &tx).await?; + ensure_editable(community_id, cx.db).await?; + allowed(&me, community_id, cx.db, permission::can_transfer_ownership).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.clone(), Rank::Owner)]; + let mut changes = vec![(user_id, Rank::Owner)]; if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) { - user_community::set_rank(&previous.user.id, &community_id, Rank::Admin, &tx).await?; + member::set_rank(previous.user.id, community_id, Rank::Admin, cx.db).await?; log::record( - &community_id, - Some(&me.id), - Some(&previous.user.id), + community_id, + Some(me.id), + Some(previous.user.id), &LogAction::RankChanged { rank: Rank::Admin }, - &tx, + cx.db, ) .await?; - changes.push((previous.user.id.clone(), Rank::Admin)); + changes.push((previous.user.id, Rank::Admin)); } - user_community::set_rank(&user_id, &community_id, Rank::Owner, &tx).await?; + member::set_rank(user_id, community_id, Rank::Owner, cx.db).await?; log::record( - &community_id, - Some(&me.id), - Some(&user_id), + community_id, + Some(me.id), + Some(user_id), &LogAction::RankChanged { rank: Rank::Owner }, - &tx, + cx.db, ) .await?; if permission::is_builder(me.role) { - let community = community::read(&community_id, &me.id, &tx).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), + 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, - &tx, + cx.db, ) .await?; } - tx.commit().await?; for (changed_id, rank) in changes { cx.emit( - To::Community(community_id.clone()), + To::Community(community_id), Event::RankChanged { - community_id: community_id.clone(), + community_id, user_id: changed_id, rank, }, @@ -451,18 +430,18 @@ impl Handle for TimeoutUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; let Self { user_id, minutes } = self; - managed(&me, &user_id, &cx.db).await?; + 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?; + user::set_timeout(user_id, until, cx.db).await?; if until.is_some() { - authentication::revoke(&cx.sh.services.hub, Revoke::User(&user_id), &cx.db).await?; + authentication::revoke(&cx.sh.services.hub, Revoke::User(user_id), cx.db).await?; } - admin_log::record( - Some(&me.id), - Some(&user_id), + log::record_admin( + Some(me.id), + Some(user_id), None, &AdminAction::UserTimedOut { minutes }, - &cx.db, + cx.db, ) .await?; @@ -478,33 +457,30 @@ impl Handle for BanUser { reason, scope, } = self; - let target = managed(&me, &user_id, &cx.db).await?; - let tx = cx.db.transaction().await?; - user::set_suspended(&user_id, true, &tx).await?; - authentication::revoke_sessions(&user_id, &tx).await?; + 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.to_ascii_lowercase(), + &target.username, reason.as_deref(), - &me.id, - &tx, + cx.db, ) .await?; if scope == BanScope::AccountAndIp - && let Some(address) = user::last_ip(&user_id, &tx).await? + && let Some(address) = user::last_ip(user_id, cx.db).await? { - server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx).await?; + server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), cx.db).await?; } - admin_log::record( - Some(&me.id), - Some(&user_id), + log::record_admin( + Some(me.id), + Some(user_id), None, &AdminAction::UserBanned { reason }, - &tx, + cx.db, ) .await?; - tx.commit().await?; - cx.sh.services.hub.kick_user(&user_id, Close::Banned); + cx.sh.services.hub.kick_user(user_id, Close::Banned); Ok(()) } @@ -512,15 +488,15 @@ impl Handle for BanUser { impl Handle for ListServerBans { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - server_ban::list(&cx.db).await + server_ban::list(cx.db).await } } impl Handle for RemoveServerBan { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - server_ban::remove(&self.id, &cx.db).await?; - admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &cx.db).await?; + server_ban::remove(self.id, cx.db).await?; + log::record_admin(Some(me.id), None, None, &AdminAction::BanRemoved, cx.db).await?; Ok(()) } @@ -530,15 +506,9 @@ impl Handle for CreateInviteCode { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; ensure(permission::is_builder(me.role) && self.uses > 0)?; - let code = invite::create(self.uses, self.hours, &me, &cx.db).await?; - admin_log::record( - Some(&me.id), - None, - None, - &AdminAction::InviteCreated, - &cx.db, - ) - .await?; + 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) } @@ -546,22 +516,15 @@ impl Handle for CreateInviteCode { impl Handle for ListInviteCodes { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - invite::list(&cx.db).await + registration_code::list(cx.db).await } } impl Handle for DeleteInviteCode { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - invite::delete(&self.code, &cx.db).await?; - admin_log::record( - Some(&me.id), - None, - None, - &AdminAction::InviteDeleted, - &cx.db, - ) - .await?; + registration_code::delete(&self.code, cx.db).await?; + log::record_admin(Some(me.id), None, None, &AdminAction::InviteDeleted, cx.db).await?; Ok(()) } @@ -571,11 +534,11 @@ impl Handle for SearchMessages { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { message::search( self.text.as_deref(), - self.user_id.as_deref(), - self.community_id.as_deref(), + self.user_id, + self.community_id, self.after_ms, self.before_ms, - &cx.db, + cx.db, ) .await } @@ -584,15 +547,15 @@ impl Handle for SearchMessages { impl Handle for SearchCommunity { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; message::search( Some(&self.text), None, - Some(&self.community_id), + Some(self.community_id), None, None, - &cx.db, + cx.db, ) .await } @@ -602,37 +565,20 @@ impl Handle for PurgeUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; let user_id = self.user_id; - managed(&me, &user_id, &cx.db).await?; - let tx = cx.db.transaction().await?; - let upload_ids = attachment::uploads_of(&user_id, &tx).await?; - let message_ids = message::ids_of_user(&user_id, &tx).await?; - let mut deleted: BTreeMap> = BTreeMap::new(); - for message_id in &message_ids { - let message = message::delete(message_id, &tx).await?; - deleted - .entry(message.community_id) - .or_default() - .push(message.id); - } - attachment::delete_uploads(&user_id, &tx).await?; - admin_log::record( - Some(&me.id), - Some(&user_id), + 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: message_ids.len() as u64, + messages: deleted.len() as u64, }, - &tx, + cx.db, ) .await?; - tx.commit().await?; - attachment::remove_files(&upload_ids, &cx.sh.directory); - for (community_id, ids) in deleted { - cx.emit( - To::Community(community_id.clone()), - Event::MessagesDeleted { community_id, ids }, - ); - } + cx.out.extend(messages_deleted(deleted)); Ok(()) } @@ -640,39 +586,28 @@ impl Handle for PurgeUser { impl Handle for ListAttachments { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - attachment::all( - self.user_id.as_deref(), - self.community_id.as_deref(), - &cx.db, - ) - .await + attachment::all(self.user_id, self.community_id, cx.db).await } } impl Handle for DeleteAttachment { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let attachment_id = self.attachment_id; - let stored = attachment::read(&attachment_id, &cx.db).await?; - let community = community::label(&stored.community_id, &cx.db).await?; - let tx = cx.db.transaction().await?; - attachment::delete(&attachment_id, &tx).await?; - admin_log::record( - Some(&me.id), - Some(&stored.uploader_id), + let stored = attachment::read(self.attachment_id, cx.db).await?; + let community = community::label(stored.community_id, cx.db).await?; + attachment::delete(self.attachment_id, cx.db).await?; + log::record_admin( + Some(me.id), + Some(stored.uploader_id), Some(&community), &AdminAction::AttachmentDeleted, - &tx, + cx.db, ) .await?; - let mut broadcast = None; - if let Some(message_id) = &stored.message_id { - let updated = message::read(message_id, &tx).await?; - broadcast = Some(message_event(&updated, Event::MessageUpdated)); + if let Some(message_id) = stored.message_id { + let updated = message::read(message_id, cx.db).await?; + cx.out.push(message_event(&updated, Event::MessageUpdated)); } - tx.commit().await?; - attachment::remove_files(&[attachment_id], &cx.sh.directory); - cx.out.extend(broadcast); Ok(()) } @@ -680,7 +615,7 @@ impl Handle for DeleteAttachment { impl Handle for GetStorageUsage { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - let (users, communities) = attachment::usage(&cx.db).await?; + let (users, communities) = attachment::usage(cx.db).await?; Ok(StorageUsage { users, communities }) } @@ -689,11 +624,11 @@ impl Handle for GetStorageUsage { impl Handle for CreateBackup { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let backup = backup::create(&cx.db, &cx.sh.backups).await?; + let backup = backup::create(&cx.sh.db, &cx.sh.backups).await?; let action = AdminAction::BackupCreated { name: backup.name.clone(), }; - admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; Ok(backup) } @@ -710,7 +645,7 @@ impl Handle for DeleteBackup { let me = me.user()?; backup::delete(&self.name, &cx.sh.backups)?; let action = AdminAction::BackupDeleted { name: self.name }; - admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; Ok(()) } @@ -723,27 +658,25 @@ impl Handle for SetCommunityVoice { community_id, enabled, } = self; - allowed(&me, &community_id, &cx.db, permission::can_manage_voice).await?; - let tx = cx.db.transaction().await?; - community::set_voice_enabled(&community_id, enabled, &tx).await?; - let updated = community::read(&community_id, &me.id, &tx).await?; + allowed(&me, community_id, cx.db, permission::can_manage_voice).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) { - admin_log::record( - Some(&me.id), + log::record_admin( + Some(me.id), None, Some(&updated.name), &AdminAction::CommunityVoiceSet { enabled }, - &tx, + cx.db, ) .await?; } - tx.commit().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) { + for user_id in rooms.room_users(community_id) { + if !permission::is_builder(user::read(user_id, cx.db).await?.role) { cx.out - .extend(leave_room_voice(rooms, &community_id, &user_id, &cx.db).await?); + .extend(leave_room_voice(rooms, community_id, user_id, cx.db).await?); } } } @@ -761,37 +694,37 @@ impl Handle for SetGhost { let me = me.user()?; let enabled = self.enabled; let rooms = &cx.sh.services.rooms; - user::set_ghost(&me.id, enabled, &cx.db).await?; + user::set_ghost(me.id, enabled, cx.db).await?; let action = if enabled { AdminAction::GhostEnabled } else { AdminAction::GhostDisabled }; - admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; let mut broadcasts = Vec::new(); - let outsider = match rooms.room_of(&me.id) { - Some(community_id) => is_outsider(&me.id, &community_id, &cx.db).await?, + let outsider = match rooms.room_of(me.id) { + Some(community_id) => is_outsider(me.id, community_id, cx.db).await?, None => false, }; - if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) { - let community_id = departure.community_id.clone(); + if !outsider && let Some(mut departure) = rooms.set_ghost(me.id, enabled) { + let community_id = departure.community_id; if enabled { broadcasts.extend(shares_ended(&mut departure)); broadcasts - .extend(call_ended(&community_id, &me.id, departure.call_log, &cx.db).await?); + .extend(call_ended(community_id, me.id, departure.call_log, cx.db).await?); let event = Event::VoiceLeft { - community_id: community_id.clone(), - user_id: me.id.clone(), + community_id, + user_id: me.id, }; broadcasts.push(Broadcast::new( - To::CommunityExcept(community_id, me.id.clone()), + To::CommunityExcept(community_id, me.id), event, )); } else { - let muted = user::voice_muted(&me.id, &cx.db).await?; - broadcasts.extend(voice_joined(&community_id, &me.id, muted)); + let muted = user::voice_muted(me.id, cx.db).await?; + broadcasts.extend(voice_joined(community_id, me.id, muted)); if let Some(seconds) = departure.ghost_seconds { - record_ghost_voice(&me.id, &community_id, seconds, &cx.db).await?; + record_ghost_voice(me.id, community_id, seconds, cx.db).await?; } } } diff --git a/crates/server/src/call/community.rs b/crates/server/src/call/community.rs index 1b067bd..bbcc8db 100644 --- a/crates/server/src/call/community.rs +++ b/crates/server/src/call/community.rs @@ -6,67 +6,65 @@ use common::{ }, error::Error, event::Event, - model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User}, + model::{AdminAction, Ban, Community, Id, LogAction, LogEntry, Member, Rank, Sanction, User}, permission, validate::validate_avatar_size, }; use crate::{ - admin_log, call::{Cx, Handle, Me}, - community, - error::ServerError, - log, + db::{self, community::Kind}, + error::{ServerError, ensure, ensure_with}, + files, publish::To, - request::{ - actor_rank, allowed, ensure, ensure_editable, ensure_with, leave_room_voice, voice_closed, - }, - server_settings, user, user_community, + request::{actor_rank, allowed, delete_community, ensure_editable, leave_room_voice}, }; async fn remove_member( me: &User, - community_id: String, - user_id: String, + community_id: Id, + user_id: Id, reason: Option, sanction: Sanction, cx: &mut Cx<'_>, ) -> Result<(), ServerError> { - ensure_editable(&community_id, &cx.db).await?; - let target = user::read(&user_id, &cx.db).await?; + let db = cx.db; + ensure_editable(community_id, db).await?; + let target = db::user::read(user_id, db).await?; ensure(permission::can_moderate( - actor_rank(me, &community_id, &cx.db).await?, - actor_rank(&target, &community_id, &cx.db).await?, + actor_rank(me, community_id, db).await?, + actor_rank(&target, community_id, db).await?, ))?; - let community = community::read(&community_id, &me.id, &cx.db).await?; - let tx = cx.db.transaction().await?; - user_community::leave(&user_id, &community_id, &tx).await?; + let community = db::community::read(community_id, me.id, db).await?; + let left = db::member::leave(user_id, community_id, db).await?; let action = match sanction { Sanction::Ban => { - user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?; + db::member::ban(user_id, community_id, reason.as_deref(), db).await?; LogAction::Banned { reason: reason.clone(), } } - Sanction::Kick => LogAction::Kicked { - reason: reason.clone(), - }, + Sanction::Kick => { + ensure_with(left == 1, Error::NotFound)?; + LogAction::Kicked { + reason: reason.clone(), + } + } }; - log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; - tx.commit().await?; + db::log::record(community_id, Some(me.id), Some(user_id), &action, db).await?; cx.out - .extend(leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?); + .extend(leave_room_voice(&cx.sh.services.rooms, community_id, user_id, db).await?); cx.emit( - To::User(user_id.clone()), + To::User(user_id), Event::Removed { - community_id: community_id.clone(), + community_id, community_name: community.name, sanction, reason, }, ); cx.emit( - To::Community(community_id.clone()), + To::Community(community_id), Event::MemberLeft { community_id, user_id, @@ -79,46 +77,38 @@ async fn remove_member( impl Handle for CreateCommunity { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let limit = server_settings::read(&cx.db) - .await? - .max_communities_per_user; - let owned = user_community::owned_groups(&me.id, &cx.db).await?; - ensure_with(limit == 0 || owned < limit as usize, Error::LimitReached)?; - let tx = cx.db.transaction().await?; - let community = community::create(&self.name, &tx).await?; - user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?; - log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?; - tx.commit().await?; + let db = cx.db; + let limit = db::settings::read(db).await?.max_communities_per_user; + let owned = db::member::owned_groups(me.id, db).await?; + ensure_with(limit == 0 || owned < limit, Error::LimitReached)?; + let community_id = db::community::create(Kind::Group, &self.name, db).await?; + db::member::join(me.id, community_id, Rank::Owner, db).await?; + db::log::record(community_id, Some(me.id), None, &LogAction::Created, db).await?; - Ok(community) + db::community::read(community_id, me.id, db).await } } impl Handle for GetCommunity { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; - community::read(&self.community_id, &me.id, &cx.db).await + db::community::read(self.community_id, me.id, cx.db).await } } impl Handle for UpdateCommunity { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - ensure_editable(&self.community_id, &cx.db).await?; - allowed( - &me, - &self.community_id, - &cx.db, - permission::can_rename_community, - ) - .await?; - let updated = community::update(&self.community_id, &self.name, &me.id, &cx.db).await?; + let db = cx.db; + ensure_editable(self.community_id, db).await?; + allowed(&me, self.community_id, db, permission::can_rename_community).await?; + let updated = db::community::update(self.community_id, &self.name, me.id, db).await?; let action = LogAction::Renamed { name: updated.name.clone(), }; - log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?; + db::log::record(self.community_id, Some(me.id), None, &action, db).await?; cx.emit( To::Community(self.community_id), Event::CommunityUpdated(updated.clone()), @@ -131,30 +121,21 @@ impl Handle for UpdateCommunity { impl Handle for UpdateCommunityAvatar { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - ensure_editable(&self.community_id, &cx.db).await?; - allowed( - &me, - &self.community_id, - &cx.db, - permission::can_rename_community, - ) - .await?; + let db = cx.db; + ensure_editable(self.community_id, db).await?; + allowed(&me, self.community_id, db, permission::can_rename_community).await?; if let Some(bytes) = &self.image { - validate_avatar_size(bytes, server_settings::read(&cx.db).await?.max_avatar_bytes)?; + validate_avatar_size(bytes, db::settings::read(db).await?.max_avatar_bytes)?; + files::check_avatar(bytes)?; } - let updated = community::set_avatar( - &self.community_id, - self.image.as_deref(), - &me.id, - &mut cx.db, - ) - .await?; + db::avatar::set_community(self.community_id, self.image.as_deref(), db).await?; + let updated = db::community::read(self.community_id, me.id, db).await?; let action = if self.image.is_some() { LogAction::AvatarChanged } else { LogAction::AvatarRemoved }; - log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?; + db::log::record(self.community_id, Some(me.id), None, &action, db).await?; cx.emit( To::Community(self.community_id), Event::CommunityUpdated(updated.clone()), @@ -167,36 +148,27 @@ impl Handle for UpdateCommunityAvatar { impl Handle for DeleteCommunity { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - ensure_editable(&self.community_id, &cx.db).await?; - allowed( - &me, - &self.community_id, - &cx.db, - permission::can_delete_community, - ) - .await?; - let tx = cx.db.transaction().await?; - let member_ids = user_community::member_ids(&self.community_id, &tx).await?; - let owned = - user_community::rank(&me.id, &self.community_id, &tx).await? == Some(Rank::Owner); - let deleted = community::delete(&self.community_id, &me.id, &tx).await?; + let db = cx.db; + ensure_editable(self.community_id, db).await?; + allowed(&me, self.community_id, db, permission::can_delete_community).await?; + let member_ids = db::member::member_ids(self.community_id, db).await?; + let owned = db::member::rank(me.id, self.community_id, db).await? == Some(Rank::Owner); + let deleted = db::community::read(self.community_id, me.id, db).await?; if permission::is_builder(me.role) && !owned { - admin_log::record( - Some(&me.id), + db::log::record_admin( + Some(me.id), None, Some(&deleted.name), &AdminAction::CommunityDeleted, - &tx, + db, ) .await?; } - tx.commit().await?; - cx.out - .extend(voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?); + delete_community(self.community_id, cx).await?; cx.emit( To::Users(member_ids), Event::CommunityDeleted { - community_id: deleted.id.clone(), + community_id: deleted.id, }, ); @@ -207,30 +179,25 @@ impl Handle for DeleteCommunity { impl Handle for LeaveCommunity { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - ensure_editable(&self.community_id, &cx.db).await?; - allowed(&me, &self.community_id, &cx.db, permission::can_leave).await?; - let tx = cx.db.transaction().await?; - user_community::leave(&me.id, &self.community_id, &tx).await?; - log::record( - &self.community_id, - Some(&me.id), - None, - &LogAction::Left, - &tx, - ) - .await?; - if user_community::member_ids(&self.community_id, &tx) + let db = cx.db; + ensure_editable(self.community_id, db).await?; + let rank = db::member::rank(me.id, self.community_id, db).await?; + ensure(permission::can_leave(rank))?; + let left = db::member::leave(me.id, self.community_id, db).await?; + ensure_with(left == 1, Error::NotFound)?; + db::log::record(self.community_id, Some(me.id), None, &LogAction::Left, db).await?; + if db::member::member_ids(self.community_id, db) .await? .is_empty() { - community::delete(&self.community_id, &me.id, &tx).await?; + delete_community(self.community_id, cx).await?; + } else { + let broadcasts = + leave_room_voice(&cx.sh.services.rooms, self.community_id, me.id, db).await?; + cx.out.extend(broadcasts); } - tx.commit().await?; - let broadcasts = - leave_room_voice(&cx.sh.services.rooms, &self.community_id, &me.id, &cx.db).await?; - cx.out.extend(broadcasts); cx.emit( - To::Community(self.community_id.clone()), + To::Community(self.community_id), Event::MemberLeft { community_id: self.community_id, user_id: me.id, @@ -245,16 +212,16 @@ impl Handle for ListCommunities { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - community::communities_of(&me.id, &cx.db).await + db::community::communities_of(me.id, cx.db).await } } impl Handle for ListMembers { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; - user_community::members(&self.community_id, &cx.db).await + db::member::members(self.community_id, cx.db).await } } @@ -291,14 +258,15 @@ impl Handle for BanMember { impl Handle for Unban { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?; - user_community::unban(&self.user_id, &self.community_id, &cx.db).await?; - log::record( - &self.community_id, - Some(&me.id), - Some(&self.user_id), + let db = cx.db; + allowed(&me, self.community_id, db, permission::can_unban).await?; + db::member::unban(self.user_id, self.community_id, db).await?; + db::log::record( + self.community_id, + Some(me.id), + Some(self.user_id), &LogAction::Unbanned, - &cx.db, + db, ) .await?; @@ -309,33 +277,34 @@ impl Handle for Unban { impl Handle for ListBans { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?; + allowed(&me, self.community_id, cx.db, permission::can_unban).await?; - user_community::bans(&self.community_id, &cx.db).await + db::member::bans(self.community_id, cx.db).await } } impl Handle for SetRank { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - ensure_editable(&self.community_id, &cx.db).await?; - let target = user::read(&self.user_id, &cx.db).await?; + let db = cx.db; + ensure_editable(self.community_id, db).await?; + let target = db::user::read(self.user_id, db).await?; ensure(permission::can_set_rank( - actor_rank(&me, &self.community_id, &cx.db).await?, - actor_rank(&target, &self.community_id, &cx.db).await?, + actor_rank(&me, self.community_id, db).await?, + actor_rank(&target, self.community_id, db).await?, self.rank, ))?; - user_community::set_rank(&self.user_id, &self.community_id, self.rank, &cx.db).await?; - log::record( - &self.community_id, - Some(&me.id), - Some(&self.user_id), + db::member::set_rank(self.user_id, self.community_id, self.rank, db).await?; + db::log::record( + self.community_id, + Some(me.id), + Some(self.user_id), &LogAction::RankChanged { rank: self.rank }, - &cx.db, + db, ) .await?; cx.emit( - To::Community(self.community_id.clone()), + To::Community(self.community_id), Event::RankChanged { community_id: self.community_id, user_id: self.user_id, @@ -350,8 +319,8 @@ impl Handle for SetRank { impl Handle for ListLogs { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read_logs).await?; + allowed(&me, self.community_id, cx.db, permission::can_read_logs).await?; - log::list(&self.community_id, &cx.db).await + db::log::list(self.community_id, cx.db).await } } diff --git a/crates/server/src/call/message.rs b/crates/server/src/call/message.rs index 90a943b..fca2525 100644 --- a/crates/server/src/call/message.rs +++ b/crates/server/src/call/message.rs @@ -5,20 +5,17 @@ use common::{ }, error::Error, event::Event, - model::{AdminAction, LogAction, Message, ServerSettings, Unread, User}, + model::{AdminAction, Id, LogAction, Message, ServerSettings, Unread, User}, permission, validate::{validate_new_message, validate_vote}, }; use crate::{ - admin_log, call::{Cx, Handle, Me}, - community, - error::ServerError, - log, message, + db::{self, community::Kind, message::ForwardMode}, + error::{ServerError, ensure, ensure_with}, publish::To, - request::{actor_rank, allowed, ensure, is_outsider, message_event}, - server_settings, stats, user, user_community, + request::{actor_rank, allowed, is_outsider, message_event}, }; fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(), ServerError> { @@ -30,32 +27,36 @@ fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<( .sh .services .rate_limit - .allow(&me.id, settings.messages_per_minute)?) + .allow(&me.id.to_string(), settings.messages_per_minute)?) } impl Handle for CreateMessage { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let settings = server_settings::read(&cx.db).await?; + let settings = db::settings::read(cx.db).await?; limit_messages(&me, &settings, cx)?; validate_new_message( &self.body, self.attachments.len(), settings.max_message_length as usize, )?; - allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; - let tx = cx.db.transaction().await?; - let created = message::create( - &me.id, - &self.community_id, + allowed(&me, self.community_id, cx.db, permission::can_post).await?; + if let Some(reply_to) = self.reply_to { + ensure_with( + db::message::community_of(reply_to, cx.db).await? == self.community_id, + Error::NotFound, + )?; + } + let created = db::message::create( + me.id, + self.community_id, &self.body, &self.attachments, - self.reply_to.as_deref(), - &tx, + self.reply_to, + cx.db, ) .await?; - stats::mark_active(&me.id, &tx).await?; - tx.commit().await?; + db::stats::mark_active(me.id, cx.db).await?; cx.out.push(message_event(&created, Event::MessageCreated)); Ok(created) @@ -65,34 +66,24 @@ impl Handle for CreateMessage { impl Handle for ForwardMessages { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?; + limit_messages(&me, &db::settings::read(cx.db).await?, cx)?; ensure(permission::can_post( - actor_rank(&me, &self.community_id, &cx.db).await?, + actor_rank(&me, self.community_id, cx.db).await?, ))?; - let tx = cx.db.transaction().await?; let mut sources = Vec::new(); for message_id in &self.message_ids { - let source = message::read(message_id, &tx).await?; + let source = db::message::read(*message_id, cx.db).await?; ensure(permission::can_read( - actor_rank(&me, &source.community_id, &tx).await?, + actor_rank(&me, source.community_id, cx.db).await?, ))?; sources.push(source); } let mode = if self.snippet { - message::ForwardMode::Snippet + ForwardMode::Snippet } else { - message::ForwardMode::Copy + ForwardMode::Copy }; - let created = message::forward( - &me, - &self.community_id, - &sources, - mode, - &cx.sh.directory, - &tx, - ) - .await?; - tx.commit().await?; + let created = db::message::forward(me.id, self.community_id, &sources, mode, cx.db).await?; for message in &created { cx.out.push(message_event(message, Event::MessageCreated)); } @@ -104,15 +95,15 @@ impl Handle for ForwardMessages { impl Handle for UpdateMessage { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let existing = message::read(&self.message_id, &cx.db).await?; - allowed(&me, &existing.community_id, &cx.db, permission::can_post).await?; + let existing = db::message::read(self.message_id, cx.db).await?; + allowed(&me, existing.community_id, cx.db, permission::can_post).await?; ensure(existing.user_id == me.id)?; validate_new_message( &self.body, 0, - server_settings::read(&cx.db).await?.max_message_length as usize, + db::settings::read(cx.db).await?.max_message_length as usize, )?; - let updated = message::update(&self.message_id, &self.body, &cx.db).await?; + let updated = db::message::update(self.message_id, &self.body, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(updated) @@ -122,40 +113,40 @@ impl Handle for UpdateMessage { impl Handle for DeleteMessage { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let existing = message::read(&self.message_id, &cx.db).await?; - let author = user::read(&existing.user_id, &cx.db).await?; + let existing = db::message::read(self.message_id, cx.db).await?; + let author = db::user::read(existing.user_id, cx.db).await?; ensure(permission::can_delete_message( - actor_rank(&me, &existing.community_id, &cx.db).await?, - actor_rank(&author, &existing.community_id, &cx.db).await?, + actor_rank(&me, existing.community_id, cx.db).await?, + actor_rank(&author, existing.community_id, cx.db).await?, existing.user_id == me.id, ))?; - let deleted = message::delete(&self.message_id, &cx.db).await?; + db::message::delete(existing.id, cx.db).await?; if existing.user_id != me.id { - log::record( - &deleted.community_id, - Some(&me.id), - Some(&existing.user_id), + db::log::record( + existing.community_id, + Some(me.id), + Some(existing.user_id), &LogAction::MessageDeleted, - &cx.db, + cx.db, ) .await?; } if permission::is_builder(me.role) && existing.user_id != me.id { - let community = community::label(&deleted.community_id, &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&existing.user_id), + let community = db::community::label(existing.community_id, cx.db).await?; + db::log::record_admin( + Some(me.id), + Some(existing.user_id), Some(&community), &AdminAction::MessageDeleted, - &cx.db, + cx.db, ) .await?; } cx.emit( - To::Community(deleted.community_id.clone()), + To::Community(existing.community_id), Event::MessagesDeleted { - community_id: deleted.community_id, - ids: vec![deleted.id], + community_id: existing.community_id, + ids: vec![existing.id], }, ); @@ -166,21 +157,19 @@ impl Handle for DeleteMessage { impl Handle for CreatePoll { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let settings = server_settings::read(&cx.db).await?; + let settings = db::settings::read(cx.db).await?; limit_messages(&me, &settings, cx)?; - allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; - let tx = cx.db.transaction().await?; - let created = message::create_poll( - &me.id, - &self.community_id, + allowed(&me, self.community_id, cx.db, permission::can_post).await?; + let created = db::message::create_poll( + me.id, + self.community_id, &self.question, &self.options, self.multiple, - &tx, + cx.db, ) .await?; - stats::mark_active(&me.id, &tx).await?; - tx.commit().await?; + db::stats::mark_active(me.id, cx.db).await?; cx.out.push(message_event(&created, Event::MessageCreated)); Ok(created) @@ -190,13 +179,13 @@ impl Handle for CreatePoll { impl Handle for Vote { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let existing = message::read(&self.message_id, &cx.db).await?; + let existing = db::message::read(self.message_id, cx.db).await?; ensure(permission::can_read( - actor_rank(&me, &existing.community_id, &cx.db).await?, + actor_rank(&me, existing.community_id, cx.db).await?, ))?; let poll = existing.poll.as_ref().ok_or(Error::NotFound)?; validate_vote(poll, &self.positions)?; - let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?; + let updated = db::message::vote(self.message_id, me.id, &self.positions, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) @@ -206,12 +195,12 @@ impl Handle for Vote { impl Handle for ClosePoll { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let existing = message::read(&self.message_id, &cx.db).await?; + let existing = db::message::read(self.message_id, cx.db).await?; ensure(permission::can_close_poll( - actor_rank(&me, &existing.community_id, &cx.db).await?, + actor_rank(&me, existing.community_id, cx.db).await?, existing.user_id == me.id, ))?; - let updated = message::close_poll(&self.message_id, &cx.db).await?; + let updated = db::message::close_poll(self.message_id, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) @@ -221,11 +210,11 @@ impl Handle for ClosePoll { impl Handle for React { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let existing = message::read(&self.message_id, &cx.db).await?; + let existing = db::message::read(self.message_id, cx.db).await?; ensure(permission::can_read( - actor_rank(&me, &existing.community_id, &cx.db).await?, + actor_rank(&me, existing.community_id, cx.db).await?, ))?; - let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?; + let updated = db::message::react(self.message_id, me.id, &self.emoji, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) @@ -235,13 +224,14 @@ impl Handle for React { impl Handle for Pin { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let existing = message::read(&self.message_id, &cx.db).await?; - let direct = community::is_direct(&existing.community_id, &cx.db).await?; + let existing = db::message::read(self.message_id, cx.db).await?; + let direct = + db::community::kind_of(existing.community_id, cx.db).await? == Some(Kind::Direct); ensure(permission::can_pin( - actor_rank(&me, &existing.community_id, &cx.db).await?, + actor_rank(&me, existing.community_id, cx.db).await?, direct, ))?; - let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?; + let updated = db::message::pin(self.message_id, self.pinned, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); Ok(()) @@ -251,18 +241,18 @@ impl Handle for Pin { impl Handle for ListPins { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; - message::pinned(&self.community_id, &cx.db).await + db::message::pinned(self.community_id, cx.db).await } } impl Handle for ListMessages { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; - message::read_page(&self.community_id, self.before.as_deref(), &cx.db).await + db::message::read_page(self.community_id, self.before, cx.db).await } } @@ -270,16 +260,19 @@ impl Handle for ListUnreads { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - user_community::unreads(&me.id, &me.username, &cx.db).await + db::member::unreads(me.id, &me.username, cx.db).await } } impl Handle for MarkRead { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - ensure(!is_outsider(&me.id, &self.community_id, &cx.db).await?)?; - message::ensure_in_community(&self.message_id, &self.community_id, &cx.db).await?; - user_community::mark_read(&me.id, &self.community_id, &self.message_id, &cx.db).await?; + ensure(!is_outsider(me.id, self.community_id, cx.db).await?)?; + ensure_with( + db::message::community_of(self.message_id, cx.db).await? == self.community_id, + Error::NotFound, + )?; + db::member::mark_read(me.id, self.community_id, self.message_id, cx.db).await?; Ok(()) } @@ -288,11 +281,11 @@ impl Handle for MarkRead { impl Handle for Typing { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; - if user::is_ghost(&me.id, &cx.db).await? { + allowed(&me, self.community_id, cx.db, permission::can_read).await?; + if db::user::is_ghost(me.id, cx.db).await? { return Ok(()); } - let others: Vec = user_community::member_ids(&self.community_id, &cx.db) + let others: Vec = db::member::member_ids(self.community_id, cx.db) .await? .into_iter() .filter(|user_id| *user_id != me.id) diff --git a/crates/server/src/call/mod.rs b/crates/server/src/call/mod.rs index 943bf75..9d4fbb2 100644 --- a/crates/server/src/call/mod.rs +++ b/crates/server/src/call/mod.rs @@ -8,32 +8,32 @@ mod voice; use std::{future::Future, sync::Arc}; use common::{ - call::{Call, Gate, Request}, + call::{Call, Gate, Login, Register, Request}, error::Error, event::Event, frame::{self, DOWN_MAX}, model::User, permission, }; -use turso::Connection; use crate::{ - error::ServerError, + db::{self, Connection}, + error::{ServerError, ensure}, hub::Client, network::Shared, - publish::{Broadcast, To, publish}, + publish::{Broadcast, To}, request, }; pub(crate) struct Cx<'a> { pub client: &'a Arc, pub sh: &'a Shared, - pub db: Connection, + pub db: &'a Connection, pub out: Vec, } impl<'a> Cx<'a> { - pub(crate) fn new(client: &'a Arc, sh: &'a Shared, db: Connection) -> Self { + pub(crate) fn new(client: &'a Arc, sh: &'a Shared, db: &'a Connection) -> Self { Self { client, sh, @@ -72,10 +72,10 @@ pub(crate) trait Handle: Call { async fn gate(gate: Gate, cx: &Cx<'_>) -> Result { match gate { Gate::Guest => Ok(Me::Guest), - Gate::User => Ok(Me::User(request::authenticated(cx.client, &cx.db).await?)), + Gate::User => Ok(Me::User(request::authenticated(cx.client, cx.db).await?)), Gate::Builder => { - let user = request::authenticated(cx.client, &cx.db).await?; - request::ensure(permission::is_builder(user.role))?; + let user = request::authenticated(cx.client, cx.db).await?; + ensure(permission::is_builder(user.role))?; Ok(Me::User(user)) } @@ -83,14 +83,21 @@ async fn gate(gate: Gate, cx: &Cx<'_>) -> Result { } async fn serve(call: C, cx: &mut Cx<'_>) -> Vec { - let reply = async { + let db = cx.db; + let reply = db::atomic(db, async { call.validate()?; let me = gate(C::GATE, cx).await?; call.handle(me, cx).await - } + }) .await; - publish(cx.sh, std::mem::take(&mut cx.out)).await; + if reply.is_err() { + cx.out.clear(); + } + + encode::(reply) +} +pub(crate) fn encode(reply: Result) -> Vec { let reply = reply.map_err(Error::from); frame::encode(&reply, DOWN_MAX).unwrap_or_else(|_| { frame::encode(&Err::(Error::Server), DOWN_MAX).expect("small") @@ -166,8 +173,8 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { Request::ListVoiceRooms(call) => serve(call, cx).await, Request::KickFromVoice(call) => serve(call, cx).await, Request::ServerMute(call) => serve(call, cx).await, - Request::Register(call) => serve(call, cx).await, - Request::Login(call) => serve(call, cx).await, + Request::Register(_) => encode::(Err(Error::Server.into())), + Request::Login(_) => encode::(Err(Error::Server.into())), Request::Logout(call) => serve(call, cx).await, Request::DeleteUser(call) => serve(call, cx).await, Request::WatchCommunity(call) => serve(call, cx).await, diff --git a/crates/server/src/call/social.rs b/crates/server/src/call/social.rs index 7bbdfea..472dbdd 100644 --- a/crates/server/src/call/social.rs +++ b/crates/server/src/call/social.rs @@ -7,36 +7,32 @@ use common::{ error::Error, event::Event, model::{ - AdminAction, Community, Friends, Invitation, LogAction, Member, Rank, Report, ReportStatus, - User, + AdminAction, Community, Friends, Id, Invitation, LogAction, Member, Rank, Report, + ReportStatus, User, }, permission, }; use crate::{ - admin_log, call::{Cx, Handle, Me}, - community, direct, - error::ServerError, - friend, invitation, log, message, notes, + db::{self, direct::Opening, friend::FriendState}, + error::{ServerError, ensure, ensure_with}, publish::To, - report, - request::{actor_rank, allowed, ensure, ensure_editable, ensure_with}, - user, user_community, + request::{actor_rank, allowed, ensure_editable}, }; -async fn friends_updated(user_ids: [&str; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> { +async fn friends_updated(user_ids: [Id; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> { for user_id in user_ids { - let event = Event::FriendsUpdated(friend::state(user_id, &cx.db).await?); - cx.emit(To::User(user_id.to_string()), event); + let event = Event::FriendsUpdated(db::friend::state(user_id, cx.db).await?); + cx.emit(To::User(user_id), event); } Ok(()) } -async fn invitations_updated(user_id: &str, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let event = Event::InvitationsUpdated(invitation::of(user_id, &cx.db).await?); - cx.emit(To::User(user_id.to_string()), event); +async fn invitations_updated(user_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let event = Event::InvitationsUpdated(db::invitation::of(user_id, cx.db).await?); + cx.emit(To::User(user_id), event); Ok(()) } @@ -45,7 +41,7 @@ impl Handle for FindUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - user::by_username(&self.username, &cx.db) + db::user::by_username(&self.username, cx.db) .await? .filter(|found| found.id != me.id) .ok_or(Error::NotFound.into()) @@ -55,14 +51,15 @@ impl Handle for FindUser { impl Handle for OpenDirect { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - match direct::open(&me.id, &self.user_id, &mut cx.db).await? { - direct::Opening::Created(community) => { - let peer_view = community::read(&community.id, &self.user_id, &cx.db).await?; + ensure(me.id != self.user_id)?; + match db::direct::open(me.id, self.user_id, cx.db).await? { + Opening::Created(community) => { + let peer_view = db::community::read(community.id, self.user_id, cx.db).await?; cx.emit(To::User(self.user_id), Event::CommunityAdded(peer_view)); Ok(community) } - direct::Opening::Existing(community) => Ok(community), + Opening::Existing(community) => Ok(community), } } } @@ -70,8 +67,9 @@ impl Handle for OpenDirect { impl Handle for OpenNotes { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - - notes::open(&me.id, &mut cx.db).await + match db::direct::open(me.id, me.id, cx.db).await? { + Opening::Created(community) | Opening::Existing(community) => Ok(community), + } } } @@ -79,65 +77,75 @@ impl Handle for ListFriends { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - friend::state(&me.id, &cx.db).await + db::friend::state(me.id, cx.db).await } } impl Handle for AddFriend { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - friend::add(&me.id, &self.user_id, &mut cx.db).await?; + let db = cx.db; + ensure_with(me.id != self.user_id, Error::Forbidden)?; + ensure_with( + db::friend::pair(me.id, self.user_id, db).await?.is_none(), + Error::Taken, + )?; + match db::friend::pair(self.user_id, me.id, db).await? { + Some(FriendState::Requested) => db::friend::accept(me.id, self.user_id, db).await?, + _ => db::friend::request(me.id, self.user_id, db).await?, + } - friends_updated([&me.id, &self.user_id], cx).await + friends_updated([me.id, self.user_id], cx).await } } impl Handle for AcceptFriend { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - friend::accept(&me.id, &self.user_id, &mut cx.db).await?; + db::friend::accept(me.id, self.user_id, cx.db).await?; - friends_updated([&me.id, &self.user_id], cx).await + friends_updated([me.id, self.user_id], cx).await } } impl Handle for RemoveFriend { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - friend::remove(&me.id, &self.user_id, &mut cx.db).await?; + db::friend::remove(me.id, self.user_id, cx.db).await?; - friends_updated([&me.id, &self.user_id], cx).await + friends_updated([me.id, self.user_id], cx).await } } impl Handle for Invite { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - ensure_editable(&self.community_id, &cx.db).await?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; - let target = user::read(&self.user_id, &cx.db).await?; - if user_community::rank(&self.user_id, &self.community_id, &cx.db) + let db = cx.db; + ensure_editable(self.community_id, db).await?; + allowed(&me, self.community_id, db, permission::can_read).await?; + let target = db::user::read(self.user_id, db).await?; + if db::member::rank(self.user_id, self.community_id, db) .await? .is_some() { return Err(Error::AlreadyMember.into()); } - let banned = user_community::is_banned(&self.user_id, &self.community_id, &cx.db).await?; + let banned = db::member::is_banned(self.user_id, self.community_id, db).await?; ensure(permission::can_join(target.role, banned))?; - if invitation::exists(&self.community_id, &self.user_id, &cx.db).await? { + if db::invitation::exists(self.community_id, self.user_id, db).await? { return Err(Error::AlreadyInvited.into()); } - invitation::insert(&self.community_id, &self.user_id, &me.id, &cx.db).await?; - log::record( - &self.community_id, - Some(&me.id), - Some(&self.user_id), + db::invitation::insert(self.community_id, self.user_id, me.id, db).await?; + db::log::record( + self.community_id, + Some(me.id), + Some(self.user_id), &LogAction::Invited, - &cx.db, + db, ) .await?; - invitations_updated(&self.user_id, cx).await + invitations_updated(self.user_id, cx).await } } @@ -145,37 +153,29 @@ impl Handle for ListInvitations { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - invitation::of(&me.id, &cx.db).await + db::invitation::of(me.id, cx.db).await } } impl Handle for AcceptInvitation { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let tx = cx.db.transaction().await?; - invitation::take(&self.community_id, &me.id, &tx).await?; - let banned = user_community::is_banned(&me.id, &self.community_id, &tx).await?; + let db = cx.db; + db::invitation::take(self.community_id, me.id, db).await?; + let banned = db::member::is_banned(me.id, self.community_id, db).await?; ensure(permission::can_join(me.role, banned))?; - user_community::join(&me.id, &self.community_id, Rank::Member, &tx).await?; - log::record( - &self.community_id, - Some(&me.id), - None, - &LogAction::Joined, - &tx, - ) - .await?; - let community = community::read(&self.community_id, &me.id, &tx).await?; - tx.commit().await?; + db::member::join(me.id, self.community_id, Rank::Member, db).await?; + db::log::record(self.community_id, Some(me.id), None, &LogAction::Joined, db).await?; + let community = db::community::read(self.community_id, me.id, db).await?; let event = Event::MemberJoined { - community_id: self.community_id.clone(), + community_id: self.community_id, member: Member { user: me.clone(), rank: Rank::Member, }, }; cx.emit(To::Community(self.community_id), event); - invitations_updated(&me.id, cx).await?; + invitations_updated(me.id, cx).await?; Ok(community) } @@ -184,30 +184,31 @@ impl Handle for AcceptInvitation { impl Handle for DeclineInvitation { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - invitation::take(&self.community_id, &me.id, &cx.db).await?; + db::invitation::take(self.community_id, me.id, cx.db).await?; - invitations_updated(&me.id, cx).await + invitations_updated(me.id, cx).await } } impl Handle for ReportMessage { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - let message = message::read(&self.message_id, &cx.db).await?; - let actor = actor_rank(&me, &message.community_id, &cx.db).await?; + let db = cx.db; + let message = db::message::read(self.message_id, db).await?; + let actor = actor_rank(&me, message.community_id, db).await?; ensure(permission::can_read(actor) && me.id != message.user_id)?; ensure_with( - !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?, + !db::report::is_open(me.id, message.user_id, Some(self.message_id), db).await?, Error::Taken, )?; - report::insert( - &me.id, - &message.user_id, - Some(&self.message_id), - Some(&message.community_id), + db::report::insert( + me.id, + message.user_id, + Some(self.message_id), + Some(message.community_id), Some(&message.body), &self.reason, - &cx.db, + db, ) .await?; cx.emit(To::Builders, Event::ReportCreated); @@ -219,22 +220,14 @@ impl Handle for ReportMessage { impl Handle for ReportUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - user::read(&self.user_id, &cx.db).await?; + let db = cx.db; + db::user::read(self.user_id, db).await?; ensure(me.id != self.user_id)?; ensure_with( - !report::is_open(&me.id, &self.user_id, None, &cx.db).await?, + !db::report::is_open(me.id, self.user_id, None, db).await?, Error::Taken, )?; - report::insert( - &me.id, - &self.user_id, - None, - None, - None, - &self.reason, - &cx.db, - ) - .await?; + db::report::insert(me.id, self.user_id, None, None, None, &self.reason, db).await?; cx.emit(To::Builders, Event::ReportCreated); Ok(()) @@ -243,23 +236,24 @@ impl Handle for ReportUser { impl Handle for ListReports { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - report::list(self.status, &cx.db).await + db::report::list(self.status, cx.db).await } } impl Handle for HandleReport { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; + let db = cx.db; ensure(permission::is_builder(me.role) && self.status != ReportStatus::Open)?; - let target = report::handle(&self.report_id, self.status, &me.id, &cx.db).await?; - admin_log::record( - Some(&me.id), - target.as_deref(), + let target = db::report::handle(self.report_id, self.status, me.id, db).await?; + db::log::record_admin( + Some(me.id), + target, None, &AdminAction::ReportHandled { status: self.status, }, - &cx.db, + db, ) .await?; diff --git a/crates/server/src/call/user.rs b/crates/server/src/call/user.rs index fcd725d..f992053 100644 --- a/crates/server/src/call/user.rs +++ b/crates/server/src/call/user.rs @@ -4,42 +4,40 @@ use common::{ UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser, }, event::Event, - model::{AdminAction, Presence, ServerSettings, SessionInfo, User}, + model::{AdminAction, Id, Presence, ServerSettings, SessionInfo, User}, validate::validate_avatar_size, }; use crate::{ - admin_log, authentication, + authentication, call::{Cx, Handle, Me}, + db, error::ServerError, + files, publish::{To, related_user_ids}, request::{effective_presence, managed, presence_changed}, - server_settings, user, }; pub(super) fn user_updated(user: &User, cx: &mut Cx<'_>) { - cx.emit( - To::Related(user.id.clone()), - Event::UserUpdated(user.clone()), - ); + cx.emit(To::Related(user.id), Event::UserUpdated(user.clone())); } impl Handle for GetSettings { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - server_settings::read(&cx.db).await + db::settings::read(cx.db).await } } impl Handle for GetUser { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - user::read(&self.user_id, &cx.db).await + db::user::read(self.user_id, cx.db).await } } impl Handle for UpdateUser { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let user = user::update(&me.id, &self.username, &cx.db).await?; + let user = db::user::update(me.id, &self.username, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -49,7 +47,7 @@ impl Handle for UpdateUser { impl Handle for UpdateStatus { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let user = user::update_status(&me.id, &self.status, &cx.db).await?; + let user = db::user::update_status(me.id, &self.status, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -59,21 +57,21 @@ impl Handle for UpdateStatus { impl Handle for UpdatePresence { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - user::update_presence(&me.id, self.presence, &cx.db).await?; + db::user::update_presence(me.id, self.presence, cx.db).await?; cx.out - .extend(presence_changed(&cx.sh.services.hub, &me.id, &cx.db).await?); + .extend(presence_changed(&cx.sh.services.hub, me.id, cx.db).await?); Ok(()) } } impl Handle for ListPresences { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; let hub = &cx.sh.services.hub; let mut presences = Vec::new(); - for user_id in related_user_ids(&me.id, &cx.db).await? { - let effective = effective_presence(hub, &user_id, &cx.db).await?; + for user_id in related_user_ids(me.id, cx.db).await? { + let effective = effective_presence(hub, user_id, cx.db).await?; if effective != Presence::Offline || user_id == me.id { presences.push((user_id, effective)); } @@ -86,9 +84,11 @@ impl Handle for ListPresences { impl Handle for UpdateAvatar { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let maximum = server_settings::read(&cx.db).await?.max_avatar_bytes; + let maximum = db::settings::read(cx.db).await?.max_avatar_bytes; validate_avatar_size(&self.image, maximum)?; - let user = user::set_avatar(&me.id, Some(&self.image), &mut cx.db).await?; + files::check_avatar(&self.image)?; + db::avatar::set_user(me.id, Some(&self.image), cx.db).await?; + let user = db::user::read(me.id, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -98,7 +98,8 @@ impl Handle for UpdateAvatar { impl Handle for RemoveAvatar { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { let me = me.user()?; - let user = user::set_avatar(&me.id, None, &mut cx.db).await?; + db::avatar::set_user(me.id, None, cx.db).await?; + let user = db::user::read(me.id, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -107,38 +108,38 @@ impl Handle for RemoveAvatar { impl Handle for GetAvatar { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - user::avatar(&self.avatar_id, &cx.db).await + db::avatar::read(self.avatar_id, cx.db).await } } impl Handle for ListSessions { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; + managed(&me, self.user_id, cx.db).await?; - authentication::sessions(&self.user_id, &cx.db).await + db::session::list(self.user_id, cx.db).await } } impl Handle for RevokeSession { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; + managed(&me, self.user_id, cx.db).await?; authentication::revoke( &cx.sh.services.hub, authentication::Revoke::Session { - user_id: &self.user_id, - session_id: &self.session_id, + user_id: self.user_id, + session_id: self.session_id, }, - &cx.db, + cx.db, ) .await?; - admin_log::record( - Some(&me.id), - Some(&self.user_id), + db::log::record_admin( + Some(me.id), + Some(self.user_id), None, &AdminAction::SessionsRevoked, - &cx.db, + cx.db, ) .await?; diff --git a/crates/server/src/call/voice.rs b/crates/server/src/call/voice.rs index 0b4b1f6..fa76b10 100644 --- a/crates/server/src/call/voice.rs +++ b/crates/server/src/call/voice.rs @@ -6,58 +6,57 @@ use common::{ }, error::Error, event::Event, - model::{AdminAction, CallLog, VoiceRoom}, + model::{AdminAction, CallLog, Id, VoiceRoom}, permission, share::Share, }; use crate::{ - admin_log, call::{Cx, Handle, Me}, - community, - error::ServerError, - message, + db::{self, community::Kind}, + error::{ServerError, ensure}, publish::To, request::{ - allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event, - share_ended, voice_joined, voice_muted, + allowed, departed, is_outsider, leave_user_voice, managed, message_event, share_ended, + voice_joined, voice_muted, }, - user, }; impl Handle for JoinVoice { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; let community_id = self.community_id; let rooms = &cx.sh.services.rooms; - allowed(&me, &community_id, &cx.db, permission::can_join_voice).await?; - ensure(community::kind(&community_id, &cx.db).await? != community::Kind::Notes)?; + allowed(&me, community_id, cx.db, permission::can_join_voice).await?; + let kind = db::community::kind_of(community_id, cx.db) + .await? + .ok_or(Error::NotFound)?; + ensure(kind != Kind::Notes)?; ensure( permission::is_builder(me.role) - || community::voice_enabled(&community_id, &cx.db).await?, + || db::community::voice_enabled(community_id, cx.db).await?, )?; - let muted = user::voice_muted(&me.id, &cx.db).await?; - let outsider = is_outsider(&me.id, &community_id, &cx.db).await?; - let ghost = outsider || user::is_ghost(&me.id, &cx.db).await?; - let starts_call = !ghost - && community::is_direct(&community_id, &cx.db).await? - && rooms.participants(&community_id).is_empty(); - let joined = rooms.join(cx.client, &community_id, muted, ghost)?; + let muted = db::user::voice_muted(me.id, cx.db).await?; + let outsider = is_outsider(me.id, community_id, cx.db).await?; + let ghost = outsider || db::user::is_ghost(me.id, cx.db).await?; + let starts_call = + !ghost && kind == Kind::Direct && rooms.participants(community_id).is_empty(); + let joined = rooms.join(cx.client, community_id, muted, ghost)?; let mut broadcasts = match joined.departure { - Some(departure) => departed(departure, &cx.db).await?, + Some(departure) => departed(departure, cx.db).await?, None => Vec::new(), }; if starts_call { let created = - message::create_call_log(&community_id, &me.id, CallLog::Started, &cx.db).await?; + db::message::create_call_log(community_id, me.id, CallLog::Started, cx.db).await?; broadcasts.push(message_event(&created, Event::MessageCreated)); } if !ghost && !joined.transferred { - broadcasts.extend(voice_joined(&community_id, &me.id, muted)); + broadcasts.extend(voice_joined(community_id, me.id, muted)); } cx.out.extend(broadcasts); - Ok(rooms.participants(&community_id)) + Ok(rooms.participants(community_id)) } } @@ -65,7 +64,7 @@ impl Handle for LeaveVoice { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { me.user()?; if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) { - cx.out.extend(departed(departure, &cx.db).await?); + cx.out.extend(departed(departure, cx.db).await?); } Ok(()) @@ -79,13 +78,13 @@ impl Handle for StartShare { let Some(community_id) = rooms.room_of_conn(cx.client.id) else { return Err(Error::NotFound.into()); }; - allowed(&me, &community_id, &cx.db, permission::can_share).await?; + allowed(&me, community_id, cx.db, permission::can_share).await?; ensure(!self.source.encode.is_empty())?; - ensure(!user::is_ghost(&me.id, &cx.db).await?)?; + ensure(!db::user::is_ghost(me.id, cx.db).await?)?; let event = Event::ShareStarted { - community_id: community_id.clone(), + community_id, share: Share { - user_id: me.id.clone(), + user_id: me.id, kind: self.kind, source: self.source.clone(), }, @@ -104,7 +103,7 @@ impl Handle for StopShare { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; if let Some(community_id) = cx.sh.services.rooms.stop_share(cx.client.id, self.kind) { - cx.out.push(share_ended(&community_id, &me.id, self.kind)); + cx.out.push(share_ended(community_id, me.id, self.kind)); } Ok(()) @@ -114,9 +113,9 @@ impl Handle for StopShare { impl Handle for ListShares { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; - Ok(cx.sh.services.rooms.shares(&self.community_id)) + Ok(cx.sh.services.rooms.shares(self.community_id)) } } @@ -129,7 +128,7 @@ impl Handle for WatchShare { .rooms .watch( cx.client.id, - &self.user_id, + self.user_id, self.kind, self.quality, &self.decode, @@ -148,7 +147,7 @@ impl Handle for UnwatchShare { cx.sh .services .rooms - .unwatch(cx.client.id, &self.user_id, self.kind), + .unwatch(cx.client.id, self.user_id, self.kind), ); Ok(()) @@ -162,7 +161,7 @@ impl Handle for RequestKeyframe { .sh .services .rooms - .keyframe(cx.client.id, &self.user_id, self.kind) + .keyframe(cx.client.id, self.user_id, self.kind) .ok_or(Error::NotFound)?; cx.out.push(keyframe); @@ -175,13 +174,16 @@ impl Handle for DeclineCall { let me = me.user()?; let community_id = self.community_id; let rooms = &cx.sh.services.rooms; - ensure(community::is_direct(&community_id, &cx.db).await?)?; - allowed(&me, &community_id, &cx.db, permission::can_read).await?; - let participants = rooms.participants(&community_id); + let kind = db::community::kind_of(community_id, cx.db) + .await? + .ok_or(Error::NotFound)?; + ensure(kind == Kind::Direct)?; + allowed(&me, community_id, cx.db, permission::can_read).await?; + let participants = rooms.participants(community_id); ensure(!participants.is_empty() && !participants.contains(&me.id))?; - rooms.decline(&community_id); + rooms.decline(community_id); let created = - message::create_call_log(&community_id, &me.id, CallLog::Declined, &cx.db).await?; + db::message::create_call_log(community_id, me.id, CallLog::Declined, cx.db).await?; cx.out.push(message_event(&created, Event::MessageCreated)); Ok(()) @@ -189,11 +191,11 @@ impl Handle for DeclineCall { } impl Handle for ListVoiceParticipants { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let me = me.user()?; - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; + allowed(&me, self.community_id, cx.db, permission::can_read).await?; - Ok(cx.sh.services.rooms.participants(&self.community_id)) + Ok(cx.sh.services.rooms.participants(self.community_id)) } } @@ -201,12 +203,12 @@ impl Handle for ListVoiceRooms { async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { let mut rooms = Vec::new(); for (community_id, user_ids, ghosts) in cx.sh.services.rooms.list() { - let community = community::label(&community_id, &cx.db).await?; + let community = db::community::label(community_id, cx.db).await?; let mut users = Vec::new(); let mut muted = Vec::new(); for user_id in user_ids { - let user = user::read(&user_id, &cx.db).await?; - if user::voice_muted(&user_id, &cx.db).await? { + let user = db::user::read(user_id, cx.db).await?; + if db::user::voice_muted(user_id, cx.db).await? { muted.push(user_id); } users.push(user); @@ -228,15 +230,15 @@ impl Handle for ListVoiceRooms { impl Handle for KickFromVoice { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; - let broadcasts = leave_user_voice(&cx.sh.services.rooms, &self.user_id, &cx.db).await?; + managed(&me, self.user_id, cx.db).await?; + let broadcasts = leave_user_voice(&cx.sh.services.rooms, self.user_id, cx.db).await?; if !broadcasts.is_empty() { - admin_log::record( - Some(&me.id), - Some(&self.user_id), + db::log::record_admin( + Some(me.id), + Some(self.user_id), None, &AdminAction::VoiceKicked, - &cx.db, + cx.db, ) .await?; } @@ -249,18 +251,18 @@ impl Handle for KickFromVoice { impl Handle for ServerMute { async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { let me = me.user()?; - managed(&me, &self.user_id, &cx.db).await?; - user::set_voice_muted(&self.user_id, self.muted, &cx.db).await?; - admin_log::record( - Some(&me.id), - Some(&self.user_id), + managed(&me, self.user_id, cx.db).await?; + db::user::set_voice_muted(self.user_id, self.muted, cx.db).await?; + db::log::record_admin( + Some(me.id), + Some(self.user_id), None, &AdminAction::VoiceMuted { muted: self.muted }, - &cx.db, + cx.db, ) .await?; - let community_id = cx.sh.services.rooms.set_muted(&self.user_id, self.muted); - let broadcast = voice_muted(community_id, &self.user_id, self.muted, &cx.db).await?; + let community_id = cx.sh.services.rooms.set_muted(self.user_id, self.muted); + let broadcast = voice_muted(community_id, self.user_id, self.muted, cx.db).await?; cx.out.push(broadcast); Ok(()) diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs deleted file mode 100644 index 2dfc8cb..0000000 --- a/crates/server/src/community.rs +++ /dev/null @@ -1,405 +0,0 @@ -use common::{ - error::Error as CommonError, - model::{Community, CommunityKind, User}, - string_enum, - validate::validate_community_name, -}; -use turso::{Connection, Row}; - -use crate::{database::new_id, error::ServerError, user}; - -string_enum! { - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - Kind { - Group => "group", - Direct => "direct", - Notes => "notes", - } -} - -type Raw = (String, String, Kind, Option, bool); - -fn raw_of(row: &Row) -> Result { - let text: String = row.get(2)?; - let kind = Kind::parse(&text).ok_or(CommonError::Server)?; - - Ok(( - row.get(0)?, - row.get(1)?, - kind, - row.get(3)?, - user::bool_at(row, 4)?, - )) -} - -async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!("SELECT {} FROM direct JOIN user ON user.id = CASE WHEN direct.user_a = ?2 THEN direct.user_b ELSE direct.user_a END WHERE direct.community_id = ?1", user::user_columns("user")), - (community_id, viewer_id), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - user::from_row(&row) -} - -async fn outsider_name( - community_id: &str, - viewer_id: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT a.username, b.username FROM direct JOIN user a ON a.id = direct.user_a JOIN user b ON b.id = direct.user_b WHERE direct.community_id = ?1 AND direct.user_a != ?2 AND direct.user_b != ?2", - (community_id, viewer_id), - ) - .await?; - let Some(row) = rows.next().await? else { - return Ok(None); - }; - let first: String = row.get(0)?; - let second: String = row.get(1)?; - - Ok(Some(format!("{first} & {second}"))) -} - -async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result { - let (id, mut name, kind, avatar_id, voice_enabled) = raw; - let kind = match kind { - Kind::Group => CommunityKind::Group, - Kind::Direct => { - if let Some(outsider) = outsider_name(&id, viewer_id, conn).await? { - name = outsider; - } - CommunityKind::Direct { - peer: peer(&id, viewer_id, conn).await?, - } - } - Kind::Notes => CommunityKind::Notes, - }; - - Ok(Community { - id, - name, - kind, - avatar_id, - voice_enabled, - }) -} - -pub async fn create(name: &str, conn: &Connection) -> Result { - validate_community_name(name)?; - - let id = new_id(); - conn.execute( - "INSERT INTO community (id, name, kind) VALUES (?1, ?2, ?3)", - (id.as_str(), name, Kind::Group.as_str()), - ) - .await?; - - Ok(Community { - id, - name: name.to_string(), - kind: CommunityKind::Group, - avatar_id: None, - voice_enabled: true, - }) -} - -pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result { - let id = new_id(); - conn.execute( - "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", - (id.as_str(), kind.as_str()), - ) - .await?; - - Ok(id) -} - -pub async fn read( - community_id: &str, - viewer_id: &str, - conn: &Connection, -) -> Result { - let raw = { - let mut rows = conn - .query( - "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE id = ?1", - (community_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - raw_of(&row)? - }; - - build(raw, viewer_id, conn).await -} - -pub async fn communities_of( - user_id: &str, - conn: &Connection, -) -> Result, ServerError> { - let raws = { - let mut rows = conn - .query( - "SELECT community.id, community.name, community.kind, community.avatar_id, community.voice_enabled FROM community JOIN user_community ON user_community.community_id = community.id WHERE user_community.user_id = ?1 ORDER BY community.id", - (user_id,), - ) - .await?; - - let mut raws = Vec::new(); - while let Some(row) = rows.next().await? { - raws.push(raw_of(&row)?); - } - - raws - }; - - let mut communities = Vec::new(); - for raw in raws { - communities.push(build(raw, user_id, conn).await?); - } - - Ok(communities) -} - -pub async fn groups(conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE", - (Kind::Group.as_str(),), - ) - .await?; - - let mut communities = Vec::new(); - while let Some(row) = rows.next().await? { - let (id, name, _, avatar_id, voice_enabled) = raw_of(&row)?; - communities.push(Community { - id, - name, - kind: CommunityKind::Group, - avatar_id, - voice_enabled, - }); - } - - Ok(communities) -} - -pub async fn update( - community_id: &str, - name: &str, - viewer_id: &str, - conn: &Connection, -) -> Result { - validate_community_name(name)?; - - conn.execute( - "UPDATE community SET name = ?2 WHERE id = ?1", - (community_id, name), - ) - .await?; - - read(community_id, viewer_id, conn).await -} - -pub async fn set_avatar( - community_id: &str, - image: Option<&[u8]>, - viewer_id: &str, - conn: &mut Connection, -) -> Result { - if let Some(bytes) = image { - user::check_avatar(bytes)?; - } - let avatar_id = image.map(|_| new_id()); - - let tx = conn.transaction().await?; - tx.execute( - "DELETE FROM community_avatar WHERE community_id = ?1", - (community_id,), - ) - .await?; - if let (Some(avatar_id), Some(bytes)) = (&avatar_id, image) { - tx.execute( - "INSERT INTO community_avatar (id, community_id, data) VALUES (?1, ?2, ?3)", - (avatar_id.as_str(), community_id, bytes), - ) - .await?; - } - tx.execute( - "UPDATE community SET avatar_id = ?2 WHERE id = ?1", - (community_id, avatar_id.as_deref()), - ) - .await?; - let community = read(community_id, viewer_id, &tx).await?; - tx.commit().await?; - - Ok(community) -} - -pub async fn delete( - community_id: &str, - viewer_id: &str, - conn: &Connection, -) -> Result { - let deleted = read(community_id, viewer_id, conn).await?; - conn.execute("DELETE FROM community WHERE id = ?1", (community_id,)) - .await?; - - Ok(deleted) -} - -pub async fn kind(community_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query("SELECT kind FROM community WHERE id = ?1", (community_id,)) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let text: String = row.get(0)?; - - Ok(Kind::parse(&text).ok_or(CommonError::Server)?) -} - -pub async fn is_direct(community_id: &str, conn: &Connection) -> Result { - Ok(kind(community_id, conn).await? == Kind::Direct) -} - -pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result { - Ok(kind(community_id, conn).await? != Kind::Group) -} - -pub async fn set_voice_enabled( - community_id: &str, - enabled: bool, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", - (community_id, i64::from(enabled)), - ) - .await?; - - Ok(()) -} - -pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - "SELECT voice_enabled FROM community WHERE id = ?1", - (community_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - user::bool_at(&row, 0) -} - -pub async fn label(community_id: &str, conn: &Connection) -> Result { - let prefix = match kind(community_id, conn).await? { - Kind::Group => { - let mut rows = conn - .query("SELECT name FROM community WHERE id = ?1", (community_id,)) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - return Ok(row.get(0)?); - } - Kind::Direct => "DM", - Kind::Notes => "Notes", - }; - - let mut rows = conn - .query( - "SELECT user.username FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.username COLLATE NOCASE", - (community_id,), - ) - .await?; - let mut usernames = Vec::new(); - while let Some(row) = rows.next().await? { - usernames.push(row.get::(0)?); - } - - Ok(format!("{prefix} · {}", usernames.join(" & "))) -} - -#[cfg(test)] -mod tests { - use common::error::Error as CommonError; - - use crate::{community, database, error::ServerError, test, user}; - - #[tokio::test] - async fn create() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let community = community::create("Tahinli", &conn).await.unwrap(); - - assert_eq!("Tahinli", community.name); - } - - #[tokio::test] - async fn read() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); - - let created_community = community::create("Tahinli", &conn).await.unwrap(); - let searched_community = community::read(&created_community.id, &viewer.id, &conn) - .await - .unwrap(); - - assert_eq!(created_community, searched_community); - } - - #[tokio::test] - async fn update() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); - - let created_community = community::create("Tahinli", &conn).await.unwrap(); - let updated_community = - community::update(&created_community.id, "Not Tahinli", &viewer.id, &conn) - .await - .unwrap(); - let searched_community = community::read(&created_community.id, &viewer.id, &conn) - .await - .unwrap(); - - assert_eq!(created_community.id, searched_community.id); - assert_eq!(updated_community, searched_community); - assert_eq!("Not Tahinli", searched_community.name); - } - - #[tokio::test] - async fn update_on_missing_community() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); - - let updated_community = - community::update("missing", "Not Tahinli", &viewer.id, &conn).await; - - assert!(matches!( - updated_community, - Err(ServerError::Wire(CommonError::NotFound)) - )); - } - - #[tokio::test] - async fn delete() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); - - let created_community = community::create("Tahinli", &conn).await.unwrap(); - let deleted_community = community::delete(&created_community.id, &viewer.id, &conn) - .await - .unwrap(); - - assert_eq!(created_community, deleted_community); - } -} diff --git a/crates/server/src/database.rs b/crates/server/src/database.rs deleted file mode 100644 index 8a2b0d9..0000000 --- a/crates/server/src/database.rs +++ /dev/null @@ -1,375 +0,0 @@ -use std::time::Duration; - -use common::error::Error as CommonError; -use turso::Connection; - -use crate::error::ServerError; - -pub type DB = turso::Database; - -const BUSY_TIMEOUT: Duration = Duration::from_secs(5); - -const MIGRATIONS: &[&str] = &[ - " - CREATE TABLE user ( - id TEXT PRIMARY KEY, - username TEXT NOT NULL UNIQUE, - password_hash TEXT NOT NULL, - role TEXT NOT NULL DEFAULT 'user', - status TEXT NOT NULL DEFAULT '', - avatar_id TEXT - ); - - CREATE TABLE avatar ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - data BLOB NOT NULL - ); - - CREATE TABLE session ( - token TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE - ); - - CREATE TABLE community ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL - ); - - CREATE TABLE message ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - body TEXT NOT NULL - ); - - CREATE INDEX message_community_id_id ON message (community_id, id); - - CREATE TABLE user_community ( - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - rank TEXT NOT NULL DEFAULT 'member', - PRIMARY KEY (user_id, community_id) - ); - - CREATE TABLE ban ( - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - PRIMARY KEY (user_id, community_id) - ); - - CREATE TABLE attachment ( - id TEXT PRIMARY KEY, - uploader_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - message_id TEXT REFERENCES message (id) ON DELETE CASCADE, - name TEXT NOT NULL, - size INTEGER NOT NULL, - kind TEXT NOT NULL, - width INTEGER, - height INTEGER - ); - - CREATE INDEX attachment_message_id ON attachment (message_id); -", - " - ALTER TABLE community ADD COLUMN kind TEXT NOT NULL DEFAULT 'group'; - ALTER TABLE message ADD COLUMN reply_to TEXT; - ALTER TABLE message ADD COLUMN edited INTEGER NOT NULL DEFAULT 0; - ALTER TABLE attachment ADD COLUMN snippet_position INTEGER; - ALTER TABLE ban ADD COLUMN reason TEXT; - ALTER TABLE community ADD COLUMN avatar_id TEXT; - - CREATE TABLE community_avatar ( - id TEXT PRIMARY KEY, - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - data BLOB NOT NULL - ); - - CREATE TABLE direct ( - user_a TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - user_b TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE, - PRIMARY KEY (user_a, user_b) - ); - - CREATE TABLE snippet ( - message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, - origin TEXT - ); - - CREATE TABLE snippet_message ( - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, - position INTEGER NOT NULL, - original_id TEXT NOT NULL, - user_id TEXT NOT NULL, - username TEXT NOT NULL, - avatar_id TEXT, - body TEXT NOT NULL, - PRIMARY KEY (message_id, position) - ); - - CREATE TABLE friend_request ( - from_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - to_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - PRIMARY KEY (from_id, to_id) - ); - - CREATE TABLE friend ( - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - friend_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - PRIMARY KEY (user_id, friend_id) - ); - - CREATE TABLE invitation ( - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - inviter_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - PRIMARY KEY (community_id, user_id) - ); -", - " - CREATE TABLE community_log ( - id TEXT PRIMARY KEY, - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, - actor_id TEXT REFERENCES user (id) ON DELETE SET NULL, - target_id TEXT REFERENCES user (id) ON DELETE SET NULL, - action TEXT NOT NULL, - detail TEXT - ); - - CREATE INDEX community_log_community_id_id ON community_log (community_id, id); -", - " - UPDATE user SET role = 'builder' WHERE role = 'staff'; - UPDATE user_community SET rank = 'builder' WHERE rank = 'staff'; -", - " - CREATE TABLE admin_log ( - id TEXT PRIMARY KEY, - actor_id TEXT REFERENCES user (id) ON DELETE SET NULL, - target_id TEXT REFERENCES user (id) ON DELETE SET NULL, - community TEXT, - action TEXT NOT NULL, - detail TEXT - ); -", - " - ALTER TABLE user ADD COLUMN suspended INTEGER NOT NULL DEFAULT 0; -", - " - CREATE TABLE server_settings ( - id INTEGER PRIMARY KEY CHECK (id = 1), - name TEXT NOT NULL, - registration_open INTEGER NOT NULL, - max_attachment_bytes INTEGER NOT NULL - ); - - INSERT INTO server_settings (id, name, registration_open, max_attachment_bytes) - VALUES (1, 'yumush', 1, 26214400); -", - " - ALTER TABLE user ADD COLUMN last_seen INTEGER; - ALTER TABLE session ADD COLUMN id TEXT; - ALTER TABLE session ADD COLUMN device TEXT NOT NULL DEFAULT ''; - ALTER TABLE session ADD COLUMN last_seen INTEGER; - UPDATE session SET id = lower(hex(randomblob(16))) WHERE id IS NULL; -", - " - ALTER TABLE user ADD COLUMN suspended_until INTEGER; - ALTER TABLE user ADD COLUMN last_ip TEXT; - - CREATE TABLE server_ban ( - id TEXT PRIMARY KEY, - kind TEXT NOT NULL, - value TEXT NOT NULL, - reason TEXT, - created_by TEXT REFERENCES user (id) ON DELETE SET NULL - ); -", - " - CREATE TABLE invite_code ( - code TEXT PRIMARY KEY, - uses_left INTEGER NOT NULL, - expires_at INTEGER, - created_by TEXT REFERENCES user (id) ON DELETE SET NULL - ); -", - " - ALTER TABLE server_settings ADD COLUMN maintenance INTEGER NOT NULL DEFAULT 0; -", - " - CREATE TABLE report ( - id TEXT PRIMARY KEY, - reporter_id TEXT REFERENCES user (id) ON DELETE SET NULL, - target_id TEXT REFERENCES user (id) ON DELETE SET NULL, - message_id TEXT, - community_id TEXT, - body TEXT, - reason TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'open', - handled_by TEXT REFERENCES user (id) ON DELETE SET NULL - ); -", - " - ALTER TABLE user ADD COLUMN voice_muted INTEGER NOT NULL DEFAULT 0; -", - " - ALTER TABLE community ADD COLUMN voice_enabled INTEGER NOT NULL DEFAULT 1; -", - " - ALTER TABLE server_settings ADD COLUMN user_quota_bytes INTEGER NOT NULL DEFAULT 0; - ALTER TABLE server_settings ADD COLUMN community_quota_bytes INTEGER NOT NULL DEFAULT 0; - ALTER TABLE server_settings ADD COLUMN message_retention_days INTEGER NOT NULL DEFAULT 0; - ALTER TABLE server_settings ADD COLUMN attachment_retention_days INTEGER NOT NULL DEFAULT 0; -", - " - ALTER TABLE server_settings ADD COLUMN announcement TEXT NOT NULL DEFAULT ''; - ALTER TABLE server_settings ADD COLUMN max_communities_per_user INTEGER NOT NULL DEFAULT 0; - ALTER TABLE server_settings ADD COLUMN max_message_length INTEGER NOT NULL DEFAULT 1024; - ALTER TABLE server_settings ADD COLUMN max_avatar_bytes INTEGER NOT NULL DEFAULT 32768; - ALTER TABLE server_settings ADD COLUMN messages_per_minute INTEGER NOT NULL DEFAULT 30; - ALTER TABLE server_settings ADD COLUMN logins_per_minute INTEGER NOT NULL DEFAULT 10; -", - " - CREATE TABLE daily_active ( - day INTEGER NOT NULL, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - PRIMARY KEY (day, user_id) - ); -", - " - ALTER TABLE user ADD COLUMN ghost INTEGER NOT NULL DEFAULT 0; -", - " - ALTER TABLE user ADD COLUMN presence TEXT NOT NULL DEFAULT 'online'; -", - " - ALTER TABLE message ADD COLUMN call TEXT; - ALTER TABLE message ADD COLUMN call_seconds INTEGER NOT NULL DEFAULT 0; -", - " - CREATE TABLE reaction ( - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - emoji TEXT NOT NULL, - PRIMARY KEY (message_id, user_id, emoji) - ); -", - " - ALTER TABLE message ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0; -", - " - ALTER TABLE user_community ADD COLUMN last_read TEXT; - UPDATE user_community SET last_read = (SELECT MAX(id) FROM message WHERE message.community_id = user_community.community_id); -", - " - CREATE TABLE notes ( - user_id TEXT PRIMARY KEY REFERENCES user (id) ON DELETE CASCADE, - community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE - ); -", - " - CREATE TABLE poll ( - message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, - question TEXT NOT NULL, - multiple INTEGER NOT NULL, - closed INTEGER NOT NULL DEFAULT 0 - ); - CREATE TABLE poll_option ( - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, - position INTEGER NOT NULL, - text TEXT NOT NULL, - PRIMARY KEY (message_id, position) - ); - CREATE TABLE poll_vote ( - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, - position INTEGER NOT NULL, - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, - PRIMARY KEY (message_id, position, user_id) - ); -", - "ALTER TABLE snippet_message ADD COLUMN poll BLOB;", -]; - -pub async fn open(path: &str) -> Result { - let db = turso::Builder::new_local(path).build().await?; - migrate(&db).await?; - - Ok(db) -} - -pub async fn connect(db: &DB) -> Result { - let conn = db.connect()?; - conn.busy_timeout(BUSY_TIMEOUT)?; - conn.execute_batch("PRAGMA foreign_keys = ON;").await?; - - Ok(conn) -} - -pub async fn scalar_i64( - conn: &Connection, - sql: &str, - params: impl turso::IntoParams, -) -> Result { - let mut rows = conn.query(sql, params).await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - - Ok(row.get(0)?) -} - -pub async fn exists( - conn: &Connection, - sql: &str, - params: impl turso::IntoParams, -) -> Result { - Ok(scalar_i64(conn, sql, params).await? != 0) -} - -pub async fn ids( - conn: &Connection, - sql: &str, - params: impl turso::IntoParams, -) -> Result, ServerError> { - let mut rows = conn.query(sql, params).await?; - - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get(0)?); - } - - Ok(ids) -} - -pub fn expect_one(affected: u64) -> Result<(), ServerError> { - if affected != 1 { - return Err(CommonError::NotFound.into()); - } - - Ok(()) -} - -async fn migrate(db: &DB) -> Result<(), ServerError> { - let mut conn = connect(db).await?; - let applied = user_version(&conn).await?; - - for (index, migration) in MIGRATIONS.iter().enumerate().skip(applied) { - let tx = conn.transaction().await?; - tx.execute_batch(migration).await?; - tx.pragma_update("user_version", index + 1).await?; - tx.commit().await?; - } - - Ok(()) -} - -async fn user_version(conn: &Connection) -> Result { - Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize) -} - -pub fn new_id() -> String { - uuid::Uuid::now_v7().to_string() -} diff --git a/crates/server/src/datagram.rs b/crates/server/src/datagram.rs index c996734..b8f1ebd 100644 --- a/crates/server/src/datagram.rs +++ b/crates/server/src/datagram.rs @@ -1,12 +1,18 @@ use std::sync::Arc; use quinn::Connection; +use tracing::warn; -use crate::{hub::Client, network::Shared, publish::publish}; +use crate::{hub::Client, network::Shared, publish}; pub(crate) async fn relay_datagrams(connection: Connection, client: Arc, shared: Shared) { while let Ok(bytes) = connection.read_datagram().await { let broadcasts = shared.services.rooms.relay(&client, &bytes); - publish(&shared, broadcasts).await; + if broadcasts.is_empty() { + continue; + } + if let Err(error) = publish::job(&shared, async |_| Ok(broadcasts)).await { + warn!("relay: {error}"); + } } } diff --git a/crates/server/src/db/attachment.rs b/crates/server/src/db/attachment.rs new file mode 100644 index 0000000..902de2a --- /dev/null +++ b/crates/server/src/db/attachment.rs @@ -0,0 +1,268 @@ +use std::collections::HashSet; + +use common::{ + constant::MAXIMUM_ATTACHMENTS_PER_MESSAGE, + error::Error, + model::{Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, Id, Usage}, + time::now_ms, +}; + +use super::{Connection, Reader, community, one, run, user}; +use crate::error::{ServerError, ensure_with}; + +const LIST_LIMIT: u32 = 200; +const USAGE_LIMIT: u32 = 50; + +pub const COLUMNS: &str = "attachment.id, attachment.name, attachment.size, attachment.kind, attachment.width, attachment.height, attachment.created_at"; + +pub struct Stored { + pub attachment: Attachment, + pub file: String, + pub uploader_id: Id, + pub community_id: Id, + pub message_id: Option, +} + +pub fn row(r: &mut Reader) -> Result { + Ok(Attachment { + id: r.get()?, + name: r.get()?, + size: r.get()?, + kind: r.named()?, + width: r.get()?, + height: r.get()?, + created_at: r.get()?, + }) +} + +pub async fn of_message( + message_id: Id, + snippet_position: Option, + db: &Connection, +) -> Result, ServerError> { + super::all( + db, + &format!( + "SELECT {COLUMNS} FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id" + ), + (message_id, snippet_position), + row, + ) + .await +} + +pub async fn bind( + message_id: Id, + user_id: Id, + community_id: Id, + attachment_ids: &[Id], + db: &Connection, +) -> Result<(), ServerError> { + ensure_with( + attachment_ids.len() <= MAXIMUM_ATTACHMENTS_PER_MESSAGE, + Error::NotFound, + )?; + for attachment_id in attachment_ids { + let bound = run( + db, + "UPDATE attachment SET message_id = ?1 WHERE id = ?2 AND uploader_id = ?3 AND community_id = ?4 AND message_id IS NULL", + (message_id, *attachment_id, user_id, community_id), + ) + .await?; + ensure_with(bound == 1, Error::NotFound)?; + } + + Ok(()) +} + +pub async fn copy_row( + id: Id, + message_id: Id, + user_id: Id, + community_id: Id, + snippet_position: Option, + db: &Connection, +) -> Result<(), ServerError> { + let copied = run( + db, + "INSERT INTO attachment (uploader_id, community_id, message_id, snippet_position, created_at, file, name, size, kind, width, height) SELECT ?2, ?3, ?4, ?5, ?6, file, name, size, kind, width, height FROM attachment WHERE id = ?1", + (id, user_id, community_id, message_id, snippet_position, now_ms()), + ) + .await?; + ensure_with(copied == 1, Error::NotFound) +} + +#[allow(clippy::too_many_arguments)] +pub async fn insert( + uploader_id: Id, + community_id: Id, + file: &str, + name: &str, + size: u64, + kind: AttachmentKind, + width: Option, + height: Option, + db: &Connection, +) -> Result { + let id: Id = one( + db, + "INSERT INTO attachment (uploader_id, community_id, created_at, file, name, size, kind, width, height) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) RETURNING id", + ( + uploader_id, + community_id, + now_ms(), + file, + name, + size, + kind.as_str(), + width, + height, + ), + |r| r.get(), + ) + .await?; + + Ok(read(id, db).await?.attachment) +} + +pub async fn read(id: Id, db: &Connection) -> Result { + one( + db, + &format!( + "SELECT {COLUMNS}, attachment.file, attachment.uploader_id, attachment.community_id, attachment.message_id FROM attachment WHERE attachment.id = ?1" + ), + (id,), + |r| { + Ok(Stored { + attachment: row(r)?, + file: r.get()?, + uploader_id: r.get()?, + community_id: r.get()?, + message_id: r.get()?, + }) + }, + ) + .await +} + +pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { + run(db, "DELETE FROM attachment WHERE id = ?1", (id,)).await?; + + Ok(()) +} + +pub async fn delete_uploads(user_id: Id, db: &Connection) -> Result<(), ServerError> { + run( + db, + "DELETE FROM attachment WHERE uploader_id = ?1", + (user_id,), + ) + .await?; + + Ok(()) +} + +pub async fn delete_stale_unbound(cutoff: u64, db: &Connection) -> Result<(), ServerError> { + run( + db, + "DELETE FROM attachment WHERE message_id IS NULL AND created_at < ?1", + (cutoff,), + ) + .await?; + + Ok(()) +} + +pub async fn delete_before(cutoff: u64, limit: u32, db: &Connection) -> Result { + run( + db, + "DELETE FROM attachment WHERE id IN (SELECT id FROM attachment WHERE created_at < ?1 ORDER BY id LIMIT ?2)", + (cutoff, limit), + ) + .await +} + +pub async fn files(db: &Connection) -> Result, ServerError> { + let files = super::all(db, "SELECT file FROM attachment", (), |r| r.get()).await?; + + Ok(files.into_iter().collect()) +} + +pub async fn quota( + user_id: Id, + community_id: Id, + db: &Connection, +) -> Result<(u64, u64), ServerError> { + one( + db, + "SELECT (SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1), (SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?2)", + (user_id, community_id), + |r| Ok((r.get()?, r.get()?)), + ) + .await +} + +pub async fn all( + user_id: Option, + community_id: Option, + db: &Connection, +) -> Result, ServerError> { + let rows = super::all( + db, + &format!( + "SELECT {COLUMNS}, attachment.uploader_id, attachment.community_id FROM attachment WHERE (?1 IS NULL OR attachment.uploader_id = ?1) AND (?2 IS NULL OR attachment.community_id = ?2) ORDER BY attachment.size DESC LIMIT ?3" + ), + (user_id, community_id, LIST_LIMIT), + |r| Ok((row(r)?, r.get::()?, r.get::()?)), + ) + .await?; + + let mut infos = Vec::new(); + for (attachment, uploader_id, community_id) in rows { + infos.push(AttachmentInfo { + attachment, + uploader: Some(user::read(uploader_id, db).await?), + community: community::label(community_id, db).await?, + }); + } + + Ok(infos) +} + +pub async fn usage(db: &Connection) -> Result<(Vec, Vec), ServerError> { + let by_user: Vec<(Id, u64, u64)> = super::all( + db, + "SELECT uploader_id, SUM(size), COUNT(*) FROM attachment GROUP BY uploader_id ORDER BY SUM(size) DESC LIMIT ?1", + (USAGE_LIMIT,), + |r| Ok((r.get()?, r.get()?, r.get()?)), + ) + .await?; + let by_community: Vec<(Id, u64, u64)> = super::all( + db, + "SELECT community_id, SUM(size), COUNT(*) FROM attachment GROUP BY community_id ORDER BY SUM(size) DESC LIMIT ?1", + (USAGE_LIMIT,), + |r| Ok((r.get()?, r.get()?, r.get()?)), + ) + .await?; + + let mut users = Vec::new(); + for (user_id, bytes, count) in by_user { + users.push(Usage { + user: user::read(user_id, db).await?, + bytes, + count, + }); + } + + let mut communities = Vec::new(); + for (community_id, bytes, count) in by_community { + communities.push(CommunityUsage { + community: community::label(community_id, db).await?, + community_id, + bytes, + count, + }); + } + + Ok((users, communities)) +} diff --git a/crates/server/src/db/avatar.rs b/crates/server/src/db/avatar.rs new file mode 100644 index 0000000..2889e86 --- /dev/null +++ b/crates/server/src/db/avatar.rs @@ -0,0 +1,52 @@ +use common::model::Id; + +use super::{Connection, one, run}; +use crate::error::ServerError; + +pub async fn read(id: Id, db: &Connection) -> Result, ServerError> { + one(db, "SELECT data FROM avatar WHERE id = ?1", (id,), |r| { + r.get() + }) + .await +} + +pub async fn set_user( + user_id: Id, + avatar: Option<&[u8]>, + db: &Connection, +) -> Result<(), ServerError> { + run(db, "DELETE FROM avatar WHERE user_id = ?1", (user_id,)).await?; + if let Some(bytes) = avatar { + run( + db, + "INSERT INTO avatar (user_id, data) VALUES (?1, ?2)", + (user_id, bytes), + ) + .await?; + } + + Ok(()) +} + +pub async fn set_community( + community_id: Id, + avatar: Option<&[u8]>, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "DELETE FROM avatar WHERE community_id = ?1", + (community_id,), + ) + .await?; + if let Some(bytes) = avatar { + run( + db, + "INSERT INTO avatar (community_id, data) VALUES (?1, ?2)", + (community_id, bytes), + ) + .await?; + } + + Ok(()) +} diff --git a/crates/server/src/db/community.rs b/crates/server/src/db/community.rs new file mode 100644 index 0000000..102e034 --- /dev/null +++ b/crates/server/src/db/community.rs @@ -0,0 +1,182 @@ +use common::{ + error::Error, + model::{Community, CommunityKind, Id}, + string_enum, +}; + +use super::{Connection, Reader, all, maybe, one, run, user}; +use crate::error::{ServerError, ensure_with}; + +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + Kind { + Group => "group", + Direct => "direct", + Notes => "notes", + } +} + +const READ: &str = "SELECT c.id, CASE WHEN d.user_a != d.user_b AND ?2 NOT IN (d.user_a, d.user_b) THEN a.username || ' & ' || b.username ELSE c.name END, c.kind, (SELECT avatar.id FROM avatar WHERE avatar.community_id = c.id), c.voice_enabled, CASE WHEN d.user_a = ?2 THEN d.user_b ELSE d.user_a END FROM community c LEFT JOIN direct d ON d.community_id = c.id LEFT JOIN user a ON a.id = d.user_a LEFT JOIN user b ON b.id = d.user_b WHERE c.id = ?1"; + +struct Raw { + id: Id, + name: String, + kind: Kind, + avatar_id: Option, + voice_enabled: bool, + peer: Option, +} + +fn raw(r: &mut Reader) -> Result { + Ok(Raw { + id: r.get()?, + name: r.get()?, + kind: r.named()?, + avatar_id: r.get()?, + voice_enabled: r.get()?, + peer: r.get()?, + }) +} + +pub async fn read(id: Id, viewer: Id, db: &Connection) -> Result { + let raw = one(db, READ, (id, viewer), raw).await?; + let kind = match raw.kind { + Kind::Group => CommunityKind::Group, + Kind::Direct => CommunityKind::Direct { + peer: user::read(raw.peer.ok_or(Error::NotFound)?, db).await?, + }, + Kind::Notes => CommunityKind::Notes, + }; + + Ok(Community { + id: raw.id, + name: raw.name, + kind, + avatar_id: raw.avatar_id, + voice_enabled: raw.voice_enabled, + }) +} + +pub async fn create(kind: Kind, name: &str, db: &Connection) -> Result { + one( + db, + "INSERT INTO community (kind, name, voice_enabled) VALUES (?1, ?2, ?3) RETURNING id", + (kind.as_str(), name, true), + |r| r.get(), + ) + .await +} + +pub async fn communities_of(user_id: Id, db: &Connection) -> Result, ServerError> { + let ids: Vec = all( + db, + "SELECT community_id FROM member WHERE user_id = ?1 ORDER BY community_id", + (user_id,), + |r| r.get(), + ) + .await?; + + let mut communities = Vec::new(); + for id in ids { + communities.push(read(id, user_id, db).await?); + } + + Ok(communities) +} + +pub async fn groups(db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT id, name, (SELECT avatar.id FROM avatar WHERE avatar.community_id = community.id), voice_enabled FROM community WHERE kind = ?1 ORDER BY name", + (Kind::Group.as_str(),), + |r| { + Ok(Community { + id: r.get()?, + name: r.get()?, + kind: CommunityKind::Group, + avatar_id: r.get()?, + voice_enabled: r.get()?, + }) + }, + ) + .await +} + +pub async fn update( + community_id: Id, + name: &str, + viewer_id: Id, + db: &Connection, +) -> Result { + let changed = run( + db, + "UPDATE community SET name = ?2 WHERE id = ?1", + (community_id, name), + ) + .await?; + ensure_with(changed == 1, Error::NotFound)?; + + read(community_id, viewer_id, db).await +} + +pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { + ensure_with( + run(db, "DELETE FROM community WHERE id = ?1", (id,)).await? == 1, + Error::NotFound, + ) +} + +pub async fn kind_of(id: Id, db: &Connection) -> Result, ServerError> { + maybe(db, "SELECT kind FROM community WHERE id = ?1", (id,), |r| { + r.named() + }) + .await +} + +pub async fn set_voice_enabled( + community_id: Id, + enabled: bool, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", + (community_id, enabled), + ) + .await?; + + Ok(()) +} + +pub async fn voice_enabled(community_id: Id, db: &Connection) -> Result { + one( + db, + "SELECT voice_enabled FROM community WHERE id = ?1", + (community_id,), + |r| r.get(), + ) + .await +} + +pub async fn label(id: Id, db: &Connection) -> Result { + let prefix = match kind_of(id, db).await?.ok_or(Error::NotFound)? { + Kind::Group => { + return one(db, "SELECT name FROM community WHERE id = ?1", (id,), |r| { + r.get() + }) + .await; + } + Kind::Direct => "DM", + Kind::Notes => "Notes", + }; + + let usernames: Vec = all( + db, + "SELECT user.username FROM user JOIN member ON member.user_id = user.id WHERE member.community_id = ?1 ORDER BY user.username", + (id,), + |r| r.get(), + ) + .await?; + + Ok(format!("{prefix} · {}", usernames.join(" & "))) +} diff --git a/crates/server/src/db/direct.rs b/crates/server/src/db/direct.rs new file mode 100644 index 0000000..49129ec --- /dev/null +++ b/crates/server/src/db/direct.rs @@ -0,0 +1,47 @@ +use common::model::{Community, Id, Rank}; + +use super::{Connection, community, maybe, member, run}; +use crate::error::ServerError; + +pub enum Opening { + Created(Community), + Existing(Community), +} + +pub async fn open(me: Id, other: Id, db: &Connection) -> Result { + let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; + + let existing: Option = maybe( + db, + "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", + (user_a, user_b), + |r| r.get(), + ) + .await?; + if let Some(community_id) = existing { + return Ok(Opening::Existing( + community::read(community_id, me, db).await?, + )); + } + + let community_id = if me == other { + let community_id = community::create(community::Kind::Notes, "", db).await?; + member::join(me, community_id, Rank::Owner, db).await?; + community_id + } else { + let community_id = community::create(community::Kind::Direct, "", db).await?; + member::join(me, community_id, Rank::Member, db).await?; + member::join(other, community_id, Rank::Member, db).await?; + community_id + }; + run( + db, + "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)", + (user_a, user_b, community_id), + ) + .await?; + + Ok(Opening::Created( + community::read(community_id, me, db).await?, + )) +} diff --git a/crates/server/src/db/friend.rs b/crates/server/src/db/friend.rs new file mode 100644 index 0000000..64e761e --- /dev/null +++ b/crates/server/src/db/friend.rs @@ -0,0 +1,104 @@ +use common::{ + error::Error, + model::{Friends, Id, User}, + string_enum, +}; + +use super::{Connection, all, maybe, run, user}; +use crate::error::{ServerError, ensure_with}; + +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + FriendState { + Requested => "requested", + Accepted => "accepted", + } +} + +async fn users( + sql: &str, + state: FriendState, + id: Id, + db: &Connection, +) -> Result, ServerError> { + all(db, sql, (id, state.as_str()), user::row).await +} + +pub async fn state(user_id: Id, db: &Connection) -> Result { + let columns = user::COLUMNS; + + Ok(Friends { + friends: users( + &format!("SELECT {columns} FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 AND friend.state = ?2 ORDER BY user.id"), + FriendState::Accepted, + user_id, + db, + ) + .await?, + incoming: users( + &format!("SELECT {columns} FROM user JOIN friend ON friend.user_id = user.id WHERE friend.friend_id = ?1 AND friend.state = ?2 ORDER BY user.id"), + FriendState::Requested, + user_id, + db, + ) + .await?, + outgoing: users( + &format!("SELECT {columns} FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 AND friend.state = ?2 ORDER BY user.id"), + FriendState::Requested, + user_id, + db, + ) + .await?, + }) +} + +pub async fn pair(me: Id, other: Id, db: &Connection) -> Result, ServerError> { + maybe( + db, + "SELECT state FROM friend WHERE user_id = ?1 AND friend_id = ?2", + (me, other), + |r| r.named(), + ) + .await +} + +pub async fn request(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { + run( + db, + "INSERT INTO friend (user_id, friend_id, state) VALUES (?1, ?2, ?3)", + (me, other, FriendState::Requested.as_str()), + ) + .await?; + + Ok(()) +} + +pub async fn accept(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { + let accepted = FriendState::Accepted.as_str(); + let updated = run( + db, + "UPDATE friend SET state = ?3 WHERE user_id = ?1 AND friend_id = ?2 AND state = ?4", + (other, me, accepted, FriendState::Requested.as_str()), + ) + .await?; + ensure_with(updated == 1, Error::NotFound)?; + run( + db, + "INSERT OR REPLACE INTO friend (user_id, friend_id, state) VALUES (?1, ?2, ?3)", + (me, other, accepted), + ) + .await?; + + Ok(()) +} + +pub async fn remove(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { + run( + db, + "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)", + (me, other), + ) + .await?; + + Ok(()) +} diff --git a/crates/server/src/db/invitation.rs b/crates/server/src/db/invitation.rs new file mode 100644 index 0000000..3949ff0 --- /dev/null +++ b/crates/server/src/db/invitation.rs @@ -0,0 +1,63 @@ +use common::{ + error::Error, + model::{Id, Invitation}, +}; + +use super::{Connection, all, community, one, run, user}; +use crate::error::{ServerError, ensure_with}; + +pub async fn of(user_id: Id, db: &Connection) -> Result, ServerError> { + let pairs: Vec<(Id, Id)> = all( + db, + "SELECT community_id, inviter_id FROM invitation WHERE user_id = ?1 ORDER BY community_id", + (user_id,), + |r| Ok((r.get()?, r.get()?)), + ) + .await?; + + let mut invitations = Vec::new(); + for (community_id, inviter_id) in pairs { + invitations.push(Invitation { + community: community::read(community_id, user_id, db).await?, + inviter: user::read(inviter_id, db).await?, + }); + } + + Ok(invitations) +} + +pub async fn exists(community_id: Id, user_id: Id, db: &Connection) -> Result { + one( + db, + "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", + (community_id, user_id), + |r| r.get(), + ) + .await +} + +pub async fn insert( + community_id: Id, + user_id: Id, + inviter_id: Id, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", + (community_id, user_id, inviter_id), + ) + .await?; + + Ok(()) +} + +pub async fn take(community_id: Id, user_id: Id, db: &Connection) -> Result<(), ServerError> { + let deleted = run( + db, + "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2", + (community_id, user_id), + ) + .await?; + ensure_with(deleted == 1, Error::NotFound) +} diff --git a/crates/server/src/db/log.rs b/crates/server/src/db/log.rs new file mode 100644 index 0000000..55ad1c7 --- /dev/null +++ b/crates/server/src/db/log.rs @@ -0,0 +1,134 @@ +use common::{ + constant::LOG_PAGE_LIMIT, + model::{AdminAction, AdminActionKind, AdminLogEntry, Id, LogAction, LogEntry, User}, + time::now_ms, +}; + +use super::{Connection, all, run, user}; +use crate::error::ServerError; + +pub async fn optional_user(id: Option, db: &Connection) -> Result, ServerError> { + match id { + Some(id) => Ok(Some(user::read(id, db).await?)), + None => Ok(None), + } +} + +pub async fn record( + community_id: Id, + actor_id: Option, + target_id: Option, + action: &LogAction, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO community_log (community_id, created_at, actor_id, target_id, action) VALUES (?1, ?2, ?3, ?4, ?5)", + (community_id, now_ms(), actor_id, target_id, bitcode::encode(action)), + ) + .await?; + + Ok(()) +} + +pub async fn list(community_id: Id, db: &Connection) -> Result, ServerError> { + let raws = all( + db, + "SELECT id, created_at, actor_id, target_id, action FROM community_log WHERE community_id = ?1 ORDER BY id DESC LIMIT ?2", + (community_id, LOG_PAGE_LIMIT), + |r| { + Ok(( + r.get::()?, + r.get::()?, + r.get::>()?, + r.get::>()?, + r.blob::()?, + )) + }, + ) + .await?; + + let mut entries = Vec::new(); + for (id, created_at, actor_id, target_id, action) in raws { + entries.push(LogEntry { + id, + created_at, + actor: optional_user(actor_id, db).await?, + target: optional_user(target_id, db).await?, + action, + }); + } + + Ok(entries) +} + +pub async fn record_admin( + actor_id: Option, + target_id: Option, + community: Option<&str>, + action: &AdminAction, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO admin_log (created_at, actor_id, target_id, community, kind, action) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ( + now_ms(), + actor_id, + target_id, + community, + action.kind().as_str(), + bitcode::encode(action), + ), + ) + .await?; + + Ok(()) +} + +pub async fn list_admin( + actor_id: Option, + target_id: Option, + kind: Option, + after_ms: Option, + before_ms: Option, + db: &Connection, +) -> Result, ServerError> { + let raws = all( + db, + "SELECT id, created_at, actor_id, target_id, community, action FROM admin_log WHERE (?1 IS NULL OR actor_id = ?1) AND (?2 IS NULL OR target_id = ?2) AND (?3 IS NULL OR kind = ?3) AND (?4 IS NULL OR created_at >= ?4) AND (?5 IS NULL OR created_at < ?5) ORDER BY id DESC LIMIT ?6", + ( + actor_id, + target_id, + kind.map(AdminActionKind::as_str), + after_ms.map(|ms| ms as i64), + before_ms.map(|ms| ms as i64), + LOG_PAGE_LIMIT, + ), + |r| { + Ok(( + r.get::()?, + r.get::()?, + r.get::>()?, + r.get::>()?, + r.get::>()?, + r.blob::()?, + )) + }, + ) + .await?; + + let mut entries = Vec::new(); + for (id, created_at, actor_id, target_id, community, action) in raws { + entries.push(AdminLogEntry { + id, + actor: optional_user(actor_id, db).await?, + target: optional_user(target_id, db).await?, + created_at, + community, + action, + }); + } + + Ok(entries) +} diff --git a/crates/server/src/db/member.rs b/crates/server/src/db/member.rs new file mode 100644 index 0000000..065e4b1 --- /dev/null +++ b/crates/server/src/db/member.rs @@ -0,0 +1,234 @@ +use std::collections::HashMap; + +use common::model::{Ban, Id, Member, Rank, Unread, mentions}; + +use super::{Connection, all, community, maybe, one, run, user}; +use crate::error::ServerError; + +pub async fn join( + user_id: Id, + community_id: Id, + rank: Rank, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO member (user_id, community_id, rank) VALUES (?1, ?2, ?3)", + (user_id, community_id, rank.as_str()), + ) + .await?; + + Ok(()) +} + +pub async fn leave(user_id: Id, community_id: Id, db: &Connection) -> Result { + run( + db, + "DELETE FROM member WHERE user_id = ?1 AND community_id = ?2", + (user_id, community_id), + ) + .await +} + +pub async fn rank( + user_id: Id, + community_id: Id, + db: &Connection, +) -> Result, ServerError> { + maybe( + db, + "SELECT rank FROM member WHERE user_id = ?1 AND community_id = ?2", + (user_id, community_id), + |r| r.named(), + ) + .await +} + +pub async fn set_rank( + user_id: Id, + community_id: Id, + rank: Rank, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "UPDATE member SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", + (user_id, community_id, rank.as_str()), + ) + .await?; + + Ok(()) +} + +pub async fn mark_read( + user_id: Id, + community_id: Id, + message_id: Id, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "UPDATE member SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", + (user_id, community_id, message_id), + ) + .await?; + + Ok(()) +} + +pub async fn unreads( + user_id: Id, + username: &str, + db: &Connection, +) -> Result, ServerError> { + let mut unreads = all( + db, + "SELECT m.community_id, (SELECT COUNT(*) FROM message WHERE message.community_id = m.community_id AND message.user_id != ?1 AND (m.last_read IS NULL OR message.id > m.last_read)), m.last_read FROM member m WHERE m.user_id = ?1", + (user_id,), + |r| { + Ok(Unread { + community_id: r.get()?, + messages: r.get()?, + mentions: 0, + last_read: r.get()?, + }) + }, + ) + .await?; + + let needle = format!("@{}", username.to_lowercase()); + let bodies: Vec<(Id, String)> = all( + db, + "SELECT message.community_id, message.body FROM message JOIN member ON member.community_id = message.community_id AND member.user_id = ?1 WHERE message.user_id != ?1 AND (member.last_read IS NULL OR message.id > member.last_read) AND instr(lower(message.body), ?2) > 0", + (user_id, needle.as_str()), + |r| Ok((r.get()?, r.get()?)), + ) + .await?; + + let mut counts: HashMap = HashMap::new(); + for (community_id, body) in bodies { + if mentions(&body, username) { + *counts.entry(community_id).or_default() += 1; + } + } + + for unread in &mut unreads { + unread.mentions = counts + .get(&unread.community_id) + .copied() + .unwrap_or_default(); + } + + Ok(unreads) +} + +pub async fn member_ids(community_id: Id, db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT user_id FROM member WHERE community_id = ?1", + (community_id,), + |r| r.get(), + ) + .await +} + +pub async fn members(community_id: Id, db: &Connection) -> Result, ServerError> { + all( + db, + &format!( + "SELECT {}, member.rank FROM user JOIN member ON member.user_id = user.id WHERE member.community_id = ?1 ORDER BY user.id", + user::COLUMNS + ), + (community_id,), + |r| { + Ok(Member { + user: user::row(r)?, + rank: r.named()?, + }) + }, + ) + .await +} + +pub async fn owned_groups(user_id: Id, db: &Connection) -> Result { + one( + db, + "SELECT COUNT(*) FROM member JOIN community ON community.id = member.community_id WHERE member.user_id = ?1 AND member.rank = ?2 AND community.kind = ?3", + ( + user_id, + Rank::Owner.as_str(), + community::Kind::Group.as_str(), + ), + |r| r.get(), + ) + .await +} + +pub async fn owned(user_id: Id, db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT community_id FROM member WHERE user_id = ?1 AND rank = ?2", + (user_id, Rank::Owner.as_str()), + |r| r.get(), + ) + .await +} + +pub async fn ban( + user_id: Id, + community_id: Id, + reason: Option<&str>, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT OR REPLACE INTO community_ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", + (user_id, community_id, reason), + ) + .await?; + + Ok(()) +} + +pub async fn unban(user_id: Id, community_id: Id, db: &Connection) -> Result<(), ServerError> { + run( + db, + "DELETE FROM community_ban WHERE user_id = ?1 AND community_id = ?2", + (user_id, community_id), + ) + .await?; + + Ok(()) +} + +pub async fn is_banned( + user_id: Id, + community_id: Id, + db: &Connection, +) -> Result { + one( + db, + "SELECT EXISTS (SELECT 1 FROM community_ban WHERE user_id = ?1 AND community_id = ?2)", + (user_id, community_id), + |r| r.get(), + ) + .await +} + +pub async fn bans(community_id: Id, db: &Connection) -> Result, ServerError> { + all( + db, + &format!( + "SELECT {}, community_ban.reason FROM user JOIN community_ban ON community_ban.user_id = user.id WHERE community_ban.community_id = ?1 ORDER BY community_ban.rowid DESC", + user::COLUMNS + ), + (community_id,), + |r| { + Ok(Ban { + user: user::row(r)?, + reason: r.get()?, + }) + }, + ) + .await +} diff --git a/crates/server/src/db/message.rs b/crates/server/src/db/message.rs new file mode 100644 index 0000000..39ee38d --- /dev/null +++ b/crates/server/src/db/message.rs @@ -0,0 +1,513 @@ +use common::{ + constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, + error::{Error, Field, Problem}, + model::{CallLog, Id, Message, MessageHit, Quote, Reaction, SnippetMessage}, + time::now_ms, +}; + +use super::{Connection, Reader, all, attachment, community, maybe, one, poll, run, snippet, user}; +use crate::error::{ServerError, ensure_with}; + +const SEARCH_LIMIT: u32 = 200; +const PAGE_LIMIT: u32 = MESSAGE_PAGE_LIMIT as u32; + +const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.created_at, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned FROM message m LEFT JOIN message r ON r.id = m.reply_to"; + +fn row(r: &mut Reader) -> Result { + let id = r.get()?; + let user_id = r.get()?; + let community_id = r.get()?; + let created_at = r.get()?; + let body = r.get()?; + let edited = r.get()?; + let reply_id: Option = r.get()?; + let reply_user_id: Option = r.get()?; + let reply_body: Option = r.get()?; + let reply_attachments: u32 = r.get()?; + let call: Option = r.get()?; + let call_seconds: u64 = r.get()?; + let pinned = r.get()?; + + let reply = match (reply_id, reply_user_id, reply_body) { + (Some(message_id), Some(user_id), Some(body)) => Some(Quote { + message_id, + user_id, + body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(), + attachments: reply_attachments, + }), + _ => None, + }; + + Ok(Message { + id, + user_id, + community_id, + created_at, + body, + attachments: Vec::new(), + reactions: Vec::new(), + reply, + snippet: None, + poll: None, + edited, + pinned, + call: call.and_then(|text| CallLog::parse(&text, call_seconds)), + }) +} + +async fn reactions(message_id: Id, db: &Connection) -> Result, ServerError> { + let rows: Vec<(String, Id)> = all( + db, + "SELECT emoji, user_id FROM reaction WHERE message_id = ?1 ORDER BY emoji, user_id", + (message_id,), + |r| Ok((r.get()?, r.get()?)), + ) + .await?; + + let mut reactions: Vec = Vec::new(); + for (emoji, user_id) in rows { + match reactions + .last_mut() + .filter(|reaction| reaction.emoji == emoji) + { + Some(reaction) => reaction.user_ids.push(user_id), + None => reactions.push(Reaction { + emoji, + user_ids: vec![user_id], + }), + } + } + + Ok(reactions) +} + +async fn insert( + user_id: Id, + community_id: Id, + body: &str, + reply_to: Option, + db: &Connection, +) -> Result { + one( + db, + "INSERT INTO message (community_id, user_id, created_at, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", + (community_id, user_id, now_ms(), body, reply_to), + |r| r.get(), + ) + .await +} + +pub async fn community_of(message_id: Id, db: &Connection) -> Result { + one( + db, + "SELECT community_id FROM message WHERE id = ?1", + (message_id,), + |r| r.get(), + ) + .await +} + +pub async fn create_call_log( + community_id: Id, + user_id: Id, + call: CallLog, + db: &Connection, +) -> Result { + let id: Id = one( + db, + "INSERT INTO message (community_id, user_id, created_at, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5) RETURNING id", + (community_id, user_id, now_ms(), call.as_str(), call.seconds()), + |r| r.get(), + ) + .await?; + + read(id, db).await +} + +pub async fn create( + user_id: Id, + community_id: Id, + body: &str, + attachments: &[Id], + reply_to: Option, + db: &Connection, +) -> Result { + let id = insert(user_id, community_id, body, reply_to, db).await?; + attachment::bind(id, user_id, community_id, attachments, db).await?; + + read(id, db).await +} + +pub async fn read(id: Id, db: &Connection) -> Result { + let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?; + message.reactions = reactions(id, db).await?; + message.poll = poll::of(id, db).await?; + message.attachments = attachment::of_message(id, None, db).await?; + message.snippet = snippet::of(id, db).await?; + + Ok(message) +} + +async fn read_all(ids: Vec, db: &Connection) -> Result, ServerError> { + let mut messages = Vec::new(); + for id in ids { + messages.push(read(id, db).await?); + } + + Ok(messages) +} + +pub async fn read_page( + community_id: Id, + before: Option, + db: &Connection, +) -> Result, ServerError> { + let mut ids = all( + db, + "SELECT id FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) ORDER BY id DESC LIMIT ?3", + (community_id, before, PAGE_LIMIT), + |r| r.get(), + ) + .await?; + ids.reverse(); + + read_all(ids, db).await +} + +pub async fn pinned(community_id: Id, db: &Connection) -> Result, ServerError> { + let ids = all( + db, + "SELECT id FROM message WHERE community_id = ?1 AND pinned = 1 ORDER BY id DESC", + (community_id,), + |r| r.get(), + ) + .await?; + + read_all(ids, db).await +} + +pub async fn create_poll( + user_id: Id, + community_id: Id, + question: &str, + options: &[String], + multiple: bool, + db: &Connection, +) -> Result { + let id = insert(user_id, community_id, "", None, db).await?; + poll::create(id, question, options, multiple, db).await?; + + read(id, db).await +} + +pub async fn vote( + message_id: Id, + user_id: Id, + positions: &[u32], + db: &Connection, +) -> Result { + poll::set_votes(message_id, user_id, positions, db).await?; + + read(message_id, db).await +} + +pub async fn close_poll(message_id: Id, db: &Connection) -> Result { + poll::close(message_id, db).await?; + + read(message_id, db).await +} + +pub async fn react( + message_id: Id, + user_id: Id, + emoji: &str, + db: &Connection, +) -> Result { + let removed = run( + db, + "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", + (message_id, user_id, emoji), + ) + .await?; + if removed == 0 { + run( + db, + "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)", + (message_id, user_id, emoji), + ) + .await?; + } + + read(message_id, db).await +} + +pub async fn pin(message_id: Id, pinned: bool, db: &Connection) -> Result { + run( + db, + "UPDATE message SET pinned = ?2 WHERE id = ?1", + (message_id, pinned), + ) + .await?; + + read(message_id, db).await +} + +pub async fn update(message_id: Id, body: &str, db: &Connection) -> Result { + ensure_with( + run( + db, + "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1", + (message_id, body), + ) + .await? + == 1, + Error::NotFound, + )?; + + read(message_id, db).await +} + +pub async fn delete(message_id: Id, db: &Connection) -> Result<(), ServerError> { + ensure_with( + run(db, "DELETE FROM message WHERE id = ?1", (message_id,)).await? == 1, + Error::NotFound, + ) +} + +pub async fn delete_where_user(user_id: Id, db: &Connection) -> Result, ServerError> { + all( + db, + "DELETE FROM message WHERE user_id = ?1 RETURNING community_id, id", + (user_id,), + |r| Ok((r.get()?, r.get()?)), + ) + .await +} + +pub async fn delete_before( + cutoff: u64, + limit: u32, + db: &Connection, +) -> Result, ServerError> { + all( + db, + "DELETE FROM message WHERE id IN (SELECT id FROM message WHERE created_at < ?1 ORDER BY id LIMIT ?2) RETURNING community_id, id", + (cutoff, limit), + |r| Ok((r.get()?, r.get()?)), + ) + .await +} + +pub async fn search( + text: Option<&str>, + user_id: Option, + community_id: Option, + after_ms: Option, + before_ms: Option, + db: &Connection, +) -> Result, ServerError> { + let ids: Vec = all( + db, + "SELECT id FROM message WHERE (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR created_at >= ?4) AND (?5 IS NULL OR created_at < ?5) ORDER BY id DESC LIMIT ?6", + ( + text, + user_id, + community_id, + after_ms.map(|ms| ms as i64), + before_ms.map(|ms| ms as i64), + SEARCH_LIMIT, + ), + |r| r.get(), + ) + .await?; + + let mut hits = Vec::new(); + for id in ids { + let message = read(id, db).await?; + let community = community::label(message.community_id, db).await?; + let author = user::read(message.user_id, db).await?; + hits.push(MessageHit { + message, + community, + author: Some(author), + }); + } + + Ok(hits) +} + +async fn origin(sources: &[Message], db: &Connection) -> Result, ServerError> { + let Some(first) = sources.first() else { + return Ok(None); + }; + if sources + .iter() + .any(|source| source.community_id != first.community_id) + { + return Ok(None); + } + + maybe( + db, + "SELECT name FROM community WHERE id = ?1 AND kind = ?2", + (first.community_id, community::Kind::Group.as_str()), + |r| r.get(), + ) + .await +} + +async fn entry(source: &Message, db: &Connection) -> Result { + let author = user::read(source.user_id, db).await?; + + Ok(SnippetMessage { + id: source.id, + user_id: author.id, + username: author.username, + avatar_id: author.avatar_id, + created_at: source.created_at, + body: source.body.clone(), + attachments: source.attachments.clone(), + poll: source.poll.clone(), + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForwardMode { + Copy, + Snippet, +} + +pub async fn forward( + user_id: Id, + community_id: Id, + sources: &[Message], + mode: ForwardMode, + db: &Connection, +) -> Result, ServerError> { + if mode == ForwardMode::Copy { + let mut created = Vec::new(); + for source in sources { + let id = insert(user_id, community_id, &source.body, None, db).await?; + for attachment in &source.attachments { + attachment::copy_row(attachment.id, id, user_id, community_id, None, db).await?; + } + if let Some(inner) = &source.snippet { + snippet::write( + id, + user_id, + community_id, + inner.origin.as_deref(), + &inner.messages, + db, + ) + .await?; + } + created.push(read(id, db).await?); + } + + return Ok(created); + } + + let mut entries = Vec::new(); + for source in sources { + match &source.snippet { + Some(inner) => entries.extend(inner.messages.iter().cloned()), + None => entries.push(entry(source, db).await?), + } + } + if entries.len() > MAXIMUM_FORWARD_MESSAGES { + return Err(Error::Invalid { + field: Field::Forward, + problem: Problem::Length { + min: 1, + max: MAXIMUM_FORWARD_MESSAGES as u64, + actual: entries.len() as u64, + }, + } + .into()); + } + + let origin = origin(sources, db).await?; + let id = insert(user_id, community_id, "", None, db).await?; + snippet::write(id, user_id, community_id, origin.as_deref(), &entries, db).await?; + + Ok(vec![read(id, db).await?]) +} + +#[cfg(test)] +mod tests { + use common::model::Role; + + use super::{ForwardMode, create, forward, read_page}; + use crate::{ + db::{community, user}, + test, + }; + + #[tokio::test] + async fn read_page_orders_and_pages() { + let db = test::db().await; + let conn = db.lock().await.unwrap(); + let user_1 = user::create("Tahinli", "hash", Role::User, &conn) + .await + .unwrap(); + let user_2 = user::create("Not Tahinli", "hash", Role::User, &conn) + .await + .unwrap(); + let community = community::create(community::Kind::Group, "Tahinli", &conn) + .await + .unwrap(); + + let message_1 = create(user_1.id, community, "Tahinli", &[], None, &conn) + .await + .unwrap(); + let message_2 = create(user_2.id, community, "Tahinli", &[], None, &conn) + .await + .unwrap(); + let message_3 = create(user_2.id, community, "Tahinli", &[], None, &conn) + .await + .unwrap(); + + let newest = read_page(community, None, &conn).await.unwrap(); + let older = read_page(community, Some(message_3.id), &conn) + .await + .unwrap(); + + assert_eq!( + vec![message_1.clone(), message_2.clone(), message_3], + newest + ); + assert_eq!(vec![message_1, message_2], older); + } + + #[tokio::test] + async fn forward_two_as_snippet() { + let db = test::db().await; + let conn = db.lock().await.unwrap(); + let user = user::create("Tahinli", "hash", Role::User, &conn) + .await + .unwrap(); + let community = community::create(community::Kind::Group, "Tahinli", &conn) + .await + .unwrap(); + let first = create(user.id, community, "First", &[], None, &conn) + .await + .unwrap(); + let second = create(user.id, community, "Second", &[], None, &conn) + .await + .unwrap(); + + let created = forward( + user.id, + community, + &[first, second], + ForwardMode::Snippet, + &conn, + ) + .await + .unwrap(); + + assert_eq!(1, created.len()); + assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len()); + } +} diff --git a/crates/server/src/db/mod.rs b/crates/server/src/db/mod.rs new file mode 100644 index 0000000..88f7938 --- /dev/null +++ b/crates/server/src/db/mod.rs @@ -0,0 +1,167 @@ +pub mod attachment; +pub mod avatar; +pub mod community; +pub mod direct; +pub mod friend; +pub mod invitation; +pub mod log; +pub mod member; +pub mod message; +pub mod poll; +pub mod registration_code; +pub mod report; +pub mod server_ban; +pub mod session; +pub mod settings; +pub mod snippet; +pub mod stats; +pub mod user; + +use std::sync::Arc; + +use bitcode::DecodeOwned; +use common::{error::Error, model::Named}; +use tokio::sync::{Mutex, MutexGuard}; +use turso::{Builder, Database, IntoParams, Row, core::types::FromValue}; + +pub use turso::Connection; + +use crate::error::ServerError; + +const SCHEMA: &str = include_str!("schema.sql"); + +#[derive(Clone)] +pub struct Db { + database: Database, + conn: Arc>, +} + +impl Db { + pub async fn open(path: &str) -> Result { + let database = Builder::new_local(path).build().await?; + let conn = database.connect()?; + conn.execute_batch("PRAGMA foreign_keys = ON").await?; + if schema(&conn).await?.is_empty() { + conn.execute_batch(SCHEMA).await?; + } + let fresh_database = Builder::new_local(":memory:").build().await?; + let fresh = fresh_database.connect()?; + fresh.execute_batch(SCHEMA).await?; + if schema(&conn).await? != schema(&fresh).await? { + return Err(ServerError::Internal(format!( + "{path} has an old schema, delete it" + ))); + } + settings::read(&conn).await?; + + Ok(Self { + database, + conn: Arc::new(Mutex::new(conn)), + }) + } + + pub async fn lock(&self) -> Result, ServerError> { + let conn = self.conn.lock().await; + if !conn.is_autocommit()? { + conn.execute("ROLLBACK", ()).await?; + } + Ok(conn) + } + + pub async fn run( + &self, + work: impl AsyncFnOnce(&Connection) -> Result, + ) -> Result { + let db = self.lock().await?; + atomic(&db, work(&db)).await + } + + pub async fn backup(&self, target: &str) -> Result<(), ServerError> { + self.database + .connect()? + .execute("VACUUM INTO ?1", (target,)) + .await?; + Ok(()) + } +} + +pub async fn atomic( + db: &Connection, + work: impl Future>, +) -> Result { + db.execute("BEGIN IMMEDIATE", ()).await?; + let result = work.await; + db.execute(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }, ()) + .await?; + result +} + +async fn schema(db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY name", + (), + |r| r.get(), + ) + .await +} + +pub struct Reader<'a> { + row: &'a Row, + at: usize, +} + +impl Reader<'_> { + pub fn get(&mut self) -> Result { + self.at += 1; + Ok(self.row.get(self.at - 1)?) + } + + pub fn named(&mut self) -> Result { + let text: String = self.get()?; + T::parse(&text).ok_or_else(|| ServerError::Internal(format!("unknown enum text {text}"))) + } + + pub fn blob(&mut self) -> Result { + let bytes: Vec = self.get()?; + Ok(bitcode::decode(&bytes)?) + } +} + +pub async fn all( + db: &Connection, + sql: &str, + params: impl IntoParams, + read: impl Fn(&mut Reader) -> Result, +) -> Result, ServerError> { + let mut rows = db.prepare_cached(sql).await?.query(params).await?; + let mut values = Vec::new(); + while let Some(row) = rows.next().await? { + values.push(read(&mut Reader { row: &row, at: 0 })?); + } + Ok(values) +} + +pub async fn maybe( + db: &Connection, + sql: &str, + params: impl IntoParams, + read: impl Fn(&mut Reader) -> Result, +) -> Result, ServerError> { + Ok(all(db, sql, params, read).await?.into_iter().next()) +} + +pub async fn one( + db: &Connection, + sql: &str, + params: impl IntoParams, + read: impl Fn(&mut Reader) -> Result, +) -> Result { + maybe(db, sql, params, read) + .await? + .ok_or_else(|| Error::NotFound.into()) +} + +pub async fn run(db: &Connection, sql: &str, params: impl IntoParams) -> Result { + Ok(db.prepare_cached(sql).await?.execute(params).await?) +} diff --git a/crates/server/src/db/poll.rs b/crates/server/src/db/poll.rs new file mode 100644 index 0000000..daf40cb --- /dev/null +++ b/crates/server/src/db/poll.rs @@ -0,0 +1,114 @@ +use common::{ + error::Error, + model::{Id, Poll, PollOption}, +}; + +use super::{Connection, all, maybe, run}; +use crate::error::{ServerError, ensure_with}; + +pub async fn create( + message_id: Id, + question: &str, + options: &[String], + multiple: bool, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", + (message_id, question, multiple), + ) + .await?; + for (position, text) in (0u32..).zip(options) { + run( + db, + "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)", + (message_id, position, text.as_str()), + ) + .await?; + } + + Ok(()) +} + +pub async fn of(message_id: Id, db: &Connection) -> Result, ServerError> { + let Some((question, multiple, closed)) = maybe( + db, + "SELECT question, multiple, closed FROM poll WHERE message_id = ?1", + (message_id,), + |r| Ok((r.get::()?, r.get::()?, r.get::()?)), + ) + .await? + else { + return Ok(None); + }; + + let mut options: Vec = all( + db, + "SELECT text FROM poll_option WHERE message_id = ?1 ORDER BY position", + (message_id,), + |r| { + Ok(PollOption { + text: r.get()?, + voter_ids: Vec::new(), + }) + }, + ) + .await?; + let votes: Vec<(u32, Id)> = all( + db, + "SELECT position, user_id FROM poll_vote WHERE message_id = ?1 ORDER BY position, user_id", + (message_id,), + |r| Ok((r.get()?, r.get()?)), + ) + .await?; + for (position, user_id) in votes { + if let Some(option) = options.get_mut(position as usize) { + option.voter_ids.push(user_id); + } + } + + Ok(Some(Poll { + question, + options, + multiple, + closed, + })) +} + +pub async fn set_votes( + message_id: Id, + user_id: Id, + positions: &[u32], + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", + (message_id, user_id), + ) + .await?; + for position in positions { + run( + db, + "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)", + (message_id, *position, user_id), + ) + .await?; + } + + Ok(()) +} + +pub async fn close(message_id: Id, db: &Connection) -> Result<(), ServerError> { + ensure_with( + run( + db, + "UPDATE poll SET closed = 1 WHERE message_id = ?1", + (message_id,), + ) + .await? + == 1, + Error::NotFound, + ) +} diff --git a/crates/server/src/db/registration_code.rs b/crates/server/src/db/registration_code.rs new file mode 100644 index 0000000..5869fa4 --- /dev/null +++ b/crates/server/src/db/registration_code.rs @@ -0,0 +1,60 @@ +use common::{ + error::Error, + model::InviteCode, + time::{HOUR_MILLIS, now_ms}, +}; + +use super::{Connection, all, run}; +use crate::error::{ServerError, ensure_with}; + +pub async fn create( + code: &str, + uses: u32, + hours: Option, + db: &Connection, +) -> Result { + let expires_at = hours.map(|hours| now_ms() + u64::from(hours) * HOUR_MILLIS); + run( + db, + "INSERT INTO registration_code (code, uses_left, expires_at) VALUES (?1, ?2, ?3)", + (code, uses, expires_at.map(|ms| ms as i64)), + ) + .await?; + + Ok(InviteCode { + code: code.to_string(), + uses_left: uses, + expires_at, + }) +} + +pub async fn list(db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT code, uses_left, expires_at FROM registration_code", + (), + |r| { + Ok(InviteCode { + code: r.get()?, + uses_left: r.get()?, + expires_at: r.get()?, + }) + }, + ) + .await +} + +pub async fn delete(code: &str, db: &Connection) -> Result<(), ServerError> { + let deleted = run(db, "DELETE FROM registration_code WHERE code = ?1", (code,)).await?; + ensure_with(deleted == 1, Error::NotFound) +} + +pub async fn consume(code: &str, db: &Connection) -> Result<(), ServerError> { + let updated = run( + db, + "UPDATE registration_code SET uses_left = uses_left - 1 WHERE code = ?1 AND uses_left > 0 AND (expires_at IS NULL OR expires_at > ?2)", + (code, now_ms()), + ) + .await?; + ensure_with(updated == 1, Error::RegistrationClosed) +} diff --git a/crates/server/src/db/report.rs b/crates/server/src/db/report.rs new file mode 100644 index 0000000..a941746 --- /dev/null +++ b/crates/server/src/db/report.rs @@ -0,0 +1,126 @@ +use common::{ + constant::LOG_PAGE_LIMIT, + model::{Id, Report, ReportStatus}, + time::now_ms, +}; + +use super::{Connection, all, log::optional_user, one, run}; +use crate::error::ServerError; + +struct Raw { + id: Id, + created_at: u64, + reporter_id: Option, + target_id: Option, + community: Option, + message_id: Option, + community_id: Option, + body: Option, + reason: String, + status: ReportStatus, + handled_by: Option, +} + +pub async fn is_open( + reporter_id: Id, + target_id: Id, + message_id: Option, + db: &Connection, +) -> Result { + one( + db, + "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", + (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), + |r| r.get(), + ) + .await +} + +pub async fn insert( + reporter_id: Id, + target_id: Id, + message_id: Option, + community_id: Option, + body: Option<&str>, + reason: &str, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO report (created_at, reporter_id, target_id, message_id, community_id, body, reason, status) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + ( + now_ms(), + reporter_id, + target_id, + message_id, + community_id, + body, + reason, + ReportStatus::Open.as_str(), + ), + ) + .await?; + + Ok(()) +} + +pub async fn list( + status: Option, + db: &Connection, +) -> Result, ServerError> { + let raws = all( + db, + "SELECT r.id, r.created_at, r.reporter_id, r.target_id, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, r.handled_by FROM report r LEFT JOIN community c ON c.id = r.community_id WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT ?2", + (status.map(ReportStatus::as_str), LOG_PAGE_LIMIT), + |r| { + Ok(Raw { + id: r.get()?, + created_at: r.get()?, + reporter_id: r.get()?, + target_id: r.get()?, + community: r.get()?, + message_id: r.get()?, + community_id: r.get()?, + body: r.get()?, + reason: r.get()?, + status: r.named()?, + handled_by: r.get()?, + }) + }, + ) + .await?; + + let mut reports = Vec::new(); + for raw in raws { + reports.push(Report { + id: raw.id, + created_at: raw.created_at, + reporter: optional_user(raw.reporter_id, db).await?, + target: optional_user(raw.target_id, db).await?, + message_id: raw.message_id, + community_id: raw.community_id, + community: raw.community, + body: raw.body, + reason: raw.reason, + status: raw.status, + handled_by: optional_user(raw.handled_by, db).await?, + }); + } + + Ok(reports) +} + +pub async fn handle( + report_id: Id, + status: ReportStatus, + handled_by: Id, + db: &Connection, +) -> Result, ServerError> { + one( + db, + "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", + (report_id, status.as_str(), handled_by, ReportStatus::Open.as_str()), + |r| r.get(), + ) + .await +} diff --git a/crates/server/src/db/schema.sql b/crates/server/src/db/schema.sql new file mode 100644 index 0000000..981a14f --- /dev/null +++ b/crates/server/src/db/schema.sql @@ -0,0 +1,215 @@ +CREATE TABLE user ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE COLLATE NOCASE, + password_hash TEXT NOT NULL, + role TEXT NOT NULL, + status TEXT NOT NULL DEFAULT '', + presence TEXT NOT NULL, + suspended INTEGER NOT NULL DEFAULT 0, + suspended_until INTEGER, + voice_muted INTEGER NOT NULL DEFAULT 0, + ghost INTEGER NOT NULL DEFAULT 0, + last_ip TEXT, + last_seen INTEGER, + created_at INTEGER NOT NULL +) STRICT; + +CREATE TABLE session ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + token_hash BLOB NOT NULL UNIQUE, + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + device TEXT NOT NULL DEFAULT '', + last_seen INTEGER +) STRICT; +CREATE INDEX session_user ON session (user_id); + +CREATE TABLE community ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + name TEXT NOT NULL DEFAULT '' COLLATE NOCASE, + voice_enabled INTEGER NOT NULL +) STRICT; + +CREATE TABLE avatar ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER UNIQUE REFERENCES user (id) ON DELETE CASCADE, + community_id INTEGER UNIQUE REFERENCES community (id) ON DELETE CASCADE, + data BLOB NOT NULL, + CHECK ((user_id IS NULL) != (community_id IS NULL)) +) STRICT; + +CREATE TABLE member ( + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, + rank TEXT NOT NULL, + last_read INTEGER, + PRIMARY KEY (user_id, community_id) +) STRICT; +CREATE INDEX member_community ON member (community_id); + +CREATE TABLE community_ban ( + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + reason TEXT, + PRIMARY KEY (community_id, user_id) +) STRICT; + +CREATE TABLE direct ( + user_a INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + user_b INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + community_id INTEGER NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE, + PRIMARY KEY (user_a, user_b), + CHECK (user_a <= user_b) +) STRICT; + +CREATE TABLE invitation ( + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, + inviter_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + PRIMARY KEY (user_id, community_id) +) STRICT; + +CREATE TABLE friend ( + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + friend_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + state TEXT NOT NULL, + PRIMARY KEY (user_id, friend_id) +) STRICT; + +CREATE TABLE message ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + body TEXT NOT NULL, + reply_to INTEGER REFERENCES message (id) ON DELETE SET NULL, + edited INTEGER NOT NULL DEFAULT 0, + pinned INTEGER NOT NULL DEFAULT 0, + call TEXT, + call_seconds INTEGER NOT NULL DEFAULT 0 +) STRICT; +CREATE INDEX message_community ON message (community_id, id); +CREATE INDEX message_user ON message (user_id); +CREATE INDEX message_created ON message (created_at); +CREATE INDEX message_reply ON message (reply_to); + +CREATE TABLE attachment ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + uploader_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, + message_id INTEGER REFERENCES message (id) ON DELETE CASCADE, + snippet_position INTEGER, + created_at INTEGER NOT NULL, + file TEXT NOT NULL, + name TEXT NOT NULL, + size INTEGER NOT NULL, + kind TEXT NOT NULL, + width INTEGER, + height INTEGER +) STRICT; +CREATE INDEX attachment_message ON attachment (message_id); +CREATE INDEX attachment_uploader ON attachment (uploader_id); +CREATE INDEX attachment_community ON attachment (community_id); + +CREATE TABLE reaction ( + message_id INTEGER NOT NULL REFERENCES message (id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + emoji TEXT NOT NULL, + PRIMARY KEY (message_id, user_id, emoji) +) STRICT; + +CREATE TABLE poll ( + message_id INTEGER PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, + question TEXT NOT NULL, + multiple INTEGER NOT NULL, + closed INTEGER NOT NULL DEFAULT 0 +) STRICT; + +CREATE TABLE poll_option ( + message_id INTEGER NOT NULL REFERENCES poll (message_id) ON DELETE CASCADE, + position INTEGER NOT NULL, + text TEXT NOT NULL, + PRIMARY KEY (message_id, position) +) STRICT; + +CREATE TABLE poll_vote ( + message_id INTEGER NOT NULL REFERENCES poll (message_id) ON DELETE CASCADE, + position INTEGER NOT NULL, + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + PRIMARY KEY (message_id, position, user_id) +) STRICT; + +CREATE TABLE snippet ( + message_id INTEGER PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, + origin TEXT +) STRICT; + +CREATE TABLE snippet_message ( + message_id INTEGER NOT NULL REFERENCES snippet (message_id) ON DELETE CASCADE, + position INTEGER NOT NULL, + original_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + username TEXT NOT NULL, + created_at INTEGER NOT NULL, + body TEXT NOT NULL, + poll BLOB NOT NULL, + PRIMARY KEY (message_id, position) +) STRICT; + +CREATE TABLE community_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + actor_id INTEGER REFERENCES user (id) ON DELETE SET NULL, + target_id INTEGER REFERENCES user (id) ON DELETE SET NULL, + action BLOB NOT NULL +) STRICT; +CREATE INDEX community_log_community ON community_log (community_id, id); + +CREATE TABLE admin_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at INTEGER NOT NULL, + actor_id INTEGER REFERENCES user (id) ON DELETE SET NULL, + target_id INTEGER REFERENCES user (id) ON DELETE SET NULL, + community TEXT, + kind TEXT NOT NULL, + action BLOB NOT NULL +) STRICT; + +CREATE TABLE report ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at INTEGER NOT NULL, + reporter_id INTEGER REFERENCES user (id) ON DELETE SET NULL, + target_id INTEGER REFERENCES user (id) ON DELETE SET NULL, + message_id INTEGER, + community_id INTEGER, + body TEXT, + reason TEXT NOT NULL, + status TEXT NOT NULL, + handled_by INTEGER REFERENCES user (id) ON DELETE SET NULL +) STRICT; + +CREATE TABLE server_ban ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + value TEXT NOT NULL COLLATE NOCASE, + reason TEXT, + UNIQUE (kind, value) +) STRICT; + +CREATE TABLE registration_code ( + code TEXT PRIMARY KEY, + uses_left INTEGER NOT NULL, + expires_at INTEGER +) STRICT; + +CREATE TABLE daily_active ( + day INTEGER NOT NULL, + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, + PRIMARY KEY (day, user_id) +) STRICT; + +CREATE TABLE server_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + data BLOB NOT NULL +) STRICT; diff --git a/crates/server/src/db/server_ban.rs b/crates/server/src/db/server_ban.rs new file mode 100644 index 0000000..580adf0 --- /dev/null +++ b/crates/server/src/db/server_ban.rs @@ -0,0 +1,63 @@ +use common::{ + error::Error, + model::{Id, ServerBan, ServerBanKind}, +}; + +use super::{Connection, all, one, run}; +use crate::error::{ServerError, ensure_with}; + +pub async fn insert( + kind: ServerBanKind, + value: &str, + reason: Option<&str>, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT OR IGNORE INTO server_ban (kind, value, reason) VALUES (?1, ?2, ?3)", + (kind.as_str(), value, reason), + ) + .await?; + + Ok(()) +} + +pub async fn list(db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", + (), + |r| { + Ok(ServerBan { + id: r.get()?, + kind: r.named()?, + value: r.get()?, + reason: r.get()?, + }) + }, + ) + .await +} + +async fn exists(kind: ServerBanKind, value: &str, db: &Connection) -> Result { + one( + db, + "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", + (kind.as_str(), value), + |r| r.get(), + ) + .await +} + +pub async fn username_banned(username: &str, db: &Connection) -> Result { + exists(ServerBanKind::Username, username, db).await +} + +pub async fn ip_banned(ip: &str, db: &Connection) -> Result { + exists(ServerBanKind::Ip, ip, db).await +} + +pub async fn remove(id: Id, db: &Connection) -> Result<(), ServerError> { + let deleted = run(db, "DELETE FROM server_ban WHERE id = ?1", (id,)).await?; + ensure_with(deleted == 1, Error::NotFound) +} diff --git a/crates/server/src/db/session.rs b/crates/server/src/db/session.rs new file mode 100644 index 0000000..d856e9c --- /dev/null +++ b/crates/server/src/db/session.rs @@ -0,0 +1,109 @@ +use common::{ + model::{Id, SessionInfo, User}, + time::now_ms, +}; + +use super::{Connection, all, maybe, one, run, user}; +use crate::error::ServerError; + +pub async fn insert(token_hash: &[u8], user_id: Id, db: &Connection) -> Result { + one( + db, + "INSERT INTO session (token_hash, user_id) VALUES (?1, ?2) RETURNING id", + (token_hash, user_id), + |r| r.get(), + ) + .await +} + +pub async fn find(token_hash: &[u8], db: &Connection) -> Result, ServerError> { + maybe( + db, + &format!( + "SELECT session.id, {} FROM session JOIN user ON user.id = session.user_id WHERE session.token_hash = ?1", + user::COLUMNS + ), + (token_hash,), + |r| Ok((r.get()?, user::row(r)?)), + ) + .await +} + +pub async fn user_of(session_id: Id, db: &Connection) -> Result, ServerError> { + maybe( + db, + &format!( + "SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.id = ?1", + user::COLUMNS + ), + (session_id,), + user::row, + ) + .await +} + +pub async fn seen(session_id: Id, db: &Connection) -> Result<(), ServerError> { + let now = now_ms(); + run( + db, + "UPDATE user SET last_seen = ?2 WHERE id = (SELECT user_id FROM session WHERE id = ?1) AND ghost = 0", + (session_id, now), + ) + .await?; + run( + db, + "UPDATE session SET last_seen = ?2 WHERE id = ?1 AND user_id IN (SELECT id FROM user WHERE ghost = 0)", + (session_id, now), + ) + .await?; + + Ok(()) +} + +pub async fn set_device(session_id: Id, device: &str, db: &Connection) -> Result<(), ServerError> { + run( + db, + "UPDATE session SET device = ?2 WHERE id = ?1", + (session_id, device), + ) + .await?; + + Ok(()) +} + +pub async fn list(user_id: Id, db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT id, device, last_seen FROM session WHERE user_id = ?1 ORDER BY last_seen DESC", + (user_id,), + |r| { + Ok(SessionInfo { + id: r.get()?, + device: r.get()?, + last_seen: r.get()?, + }) + }, + ) + .await +} + +pub async fn delete(session_id: Id, db: &Connection) -> Result<(), ServerError> { + run(db, "DELETE FROM session WHERE id = ?1", (session_id,)).await?; + + Ok(()) +} + +pub async fn delete_of(user_id: Id, session_id: Id, db: &Connection) -> Result { + run( + db, + "DELETE FROM session WHERE id = ?1 AND user_id = ?2", + (session_id, user_id), + ) + .await +} + +pub async fn delete_all(user_id: Id, db: &Connection) -> Result<(), ServerError> { + run(db, "DELETE FROM session WHERE user_id = ?1", (user_id,)).await?; + + Ok(()) +} diff --git a/crates/server/src/db/settings.rs b/crates/server/src/db/settings.rs new file mode 100644 index 0000000..3880a9e --- /dev/null +++ b/crates/server/src/db/settings.rs @@ -0,0 +1,26 @@ +use common::model::ServerSettings; + +use super::{Connection, maybe, run}; +use crate::error::ServerError; + +pub async fn read(db: &Connection) -> Result { + Ok(maybe( + db, + "SELECT data FROM server_settings WHERE id = 1", + (), + |r| r.blob::(), + ) + .await? + .unwrap_or_default()) +} + +pub async fn update(settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> { + run( + db, + "INSERT OR REPLACE INTO server_settings (id, data) VALUES (1, ?1)", + (bitcode::encode(settings),), + ) + .await?; + + Ok(()) +} diff --git a/crates/server/src/db/snippet.rs b/crates/server/src/db/snippet.rs new file mode 100644 index 0000000..c0c411c --- /dev/null +++ b/crates/server/src/db/snippet.rs @@ -0,0 +1,94 @@ +use common::model::{Id, Poll, Snippet, SnippetMessage}; + +use super::{Connection, all, attachment, maybe, run}; +use crate::error::ServerError; + +pub async fn of(message_id: Id, db: &Connection) -> Result, ServerError> { + let Some(origin) = maybe( + db, + "SELECT origin FROM snippet WHERE message_id = ?1", + (message_id,), + |r| r.get::>(), + ) + .await? + else { + return Ok(None); + }; + + let entries: Vec<(u32, SnippetMessage)> = all( + db, + "SELECT position, original_id, user_id, username, (SELECT avatar.id FROM avatar WHERE avatar.user_id = snippet_message.user_id), created_at, body, poll FROM snippet_message WHERE message_id = ?1 ORDER BY position", + (message_id,), + |r| { + Ok(( + r.get()?, + SnippetMessage { + id: r.get()?, + user_id: r.get()?, + username: r.get()?, + avatar_id: r.get()?, + created_at: r.get()?, + body: r.get()?, + attachments: Vec::new(), + poll: r.blob::>()?, + }, + )) + }, + ) + .await?; + + let mut messages = Vec::new(); + for (position, mut entry) in entries { + entry.attachments = attachment::of_message(message_id, Some(position), db).await?; + messages.push(entry); + } + + Ok(Some(Snippet { origin, messages })) +} + +pub async fn write( + message_id: Id, + user_id: Id, + community_id: Id, + origin: Option<&str>, + entries: &[SnippetMessage], + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)", + (message_id, origin), + ) + .await?; + + for (position, entry) in (0u32..).zip(entries) { + run( + db, + "INSERT INTO snippet_message (message_id, position, original_id, user_id, username, created_at, body, poll) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + ( + message_id, + position, + entry.id, + entry.user_id, + entry.username.as_str(), + entry.created_at, + entry.body.as_str(), + bitcode::encode(&entry.poll), + ), + ) + .await?; + for attachment in &entry.attachments { + attachment::copy_row( + attachment.id, + message_id, + user_id, + community_id, + Some(position), + db, + ) + .await?; + } + } + + Ok(()) +} diff --git a/crates/server/src/db/stats.rs b/crates/server/src/db/stats.rs new file mode 100644 index 0000000..b9e9bb8 --- /dev/null +++ b/crates/server/src/db/stats.rs @@ -0,0 +1,69 @@ +use std::collections::HashMap; + +use common::{ + model::{DayStat, Id, Role}, + time::{DAY_MILLIS, now_ms}, +}; + +use super::{Connection, all, community::Kind, one, run}; +use crate::error::ServerError; + +const MAXIMUM_DAYS: u32 = 90; + +pub async fn mark_active(user_id: Id, db: &Connection) -> Result<(), ServerError> { + run( + db, + "INSERT OR IGNORE INTO daily_active (day, user_id) SELECT ?1, id FROM user WHERE id = ?2 AND ghost = 0", + (now_ms() / DAY_MILLIS, user_id), + ) + .await?; + + Ok(()) +} + +pub async fn daily(days: u32, db: &Connection) -> Result, ServerError> { + let days = u64::from(days.clamp(1, MAXIMUM_DAYS)); + let today = now_ms() / DAY_MILLIS; + let first = today + 1 - days; + let active: HashMap = all( + db, + "SELECT day, COUNT(*) FROM daily_active WHERE day >= ?1 GROUP BY day", + (first,), + |r| Ok((r.get()?, r.get()?)), + ) + .await? + .into_iter() + .collect(); + let messages: HashMap = all( + db, + "SELECT created_at / ?2 AS day, COUNT(*) FROM message WHERE created_at >= ?1 * ?2 GROUP BY day", + (first, DAY_MILLIS), + |r| Ok((r.get()?, r.get()?)), + ) + .await? + .into_iter() + .collect(); + + Ok((first..=today) + .map(|day| DayStat { + day, + active_users: active.get(&day).copied().unwrap_or_default(), + messages: messages.get(&day).copied().unwrap_or_default(), + }) + .collect()) +} + +pub async fn counts(db: &Connection) -> Result<(u64, u64, u64, u64), ServerError> { + one( + db, + "SELECT + (SELECT COUNT(*) FROM user), + (SELECT COUNT(*) FROM user WHERE role = ?1), + (SELECT COUNT(*) FROM community WHERE kind = ?2), + (SELECT COALESCE(SUM(size), 0) FROM attachment) + + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar)", + (Role::Builder.as_str(), Kind::Group.as_str()), + |r| Ok((r.get()?, r.get()?, r.get()?, r.get()?)), + ) + .await +} diff --git a/crates/server/src/db/user.rs b/crates/server/src/db/user.rs new file mode 100644 index 0000000..5ddbc20 --- /dev/null +++ b/crates/server/src/db/user.rs @@ -0,0 +1,314 @@ +use common::{ + error::Error, + model::{Account, Id, Presence, Role, User}, + permission, + time::now_ms, +}; + +use super::{Connection, Reader, all, maybe, one, run}; +use crate::error::{ServerError, ensure_with}; + +pub const COLUMNS: &str = "user.id, user.username, user.role, user.status, (SELECT avatar.id FROM avatar WHERE avatar.user_id = user.id), user.created_at"; + +pub fn row(r: &mut Reader) -> Result { + Ok(User { + id: r.get()?, + username: r.get()?, + role: r.named()?, + status: r.get()?, + avatar_id: r.get()?, + created_at: r.get()?, + }) +} + +pub async fn read(id: Id, db: &Connection) -> Result { + one( + db, + &format!("SELECT {COLUMNS} FROM user WHERE user.id = ?1"), + (id,), + row, + ) + .await +} + +pub async fn create( + username: &str, + password_hash: &str, + role: Role, + db: &Connection, +) -> Result { + let id: Id = one( + db, + "INSERT INTO user (username, password_hash, role, presence, created_at) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", + ( + username, + password_hash, + role.as_str(), + Presence::Online.as_str(), + now_ms(), + ), + |r| r.get(), + ) + .await?; + + read(id, db).await +} + +pub async fn any(db: &Connection) -> Result { + one(db, "SELECT EXISTS (SELECT 1 FROM user)", (), |r| r.get()).await +} + +pub async fn by_username(username: &str, db: &Connection) -> Result, ServerError> { + maybe( + db, + &format!("SELECT {COLUMNS} FROM user WHERE user.username = ?1"), + (username,), + row, + ) + .await +} + +pub async fn password_hash_of( + username: &str, + db: &Connection, +) -> Result, ServerError> { + maybe( + db, + &format!("SELECT {COLUMNS}, user.password_hash FROM user WHERE user.username = ?1"), + (username,), + |r| Ok((row(r)?, r.get()?)), + ) + .await +} + +pub async fn update(id: Id, username: &str, db: &Connection) -> Result { + run( + db, + "UPDATE user SET username = ?2 WHERE id = ?1", + (id, username), + ) + .await?; + + read(id, db).await +} + +pub async fn update_status(id: Id, status: &str, db: &Connection) -> Result { + run( + db, + "UPDATE user SET status = ?2 WHERE id = ?1", + (id, status), + ) + .await?; + + read(id, db).await +} + +pub async fn set_role_by_id(id: Id, role: Role, db: &Connection) -> Result { + run( + db, + "UPDATE user SET role = ?2 WHERE id = ?1", + (id, role.as_str()), + ) + .await?; + + read(id, db).await +} + +pub async fn suspended(id: Id, db: &Connection) -> Result>, ServerError> { + let (suspended, until): (bool, Option) = one( + db, + "SELECT suspended, suspended_until FROM user WHERE id = ?1", + (id,), + |r| Ok((r.get()?, r.get()?)), + ) + .await?; + + if suspended { + return Ok(Some(None)); + } + + Ok(until.filter(|until| *until > now_ms()).map(Some)) +} + +pub async fn set_timeout(id: Id, until: Option, db: &Connection) -> Result<(), ServerError> { + run( + db, + "UPDATE user SET suspended_until = ?2 WHERE id = ?1", + (id, until.map(|ms| ms as i64)), + ) + .await?; + + Ok(()) +} + +pub async fn set_last_ip(id: Id, ip: &str, db: &Connection) -> Result<(), ServerError> { + run(db, "UPDATE user SET last_ip = ?2 WHERE id = ?1", (id, ip)).await?; + + Ok(()) +} + +pub async fn last_ip(id: Id, db: &Connection) -> Result, ServerError> { + one(db, "SELECT last_ip FROM user WHERE id = ?1", (id,), |r| { + r.get() + }) + .await +} + +pub async fn builder_ids(db: &Connection) -> Result, ServerError> { + all( + db, + "SELECT id FROM user WHERE role = ?1", + (Role::Builder.as_str(),), + |r| r.get(), + ) + .await +} + +pub async fn set_suspended(id: Id, suspended: bool, db: &Connection) -> Result<(), ServerError> { + run( + db, + "UPDATE user SET suspended = ?2 WHERE id = ?1", + (id, suspended), + ) + .await?; + + Ok(()) +} + +pub async fn set_voice_muted(id: Id, muted: bool, db: &Connection) -> Result<(), ServerError> { + run( + db, + "UPDATE user SET voice_muted = ?2 WHERE id = ?1", + (id, muted), + ) + .await?; + + Ok(()) +} + +pub async fn set_ghost(id: Id, ghost: bool, db: &Connection) -> Result<(), ServerError> { + run(db, "UPDATE user SET ghost = ?2 WHERE id = ?1", (id, ghost)).await?; + + Ok(()) +} + +pub async fn is_ghost(id: Id, db: &Connection) -> Result { + Ok( + maybe(db, "SELECT ghost FROM user WHERE id = ?1", (id,), |r| { + r.get() + }) + .await? + .unwrap_or(false), + ) +} + +pub async fn presence(id: Id, db: &Connection) -> Result { + one(db, "SELECT presence FROM user WHERE id = ?1", (id,), |r| { + r.named() + }) + .await +} + +pub async fn update_presence( + id: Id, + presence: Presence, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "UPDATE user SET presence = ?2 WHERE id = ?1", + (id, presence.as_str()), + ) + .await?; + + Ok(()) +} + +pub async fn voice_muted(id: Id, db: &Connection) -> Result { + let (muted, role): (bool, Role) = one( + db, + "SELECT voice_muted, role FROM user WHERE id = ?1", + (id,), + |r| Ok((r.get()?, r.named()?)), + ) + .await?; + + Ok(muted && !permission::is_builder(role)) +} + +pub async fn set_password_hash( + id: Id, + password_hash: &str, + db: &Connection, +) -> Result<(), ServerError> { + run( + db, + "UPDATE user SET password_hash = ?2 WHERE id = ?1", + (id, password_hash), + ) + .await?; + + Ok(()) +} + +pub async fn all_accounts(db: &Connection) -> Result, ServerError> { + all( + db, + &format!("SELECT {COLUMNS}, user.suspended, user.last_seen, user.suspended_until, user.ghost FROM user ORDER BY user.username"), + (), + |r| { + Ok(Account { + user: row(r)?, + suspended: r.get()?, + last_seen: r.get()?, + suspended_until: r.get()?, + ghost: r.get()?, + }) + }, + ) + .await +} + +pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { + ensure_with( + run(db, "DELETE FROM user WHERE id = ?1", (id,)).await? == 1, + Error::NotFound, + ) +} + +#[cfg(test)] +mod tests { + use common::{error::Error, model::Role}; + + use crate::{db::user, error::ServerError, test}; + + #[tokio::test] + async fn read_by_username() { + let db = test::db().await; + let conn = db.lock().await.unwrap(); + + let created_user = user::create("Tahinli", "hash", Role::User, &conn) + .await + .unwrap(); + let _other_user = user::create("Not Tahinli", "hash", Role::User, &conn) + .await + .unwrap(); + + let searched_user = user::by_username("tahinli", &conn).await.unwrap(); + + assert_eq!(Some(created_user), searched_user); + } + + #[tokio::test] + async fn update_on_missing_user() { + let db = test::db().await; + let conn = db.lock().await.unwrap(); + + let updated_user = user::update(404, "Not Tahinli", &conn).await; + + assert!(matches!( + updated_user, + Err(ServerError::Wire(Error::NotFound)) + )); + } +} diff --git a/crates/server/src/direct.rs b/crates/server/src/direct.rs deleted file mode 100644 index 08106c9..0000000 --- a/crates/server/src/direct.rs +++ /dev/null @@ -1,51 +0,0 @@ -use common::model::{Community, Rank}; -use turso::Connection; - -use crate::{community, error::ServerError, request::ensure, user, user_community}; - -async fn find( - user_a: &str, - user_b: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", - (user_a, user_b), - ) - .await?; - - Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) -} - -pub enum Opening { - Created(Community), - Existing(Community), -} - -pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result { - ensure(me != other)?; - user::read(other, conn).await?; - - let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; - let tx = conn.transaction().await?; - if let Some(community_id) = find(user_a, user_b, &tx).await? { - let community = community::read(&community_id, me, &tx).await?; - tx.commit().await?; - - return Ok(Opening::Existing(community)); - } - - let community_id = community::create_fixed(community::Kind::Direct, &tx).await?; - user_community::join(me, &community_id, Rank::Member, &tx).await?; - user_community::join(other, &community_id, Rank::Member, &tx).await?; - tx.execute( - "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)", - (user_a, user_b, community_id.as_str()), - ) - .await?; - let community = community::read(&community_id, me, &tx).await?; - tx.commit().await?; - - Ok(Opening::Created(community)) -} diff --git a/crates/server/src/error.rs b/crates/server/src/error.rs index 4590661..56e62dc 100644 --- a/crates/server/src/error.rs +++ b/crates/server/src/error.rs @@ -21,6 +21,36 @@ impl From for common::error::Error { } } +impl From for ServerError { + fn from(error: turso::Error) -> Self { + match &error { + turso::Error::Constraint(message) + if message.starts_with("UNIQUE constraint failed") => + { + common::error::Error::Taken.into() + } + turso::Error::Constraint(message) + if message.starts_with("FOREIGN KEY constraint failed") => + { + common::error::Error::NotFound.into() + } + _ => ServerError::Internal(error.to_string()), + } + } +} + +pub fn ensure(condition: bool) -> Result<(), ServerError> { + ensure_with(condition, common::error::Error::Forbidden) +} + +pub fn ensure_with(condition: bool, error: common::error::Error) -> Result<(), ServerError> { + if !condition { + return Err(error.into()); + } + + Ok(()) +} + macro_rules! internal_from { ($($source:ty),+ $(,)?) => { $( @@ -36,7 +66,7 @@ macro_rules! internal_from { internal_from! { std::net::AddrParseError, std::io::Error, - turso::Error, + tokio::task::JoinError, quinn::ConnectionError, quinn::ReadError, quinn::ReadExactError, diff --git a/crates/server/src/files.rs b/crates/server/src/files.rs new file mode 100644 index 0000000..92d43d7 --- /dev/null +++ b/crates/server/src/files.rs @@ -0,0 +1,497 @@ +use std::{ + io::{BufReader, Cursor}, + path::{Path, PathBuf}, + time::{Duration, SystemTime}, +}; + +use common::{ + constant::{ + ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, AVATAR_SIZE, MAXIMUM_AVATAR_BYTES, + THUMBNAIL_SIZE, + }, + error::{Error as CommonError, Field, Problem}, + frame::{self, DOWN_MAX, Sending}, + model::{Attachment, AttachmentKind, Id, ServerSettings, User}, + open::{Blob, Upload}, + permission, + time::{HOUR_MILLIS, now_ms}, + validate::{validate_attachment_name, validate_attachment_size, validate_avatar_size}, +}; +use image::{ImageFormat, ImageReader, Limits}; +use quinn::{RecvStream, VarInt}; +use tokio::{ + fs::File, + io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, +}; +use tracing::error; + +use crate::{ + authentication::random_bytes, + backup, + db::{self, Db}, + error::{ServerError, ensure, ensure_with}, +}; + +const COLLECT_INTERVAL: Duration = Duration::from_secs(600); +const MAXIMUM_IMAGE_SIDE: u32 = 16384; +const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; +const THUMB_SUFFIX: &str = ".thumb"; +const FILE_NAME_BYTES: usize = 16; + +fn thumb_path(directory: &Path, file: &str) -> PathBuf { + directory.join(format!("{file}{THUMB_SUFFIX}")) +} + +fn remove_files(directory: &Path, file: &str) { + let _ = std::fs::remove_file(directory.join(file)); + let _ = std::fs::remove_file(thumb_path(directory, file)); +} + +fn media_kind(head: &[u8]) -> AttachmentKind { + if is_video(head) { + AttachmentKind::Video + } else if is_audio(head) { + AttachmentKind::Audio + } else { + AttachmentKind::File + } +} + +fn is_image(head: &[u8]) -> bool { + matches!( + image::guess_format(head), + Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) + ) +} + +fn is_video(head: &[u8]) -> bool { + head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) +} + +fn is_audio(head: &[u8]) -> bool { + head.starts_with(b"OggS") + || head.starts_with(b"fLaC") + || head.starts_with(b"ID3") + || head.starts_with(&[0xFF, 0xFB]) + || head.starts_with(&[0xFF, 0xF3]) + || head.starts_with(&[0xFF, 0xF2]) + || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE")) +} + +fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> { + let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?)) + .with_guessed_format() + .ok()?; + let mut limits = Limits::default(); + limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE); + limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE); + limits.max_alloc = Some(MAXIMUM_DECODE_BYTES); + reader.limits(limits); + let image = reader.decode().ok()?; + let (width, height) = (image.width(), image.height()); + + let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE { + image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE) + } else { + image + }; + let mut bytes = Cursor::new(Vec::new()); + fitted + .to_rgb8() + .write_to(&mut bytes, ImageFormat::Jpeg) + .ok()?; + std::fs::write(thumbnail, bytes.into_inner()).ok()?; + + Some((width, height)) +} + +pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> { + validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; + let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { + CommonError::Invalid { + field: Field::Avatar, + problem: Problem::NotJpeg, + } + })?; + if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { + return Err(CommonError::Invalid { + field: Field::Avatar, + problem: Problem::Dimensions { + expected: AVATAR_SIZE, + }, + } + .into()); + } + + Ok(()) +} + +async fn receive_body( + reader: &mut R, + path: &Path, + size: u64, +) -> Result, ServerError> { + let mismatch = |actual: u64| CommonError::Invalid { + field: Field::Attachment, + problem: Problem::Length { + min: size, + max: size, + actual, + }, + }; + let mut file = File::create(path).await?; + + let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize]; + reader.read_exact(&mut head).await?; + file.write_all(&head).await?; + + let mut received = head.len() as u64; + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; + loop { + let read = reader.read(&mut buffer).await?; + if read == 0 { + break; + } + + received += read as u64; + if received > size { + return Err(mismatch(received).into()); + } + file.write_all(&buffer[..read]).await?; + } + + if received != size { + return Err(mismatch(received).into()); + } + file.flush().await?; + + Ok(head) +} + +async fn ensure_quota( + user_id: Id, + community_id: Id, + size: u64, + settings: &ServerSettings, + db: &db::Connection, +) -> Result<(), ServerError> { + let (user_used, community_used) = db::attachment::quota(user_id, community_id, db).await?; + let over = |used: u64, limit: u64| limit != 0 && used.saturating_add(size) > limit; + ensure_with( + !over(user_used, settings.user_quota_bytes) + && !over(community_used, settings.community_quota_bytes), + CommonError::QuotaExceeded, + ) +} + +async fn write_file( + reader: &mut (impl AsyncRead + Unpin), + header: &Upload, + path: &Path, + thumbnail: PathBuf, +) -> Result<(AttachmentKind, Option, Option), ServerError> { + let head = receive_body(reader, path, header.size).await?; + let described = if is_image(&head) { + let source = path.to_path_buf(); + tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)).await? + } else { + None + }; + + Ok(match described { + Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)), + None => (media_kind(&head), None, None), + }) +} + +pub async fn store( + user: &User, + header: &Upload, + reader: &mut R, + db: &Db, + directory: &Path, +) -> Result { + let settings = db + .run(async |conn| { + let rank = permission::effective_rank( + user.role, + db::member::rank(user.id, header.community_id, conn).await?, + ); + ensure(permission::can_post(rank))?; + validate_attachment_name(&header.name)?; + let settings = db::settings::read(conn).await?; + validate_attachment_size(header.size, settings.max_attachment_bytes)?; + ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?; + + Ok(settings) + }) + .await?; + + let file: String = random_bytes::()? + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let path = directory.join(&file); + let (kind, width, height) = + match write_file(reader, header, &path, thumb_path(directory, &file)).await { + Ok(described) => described, + Err(error) => { + remove_files(directory, &file); + return Err(error); + } + }; + + let stored = db + .run(async |conn| { + ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?; + db::attachment::insert( + user.id, + header.community_id, + &file, + &header.name, + header.size, + kind, + width, + height, + conn, + ) + .await + }) + .await; + if stored.is_err() { + remove_files(directory, &file); + } + + stored +} + +pub async fn upload( + user: Option<&User>, + header: Upload, + mut receive_stream: RecvStream, + mut send_stream: Sending, + db: &Db, + directory: &Path, +) -> Result<(), ServerError> { + let stored = match user { + Some(user) => store(user, &header, &mut receive_stream, db, directory).await, + None => Err(CommonError::Unauthenticated.into()), + }; + let rejected = stored.is_err(); + let reply = stored.map_err(CommonError::from); + + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; + send_stream.finish()?; + if rejected { + let _ = receive_stream.stop(VarInt::from_u32(0)); + } + + Ok(()) +} + +async fn locate( + user: Option<&User>, + attachment_id: Id, + thumbnail: bool, + db: &Db, + directory: &Path, +) -> Result<(PathBuf, u64), ServerError> { + let user = user.ok_or(CommonError::Unauthenticated)?; + let stored = db + .run(async |conn| { + let stored = db::attachment::read(attachment_id, conn).await?; + let rank = permission::effective_rank( + user.role, + db::member::rank(user.id, stored.community_id, conn).await?, + ); + ensure(permission::can_read(rank))?; + ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; + + Ok(stored) + }) + .await?; + + let path = if thumbnail { + thumb_path(directory, &stored.file) + } else { + directory.join(&stored.file) + }; + let length = tokio::fs::metadata(&path) + .await + .map_err(|_| CommonError::NotFound)? + .len(); + + Ok((path, length)) +} + +pub async fn fetch( + user: Option<&User>, + blob: Blob, + mut send_stream: Sending, + db: &Db, + directory: &Path, + backups: &Path, +) -> Result<(), ServerError> { + let located = match &blob { + Blob::Attachment(id) => locate(user, *id, false, db, directory).await, + Blob::Thumbnail(id) => locate(user, *id, true, db, directory).await, + Blob::Backup(name) => backup::locate(user, name, db, backups).await, + }; + let located = located.map_err(CommonError::from); + let reply = located + .as_ref() + .map(|(_, length)| *length) + .map_err(Clone::clone); + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; + + if let Ok((path, _)) = located { + let mut file = File::open(path).await?; + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; + loop { + let read = file.read(&mut buffer).await?; + if read == 0 { + break; + } + send_stream.get().write_all(&buffer[..read]).await?; + } + } + send_stream.finish()?; + + Ok(()) +} + +pub async fn collect(db: Db, directory: PathBuf) { + let mut interval = tokio::time::interval(COLLECT_INTERVAL); + loop { + interval.tick().await; + if let Err(error) = sweep(&db, &directory).await { + error!("attachment sweep: {error}"); + } + } +} + +async fn sweep(db: &Db, directory: &Path) -> Result<(), ServerError> { + let stale_ms = now_ms().saturating_sub(HOUR_MILLIS); + let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); + + let files = db + .run(async |conn| { + db::attachment::delete_stale_unbound(stale_ms, conn).await?; + db::attachment::files(conn).await + }) + .await?; + + for entry in std::fs::read_dir(directory)? { + let Ok(entry) = entry else { continue }; + let name = entry.file_name().to_string_lossy().into_owned(); + let file = name.strip_suffix(THUMB_SUFFIX).unwrap_or(&name); + let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { + continue; + }; + + if modified < stale_at && !files.contains(file) { + let _ = std::fs::remove_file(entry.path()); + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use common::{ + constant::AVATAR_SIZE, + error::{Error as CommonError, Field}, + model::{AttachmentKind, Rank, Role}, + open::Upload, + }; + use image::{ImageFormat, RgbImage}; + + use super::{check_avatar, store, thumb_path}; + use crate::{db, error::ServerError, test}; + + fn jpeg(size: u32) -> Vec { + let mut bytes = Cursor::new(Vec::new()); + RgbImage::new(size, size) + .write_to(&mut bytes, ImageFormat::Jpeg) + .unwrap(); + + bytes.into_inner() + } + + #[test] + fn avatar_checks_jpeg_size() { + let small = check_avatar(&jpeg(AVATAR_SIZE / 2)); + let not_jpeg = check_avatar(b"not a jpeg"); + + assert!(matches!( + small, + Err(ServerError::Wire(CommonError::Invalid { + field: Field::Avatar, + .. + })) + )); + assert!(matches!( + not_jpeg, + Err(ServerError::Wire(CommonError::Invalid { + field: Field::Avatar, + .. + })) + )); + assert!(check_avatar(&jpeg(AVATAR_SIZE)).is_ok()); + } + + #[tokio::test] + async fn upload_then_read_in_message() { + let db = test::db().await; + let (user, community) = { + let conn = db.lock().await.unwrap(); + let user = db::user::create("Tahinli", "hash", Role::User, &conn) + .await + .unwrap(); + let community_id = db::community::create(db::community::Kind::Group, "Tahinli", &conn) + .await + .unwrap(); + db::member::join(user.id, community_id, Rank::Member, &conn) + .await + .unwrap(); + + (user, community_id) + }; + + let mut png = Cursor::new(Vec::new()); + RgbImage::new(2, 3) + .write_to(&mut png, ImageFormat::Png) + .unwrap(); + let png = png.into_inner(); + let directory = test::directory(); + let header = Upload { + community_id: community, + name: "pixel.png".to_string(), + size: png.len() as u64, + }; + let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) + .await + .unwrap(); + + let conn = db.lock().await.unwrap(); + db::message::create(user.id, community, "", &[attachment.id], None, &conn) + .await + .unwrap(); + let messages = db::message::read_page(community, None, &conn) + .await + .unwrap(); + assert_eq!(vec![attachment.clone()], messages[0].attachments); + assert_eq!(AttachmentKind::Image, attachment.kind); + assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); + + let file = db::attachment::read(attachment.id, &conn) + .await + .unwrap() + .file; + std::fs::remove_file(directory.join(&file)).unwrap(); + std::fs::remove_file(thumb_path(&directory, &file)).unwrap(); + } +} diff --git a/crates/server/src/friend.rs b/crates/server/src/friend.rs deleted file mode 100644 index 6dd3876..0000000 --- a/crates/server/src/friend.rs +++ /dev/null @@ -1,141 +0,0 @@ -use common::{ - error::Error as CommonError, - model::{Friends, User}, -}; -use turso::Connection; - -use crate::{database, error::ServerError, request::ensure_with, user}; - -async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn.query(sql, (user_id,)).await?; - - let mut users = Vec::new(); - while let Some(row) = rows.next().await? { - users.push(user::from_row(&row)?); - } - - Ok(users) -} - -async fn pair_exists( - sql: &str, - first: &str, - second: &str, - conn: &Connection, -) -> Result { - database::exists(conn, sql, (first, second)).await -} - -async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result { - pair_exists( - "SELECT COUNT(*) FROM friend WHERE user_id = ?1 AND friend_id = ?2", - me, - other, - conn, - ) - .await -} - -async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result { - pair_exists( - "SELECT COUNT(*) FROM friend_request WHERE from_id = ?1 AND to_id = ?2", - from, - to, - conn, - ) - .await -} - -async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), ServerError> { - conn.execute( - "DELETE FROM friend_request WHERE from_id = ?1 AND to_id = ?2", - (other, me), - ) - .await?; - conn.execute( - "INSERT INTO friend (user_id, friend_id) VALUES (?1, ?2)", - (me, other), - ) - .await?; - conn.execute( - "INSERT INTO friend (user_id, friend_id) VALUES (?1, ?2)", - (other, me), - ) - .await?; - - Ok(()) -} - -pub async fn state(user_id: &str, conn: &Connection) -> Result { - Ok(Friends { - friends: users( - &format!("SELECT {} FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 ORDER BY user.id", user::user_columns("user")), - user_id, - conn, - ) - .await?, - incoming: users( - &format!("SELECT {} FROM user JOIN friend_request ON friend_request.from_id = user.id WHERE friend_request.to_id = ?1 ORDER BY user.id", user::user_columns("user")), - user_id, - conn, - ) - .await?, - outgoing: users( - &format!("SELECT {} FROM user JOIN friend_request ON friend_request.to_id = user.id WHERE friend_request.from_id = ?1 ORDER BY user.id", user::user_columns("user")), - user_id, - conn, - ) - .await?, - }) -} - -pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { - ensure_with(me != other, CommonError::Forbidden)?; - user::read(other, conn).await?; - - let tx = conn.transaction().await?; - ensure_with( - !(is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await?), - CommonError::Taken, - )?; - if is_requested(other, me, &tx).await? { - befriend(me, other, &tx).await?; - } else { - tx.execute( - "INSERT INTO friend_request (from_id, to_id) VALUES (?1, ?2)", - (me, other), - ) - .await?; - } - tx.commit().await?; - - Ok(()) -} - -pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { - let tx = conn.transaction().await?; - if !is_requested(other, me, &tx).await? { - return Err(CommonError::NotFound.into()); - } - befriend(me, other, &tx).await?; - tx.commit().await?; - - Ok(()) -} - -pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { - let tx = conn.transaction().await?; - tx.execute( - "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)", - (me, other), - ) - .await?; - tx.execute( - "DELETE FROM friend_request WHERE (from_id = ?1 AND to_id = ?2) OR (from_id = ?2 AND to_id = ?1)", - (me, other), - ) - .await?; - tx.commit().await?; - - Ok(()) -} diff --git a/crates/server/src/hub.rs b/crates/server/src/hub.rs index e02ce09..5ff67cc 100644 --- a/crates/server/src/hub.rs +++ b/crates/server/src/hub.rs @@ -7,7 +7,7 @@ use std::{ }; use bytes::Bytes; -use common::transport::Close; +use common::{model::Id, transport::Close}; use quinn::Connection; use tokio::sync::mpsc::{self, error::TrySendError}; use tracing::warn; @@ -19,8 +19,8 @@ const QUEUE_LENGTH: usize = 256; static NEXT_ID: AtomicU64 = AtomicU64::new(1); pub struct Signed { - pub user_id: String, - pub token: String, + pub user_id: Id, + pub session_id: Id, } pub struct Client { @@ -29,8 +29,8 @@ pub struct Client { pub me: Option, tx: mpsc::Sender, pub closed: AtomicBool, - watching: Mutex>, - ghost_logged: Mutex>, + watching: Mutex>, + ghost_logged: Mutex>, } impl Client { @@ -53,8 +53,8 @@ impl Client { Self::new(None, me).0 } - pub fn user_id(&self) -> Option<&str> { - self.me.as_ref().map(|me| me.user_id.as_str()) + pub fn user_id(&self) -> Option { + self.me.as_ref().map(|me| me.user_id) } pub fn close(&self, close: Close) { @@ -63,22 +63,19 @@ impl Client { } } - pub fn first_visit(&self, community_id: &str) -> bool { - self.ghost_logged - .lock() - .unwrap() - .insert(community_id.to_string()) + pub fn first_visit(&self, community_id: Id) -> bool { + self.ghost_logged.lock().unwrap().insert(community_id) } - pub fn watch(&self, community_id: Option<&str>) { - *self.watching.lock().unwrap() = community_id.map(str::to_string); + pub fn watch(&self, community_id: Option) { + *self.watching.lock().unwrap() = community_id; } } pub enum Presence { None, - Online(String), - Offline(String), + Online(Id), + Offline(Id), } #[derive(Clone, Default)] @@ -87,10 +84,8 @@ pub struct Hub(Arc>>>); impl Hub { pub fn add(&self, client: Arc) -> Presence { let mut clients = self.0.lock().unwrap(); - let user_id = client.user_id().map(str::to_string); - let was_online = user_id - .as_deref() - .is_some_and(|user_id| Self::online_in(&clients, user_id)); + let user_id = client.user_id(); + let was_online = user_id.is_some_and(|user_id| Self::online_in(&clients, user_id)); clients.insert(client.id, client); match user_id { @@ -106,26 +101,24 @@ impl Hub { }; match client.user_id() { - Some(user_id) if !Self::online_in(&clients, user_id) => { - Presence::Offline(user_id.to_string()) - } + Some(user_id) if !Self::online_in(&clients, user_id) => Presence::Offline(user_id), _ => Presence::None, } } - fn online_in(clients: &HashMap>, user_id: &str) -> bool { + fn online_in(clients: &HashMap>, user_id: Id) -> bool { clients .values() .any(|client| client.user_id() == Some(user_id)) } - pub fn is_online(&self, user_id: &str) -> bool { + pub fn is_online(&self, user_id: Id) -> bool { Self::online_in(&self.0.lock().unwrap(), user_id) } pub fn online(&self) -> usize { let clients = self.0.lock().unwrap(); - let ids: HashSet<&str> = clients + let ids: HashSet = clients .values() .filter_map(|client| client.user_id()) .collect(); @@ -133,26 +126,22 @@ impl Hub { ids.len() } - pub fn conns_of(&self, user_ids: &[String]) -> Vec { + pub fn conns_of(&self, user_ids: &[Id]) -> Vec { self.0 .lock() .unwrap() .values() - .filter(|client| { - client - .user_id() - .is_some_and(|id| user_ids.iter().any(|u| u == id)) - }) + .filter(|client| client.user_id().is_some_and(|id| user_ids.contains(&id))) .map(|client| client.id) .collect() } - pub fn watchers(&self, community_id: &str) -> Vec { + pub fn watchers(&self, community_id: Id) -> Vec { self.0 .lock() .unwrap() .values() - .filter(|client| client.watching.lock().unwrap().as_deref() == Some(community_id)) + .filter(|client| *client.watching.lock().unwrap() == Some(community_id)) .map(|client| client.id) .collect() } @@ -192,15 +181,15 @@ impl Hub { } } - pub fn kick_user(&self, user_id: &str, close: Close) { + pub fn kick_user(&self, user_id: Id, close: Close) { self.kick_where(|me| me.user_id == user_id, close); } - pub fn kick_token(&self, token: &str, close: Close) { - self.kick_where(|me| me.token == token, close); + pub fn kick_session(&self, session_id: Id, close: Close) { + self.kick_where(|me| me.session_id == session_id, close); } - pub fn kick_all_except(&self, keep: &[String], close: Close) { + pub fn kick_all_except(&self, keep: &[Id], close: Close) { self.kick_where(|me| !keep.contains(&me.user_id), close); } } diff --git a/crates/server/src/invitation.rs b/crates/server/src/invitation.rs deleted file mode 100644 index 271fdd0..0000000 --- a/crates/server/src/invitation.rs +++ /dev/null @@ -1,72 +0,0 @@ -use common::{error::Error as CommonError, model::Invitation}; -use turso::Connection; - -use crate::{community, database, error::ServerError, user}; - -pub async fn of(user_id: &str, conn: &Connection) -> Result, ServerError> { - let pairs = { - let mut rows = conn - .query( - "SELECT community_id, inviter_id FROM invitation WHERE user_id = ?1 ORDER BY community_id", - (user_id,), - ) - .await?; - - let mut pairs: Vec<(String, String)> = Vec::new(); - while let Some(row) = rows.next().await? { - pairs.push((row.get(0)?, row.get(1)?)); - } - - pairs - }; - - let mut invitations = Vec::new(); - for (community_id, inviter_id) in pairs { - invitations.push(Invitation { - community: community::read(&community_id, user_id, conn).await?, - inviter: user::read(&inviter_id, conn).await?, - }); - } - - Ok(invitations) -} - -pub async fn exists( - community_id: &str, - user_id: &str, - conn: &Connection, -) -> Result { - database::exists( - conn, - "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", - (community_id, user_id), - ) - .await -} - -pub async fn insert( - community_id: &str, - user_id: &str, - inviter_id: &str, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", - (community_id, user_id, inviter_id), - ) - .await?; - - Ok(()) -} - -pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), ServerError> { - let mut rows = conn - .query( - "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2 RETURNING community_id", - (community_id, user_id), - ) - .await?; - rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(()) -} diff --git a/crates/server/src/invite.rs b/crates/server/src/invite.rs deleted file mode 100644 index 6adc211..0000000 --- a/crates/server/src/invite.rs +++ /dev/null @@ -1,89 +0,0 @@ -use common::{ - error::Error as CommonError, - model::{InviteCode, User}, - time::{self, HOUR_MILLIS}, -}; -use turso::Connection; - -use crate::{authentication, error::ServerError}; - -const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; -const CODE_LENGTH: usize = 8; - -fn generate() -> Result { - let bytes = authentication::random_bytes::()?; - - Ok(bytes - .iter() - .map(|byte| char::from(ALPHABET[usize::from(*byte) % ALPHABET.len()])) - .collect()) -} - -pub async fn create( - uses: u32, - hours: Option, - created_by: &User, - conn: &Connection, -) -> Result { - let code = generate()?; - let expires_at = hours.map(|hours| time::now_ms() + u64::from(hours) * HOUR_MILLIS); - conn.execute( - "INSERT INTO invite_code (code, uses_left, expires_at, created_by) VALUES (?1, ?2, ?3, ?4)", - ( - code.as_str(), - i64::from(uses), - expires_at.map(|millis| millis as i64), - created_by.id.as_str(), - ), - ) - .await?; - - Ok(InviteCode { - code, - uses_left: uses, - expires_at, - }) -} - -pub async fn list(conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query("SELECT code, uses_left, expires_at FROM invite_code", ()) - .await?; - - let mut codes = Vec::new(); - while let Some(row) = rows.next().await? { - let uses_left: i64 = row.get(1)?; - let expires_at: Option = row.get(2)?; - codes.push(InviteCode { - code: row.get(0)?, - uses_left: uses_left as u32, - expires_at: expires_at.map(|millis| millis as u64), - }); - } - - Ok(codes) -} - -pub async fn delete(code: &str, conn: &Connection) -> Result<(), ServerError> { - let mut rows = conn - .query( - "DELETE FROM invite_code WHERE code = ?1 RETURNING code", - (code,), - ) - .await?; - rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(()) -} - -pub async fn consume(code: &str, conn: &Connection) -> Result<(), ServerError> { - let mut rows = conn - .query( - "UPDATE invite_code SET uses_left = uses_left - 1 WHERE code = ?1 AND uses_left > 0 AND (expires_at IS NULL OR expires_at > ?2) RETURNING code", - (code, time::now_ms() as i64), - ) - .await?; - rows.next().await?.ok_or(CommonError::RegistrationClosed)?; - - Ok(()) -} diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index d84f0c2..fc3780d 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -1,34 +1,18 @@ -pub mod admin_log; -pub mod attachment; pub mod authentication; pub mod backup; pub mod call; pub mod certificate; -pub mod community; -pub mod database; pub mod datagram; -pub mod direct; +pub mod db; pub mod error; -pub mod friend; +pub mod files; pub mod hub; -pub mod invitation; -pub mod invite; -pub mod log; -pub mod message; pub mod network; -pub mod notes; -pub mod overview; pub mod publish; pub mod rate_limit; -pub mod report; pub mod request; pub mod retention; pub mod rooms; -pub mod server_ban; -pub mod server_settings; -pub mod stats; -pub mod user; -pub mod user_community; #[cfg(test)] mod test; @@ -37,7 +21,7 @@ use std::path::{Path, PathBuf}; use common::{config::Config, error::Error as CommonError, model::Role}; -use crate::error::ServerError; +use crate::{db::Db, error::ServerError}; const SERVER_CONFIG_FILE_PATH: &str = concat!( env!("CARGO_MANIFEST_DIR"), @@ -84,11 +68,11 @@ pub async fn showtime() -> Result<(), ServerError> { let config = load_config()?; - let database = database::open(&config.database_path).await?; + let database = Db::open(&config.database_path).await?; let certificate = certificate::load(&config.certificate_path, &config.key_path)?; let attachments = sibling_directory(&config.database_path, "attachments")?; let backups = sibling_directory(&config.database_path, "backups")?; - tokio::spawn(attachment::collect(database.clone(), attachments.clone())); + tokio::spawn(files::collect(database.clone(), attachments.clone())); network::serve( &config.server_address, @@ -102,12 +86,15 @@ pub async fn showtime() -> Result<(), ServerError> { pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> { let config = load_config()?; - let database = database::open(&config.database_path).await?; - let conn = database::connect(&database).await?; - let user = user::by_username(username, &conn) - .await? - .ok_or(CommonError::NotFound)?; - user::set_role_by_id(&user.id, role, &conn).await?; - - Ok(()) + let database = Db::open(&config.database_path).await?; + database + .run(async |db| { + let user = db::user::by_username(username, db) + .await? + .ok_or(CommonError::NotFound)?; + db::user::set_role_by_id(user.id, role, db).await?; + + Ok(()) + }) + .await } diff --git a/crates/server/src/log.rs b/crates/server/src/log.rs deleted file mode 100644 index 5881225..0000000 --- a/crates/server/src/log.rs +++ /dev/null @@ -1,105 +0,0 @@ -use common::{ - constant::LOG_PAGE_LIMIT, - model::{LogAction, LogEntry, Rank}, -}; -use turso::Connection; - -use crate::{database::new_id, error::ServerError, user}; - -common::string_enum! { - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - Kind { - Created => "created", - Renamed => "renamed", - AvatarChanged => "avatar_changed", - AvatarRemoved => "avatar_removed", - Invited => "invited", - Joined => "joined", - Left => "left", - Kicked => "kicked", - Banned => "banned", - Unbanned => "unbanned", - RankChanged => "rank_changed", - MessageDeleted => "message_deleted", - } -} - -fn parts(action: &LogAction) -> (&'static str, Option) { - let (kind, detail) = match action { - LogAction::Created => (Kind::Created, None), - LogAction::Renamed { name } => (Kind::Renamed, Some(name.clone())), - LogAction::AvatarChanged => (Kind::AvatarChanged, None), - LogAction::AvatarRemoved => (Kind::AvatarRemoved, None), - LogAction::Invited => (Kind::Invited, None), - LogAction::Joined => (Kind::Joined, None), - LogAction::Left => (Kind::Left, None), - LogAction::Kicked { reason } => (Kind::Kicked, reason.clone()), - LogAction::Banned { reason } => (Kind::Banned, reason.clone()), - LogAction::Unbanned => (Kind::Unbanned, None), - LogAction::RankChanged { rank } => (Kind::RankChanged, Some(rank.as_str().to_string())), - LogAction::MessageDeleted => (Kind::MessageDeleted, None), - }; - (kind.as_str(), detail) -} - -fn action_of(text: &str, detail: Option) -> Option { - Some(match Kind::parse(text)? { - Kind::Created => LogAction::Created, - Kind::Renamed => LogAction::Renamed { name: detail? }, - Kind::AvatarChanged => LogAction::AvatarChanged, - Kind::AvatarRemoved => LogAction::AvatarRemoved, - Kind::Invited => LogAction::Invited, - Kind::Joined => LogAction::Joined, - Kind::Left => LogAction::Left, - Kind::Kicked => LogAction::Kicked { reason: detail }, - Kind::Banned => LogAction::Banned { reason: detail }, - Kind::Unbanned => LogAction::Unbanned, - Kind::RankChanged => LogAction::RankChanged { - rank: Rank::parse(&detail?)?, - }, - Kind::MessageDeleted => LogAction::MessageDeleted, - }) -} - -pub async fn record( - community_id: &str, - actor_id: Option<&str>, - target_id: Option<&str>, - action: &LogAction, - conn: &Connection, -) -> Result<(), ServerError> { - let id = new_id(); - let (action, detail) = parts(action); - conn.execute( - "INSERT INTO community_log (id, community_id, actor_id, target_id, action, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - (id.as_str(), community_id, actor_id, target_id, action, detail.as_deref()), - ) - .await?; - - Ok(()) -} - -pub async fn list(community_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT l.id, l.action, l.detail, {}, {} FROM community_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE l.community_id = ?1 ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")), - (community_id,), - ) - .await?; - - let mut entries = Vec::new(); - while let Some(row) = rows.next().await? { - let text: String = row.get(1)?; - let Some(action) = action_of(&text, row.get(2)?) else { - continue; - }; - entries.push(LogEntry { - id: row.get(0)?, - actor: user::from_row_at(&row, 3)?, - target: user::from_row_at(&row, 8)?, - action, - }); - } - - Ok(entries) -} diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs deleted file mode 100644 index 23fcf81..0000000 --- a/crates/server/src/message.rs +++ /dev/null @@ -1,860 +0,0 @@ -use std::{collections::HashMap, path::Path}; - -use common::{ - constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, - error::{Error as CommonError, Field, Problem}, - model::{ - CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage, - User, - }, - time, -}; -use turso::{Connection, Row}; - -use crate::{attachment, community, database, database::new_id, error::ServerError, user}; - -const SEARCH_LIMIT: usize = 200; - -const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned FROM message m LEFT JOIN message r ON r.id = m.reply_to"; - -fn from_row(row: &Row) -> Result { - let edited: i64 = row.get(4)?; - let call_seconds: i64 = row.get(10)?; - let pinned: i64 = row.get(11)?; - let call = row - .get::>(9)? - .and_then(|text| CallLog::parse(&text, call_seconds as u64)); - let reply = match row.get::>(5)? { - Some(message_id) => { - let body: String = row.get(7)?; - let attachments: i64 = row.get(8)?; - Some(Quote { - message_id, - user_id: row.get(6)?, - body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(), - attachments: attachments as usize, - }) - } - None => None, - }; - - Ok(Message { - id: row.get(0)?, - user_id: row.get(1)?, - community_id: row.get(2)?, - body: row.get(3)?, - attachments: Vec::new(), - reactions: Vec::new(), - reply, - snippet: None, - poll: None, - edited: edited != 0, - pinned: pinned != 0, - call, - }) -} - -fn placeholders(count: usize) -> String { - (1..=count) - .map(|index| format!("?{index}")) - .collect::>() - .join(", ") -} - -async fn reactions_of( - message_ids: &[String], - conn: &Connection, -) -> Result>, ServerError> { - let mut reactions: HashMap> = HashMap::new(); - if message_ids.is_empty() { - return Ok(reactions); - } - - let placeholders = placeholders(message_ids.len()); - let mut rows = conn - .query( - &format!( - "SELECT message_id, emoji, user_id FROM reaction WHERE message_id IN ({placeholders}) ORDER BY message_id, emoji, user_id" - ), - message_ids.to_vec(), - ) - .await?; - - while let Some(row) = rows.next().await? { - let message_id: String = row.get(0)?; - let emoji: String = row.get(1)?; - let user_id: String = row.get(2)?; - let entries = reactions.entry(message_id).or_default(); - match entries - .last_mut() - .filter(|reaction| reaction.emoji == emoji) - { - Some(reaction) => reaction.user_ids.push(user_id), - None => entries.push(Reaction { - emoji, - user_ids: vec![user_id], - }), - } - } - - Ok(reactions) -} - -async fn polls_of( - message_ids: &[String], - conn: &Connection, -) -> Result, ServerError> { - let mut polls: HashMap = HashMap::new(); - if message_ids.is_empty() { - return Ok(polls); - } - - let placeholders = placeholders(message_ids.len()); - let mut rows = conn - .query( - &format!( - "SELECT message_id, question, multiple, closed FROM poll WHERE message_id IN ({placeholders})" - ), - message_ids.to_vec(), - ) - .await?; - while let Some(row) = rows.next().await? { - let multiple: i64 = row.get(2)?; - let closed: i64 = row.get(3)?; - polls.insert( - row.get(0)?, - Poll { - question: row.get(1)?, - options: Vec::new(), - multiple: multiple != 0, - closed: closed != 0, - }, - ); - } - drop(rows); - - let mut rows = conn - .query( - &format!( - "SELECT message_id, text FROM poll_option WHERE message_id IN ({placeholders}) ORDER BY message_id, position" - ), - message_ids.to_vec(), - ) - .await?; - while let Some(row) = rows.next().await? { - let message_id: String = row.get(0)?; - if let Some(poll) = polls.get_mut(&message_id) { - poll.options.push(PollOption { - text: row.get(1)?, - voter_ids: Vec::new(), - }); - } - } - drop(rows); - - let mut rows = conn - .query( - &format!( - "SELECT message_id, position, user_id FROM poll_vote WHERE message_id IN ({placeholders}) ORDER BY message_id, position, user_id" - ), - message_ids.to_vec(), - ) - .await?; - while let Some(row) = rows.next().await? { - let message_id: String = row.get(0)?; - let position: i64 = row.get(1)?; - let option = polls - .get_mut(&message_id) - .and_then(|poll| poll.options.get_mut(position as usize)); - if let Some(option) = option { - option.voter_ids.push(row.get(2)?); - } - } - - Ok(polls) -} - -async fn snippet_of(message_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT origin FROM snippet WHERE message_id = ?1", - (message_id,), - ) - .await?; - let Some(row) = rows.next().await? else { - return Ok(None); - }; - let origin: Option = row.get(0)?; - drop(rows); - - let mut rows = conn - .query( - "SELECT position, original_id, user_id, username, avatar_id, body, poll FROM snippet_message WHERE message_id = ?1 ORDER BY position", - (message_id,), - ) - .await?; - let mut entries = Vec::new(); - while let Some(row) = rows.next().await? { - let position: i64 = row.get(0)?; - entries.push(( - position, - SnippetMessage { - id: row.get(1)?, - user_id: row.get(2)?, - username: row.get(3)?, - avatar_id: row.get(4)?, - body: row.get(5)?, - attachments: Vec::new(), - poll: row - .get::>>(6)? - .and_then(|bytes| bitcode::decode(&bytes).ok()), - }, - )); - } - drop(rows); - - let mut messages = Vec::new(); - for (position, mut entry) in entries { - entry.attachments = attachment::of_message(message_id, Some(position), conn).await?; - messages.push(entry); - } - - Ok(Some(Snippet { origin, messages })) -} - -async fn hydrate(messages: Vec, conn: &Connection) -> Result, ServerError> { - let ids: Vec = messages.iter().map(|message| message.id.clone()).collect(); - let mut reactions = reactions_of(&ids, conn).await?; - let mut polls = polls_of(&ids, conn).await?; - - let mut hydrated = Vec::new(); - for mut message in messages { - message.reactions = reactions.remove(&message.id).unwrap_or_default(); - message.poll = polls.remove(&message.id); - message.attachments = attachment::of_message(&message.id, None, conn).await?; - message.snippet = snippet_of(&message.id, conn).await?; - hydrated.push(message); - } - - Ok(hydrated) -} - -async fn insert( - user_id: &str, - community_id: &str, - body: &str, - reply_to: Option<&str>, - conn: &Connection, -) -> Result { - let message_id = new_id(); - conn.execute( - "INSERT INTO message (id, user_id, community_id, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5)", - (message_id.as_str(), user_id, community_id, body, reply_to), - ) - .await?; - - Ok(message_id) -} - -pub async fn ensure_in_community( - message_id: &str, - community_id: &str, - conn: &Connection, -) -> Result<(), ServerError> { - let mut rows = conn - .query( - "SELECT id FROM message WHERE id = ?1 AND community_id = ?2", - (message_id, community_id), - ) - .await?; - if rows.next().await?.is_none() { - return Err(CommonError::NotFound.into()); - } - - Ok(()) -} - -pub async fn create_call_log( - community_id: &str, - user_id: &str, - call: CallLog, - conn: &Connection, -) -> Result { - let message_id = new_id(); - conn.execute( - "INSERT INTO message (id, user_id, community_id, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5)", - ( - message_id.as_str(), - user_id, - community_id, - call.as_str(), - call.seconds() as i64, - ), - ) - .await?; - - read(&message_id, conn).await -} - -pub async fn create( - user_id: &str, - community_id: &str, - body: &str, - attachments: &[String], - reply_to: Option<&str>, - conn: &Connection, -) -> Result { - if let Some(reply_to) = reply_to { - ensure_in_community(reply_to, community_id, conn).await?; - } - - let message_id = insert(user_id, community_id, body, reply_to, conn).await?; - attachment::bind(&message_id, user_id, community_id, attachments, conn).await?; - - read(&message_id, conn).await -} - -pub async fn read(message_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query(&format!("{SELECT} WHERE m.id = ?1"), (message_id,)) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let message = from_row(&row)?; - drop(rows); - - hydrate(vec![message], conn) - .await? - .pop() - .ok_or(CommonError::NotFound.into()) -} - -pub async fn read_page( - community_id: &str, - before: Option<&str>, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - &format!( - "{SELECT} WHERE m.community_id = ?1 AND (?2 IS NULL OR m.id < ?2) ORDER BY m.id DESC LIMIT ?3" - ), - (community_id, before, MESSAGE_PAGE_LIMIT as i64), - ) - .await?; - - let mut messages = Vec::new(); - while let Some(row) = rows.next().await? { - messages.push(from_row(&row)?); - } - drop(rows); - messages.reverse(); - - hydrate(messages, conn).await -} - -pub async fn create_poll( - user_id: &str, - community_id: &str, - question: &str, - options: &[String], - multiple: bool, - conn: &Connection, -) -> Result { - let message_id = insert(user_id, community_id, "", None, conn).await?; - conn.execute( - "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", - (message_id.as_str(), question, multiple as i64), - ) - .await?; - for (position, text) in options.iter().enumerate() { - conn.execute( - "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)", - (message_id.as_str(), position as i64, text.as_str()), - ) - .await?; - } - - read(&message_id, conn).await -} - -pub async fn vote( - message_id: &str, - user_id: &str, - positions: &[u32], - conn: &Connection, -) -> Result { - conn.execute( - "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", - (message_id, user_id), - ) - .await?; - for position in positions { - conn.execute( - "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)", - (message_id, *position as i64, user_id), - ) - .await?; - } - - read(message_id, conn).await -} - -pub async fn close_poll(message_id: &str, conn: &Connection) -> Result { - let updated = conn - .execute( - "UPDATE poll SET closed = 1 WHERE message_id = ?1", - (message_id,), - ) - .await?; - database::expect_one(updated)?; - - read(message_id, conn).await -} - -pub async fn react( - message_id: &str, - user_id: &str, - emoji: &str, - conn: &Connection, -) -> Result { - let removed = conn - .execute( - "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", - (message_id, user_id, emoji), - ) - .await?; - if removed == 0 { - conn.execute( - "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)", - (message_id, user_id, emoji), - ) - .await?; - } - - read(message_id, conn).await -} - -pub async fn pin( - message_id: &str, - pinned: bool, - conn: &Connection, -) -> Result { - conn.execute( - "UPDATE message SET pinned = ?2 WHERE id = ?1", - (message_id, pinned as i64), - ) - .await?; - - read(message_id, conn).await -} - -pub async fn pinned(community_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("{SELECT} WHERE m.community_id = ?1 AND m.pinned = 1 ORDER BY m.id DESC"), - (community_id,), - ) - .await?; - - let mut messages = Vec::new(); - while let Some(row) = rows.next().await? { - messages.push(from_row(&row)?); - } - drop(rows); - - hydrate(messages, conn).await -} - -pub async fn update( - message_id: &str, - body: &str, - conn: &Connection, -) -> Result { - let updated = conn - .execute( - "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1", - (message_id, body), - ) - .await?; - database::expect_one(updated)?; - - read(message_id, conn).await -} - -pub async fn delete(message_id: &str, conn: &Connection) -> Result { - let message = read(message_id, conn).await?; - conn.execute("DELETE FROM message WHERE id = ?1", (message_id,)) - .await?; - - Ok(message) -} - -pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result, ServerError> { - database::ids( - conn, - "SELECT id FROM message WHERE user_id = ?1", - (user_id,), - ) - .await -} - -pub async fn search( - text: Option<&str>, - user_id: Option<&str>, - community_id: Option<&str>, - after_ms: Option, - before_ms: Option, - conn: &Connection, -) -> Result, ServerError> { - let (after, before) = time::range_bounds(after_ms, before_ms); - let mut rows = conn - .query( - "SELECT id FROM message WHERE (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR id >= ?4) AND (?5 IS NULL OR id < ?5) ORDER BY id DESC LIMIT ?6", - ( - text, - user_id, - community_id, - after, - before, - SEARCH_LIMIT as i64, - ), - ) - .await?; - - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get::(0)?); - } - drop(rows); - - let mut hits = Vec::new(); - for id in ids { - let message = read(&id, conn).await?; - let community = community::label(&message.community_id, conn).await?; - let author = user::read(&message.user_id, conn).await?; - hits.push(MessageHit { - message, - community, - author: Some(author), - }); - } - - Ok(hits) -} - -async fn origin(sources: &[Message], conn: &Connection) -> Result, ServerError> { - let Some(first) = sources.first() else { - return Ok(None); - }; - let community_id = &first.community_id; - if sources - .iter() - .any(|source| &source.community_id != community_id) - { - return Ok(None); - } - - let mut rows = conn - .query( - "SELECT name FROM community WHERE id = ?1 AND kind = ?2", - (community_id.as_str(), community::Kind::Group.as_str()), - ) - .await?; - Ok(match rows.next().await? { - Some(row) => Some(row.get(0)?), - None => None, - }) -} - -async fn entry(source: &Message, conn: &Connection) -> Result { - let author: User = user::read(&source.user_id, conn).await?; - - Ok(SnippetMessage { - id: source.id.clone(), - user_id: author.id, - username: author.username, - avatar_id: author.avatar_id, - body: source.body.clone(), - attachments: source.attachments.clone(), - poll: source.poll.clone(), - }) -} - -async fn write_snippet( - message_id: &str, - user_id: &str, - community_id: &str, - origin: Option<&str>, - entries: &[SnippetMessage], - directory: &Path, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)", - (message_id, origin), - ) - .await?; - - for (position, entry) in entries.iter().enumerate() { - let position = position as i64; - let poll = entry.poll.as_ref().map(bitcode::encode); - conn.execute( - "INSERT INTO snippet_message (message_id, position, original_id, user_id, username, avatar_id, body, poll) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", - ( - message_id, - position, - entry.id.as_str(), - entry.user_id.as_str(), - entry.username.as_str(), - entry.avatar_id.as_deref(), - entry.body.as_str(), - poll, - ), - ) - .await?; - for attachment in &entry.attachments { - attachment::copy( - attachment, - message_id, - user_id, - community_id, - Some(position), - directory, - conn, - ) - .await?; - } - } - - Ok(()) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ForwardMode { - Copy, - Snippet, -} - -pub async fn forward( - user: &User, - community_id: &str, - sources: &[Message], - mode: ForwardMode, - directory: &Path, - conn: &Connection, -) -> Result, ServerError> { - if mode == ForwardMode::Copy { - let mut created = Vec::new(); - for source in sources { - let message_id = insert(&user.id, community_id, &source.body, None, conn).await?; - for attachment in &source.attachments { - attachment::copy( - attachment, - &message_id, - &user.id, - community_id, - None, - directory, - conn, - ) - .await?; - } - if let Some(inner) = &source.snippet { - write_snippet( - &message_id, - &user.id, - community_id, - inner.origin.as_deref(), - &inner.messages, - directory, - conn, - ) - .await?; - } - created.push(read(&message_id, conn).await?); - } - - return Ok(created); - } - - let mut entries = Vec::new(); - for source in sources { - match &source.snippet { - Some(inner) => entries.extend(inner.messages.iter().cloned()), - None => entries.push(entry(source, conn).await?), - } - } - if entries.len() > MAXIMUM_FORWARD_MESSAGES { - return Err(CommonError::Invalid { - field: Field::Forward, - problem: Problem::Length { - min: 1, - max: MAXIMUM_FORWARD_MESSAGES as u64, - actual: entries.len() as u64, - }, - } - .into()); - } - - let origin = origin(sources, conn).await?; - let message_id = insert(&user.id, community_id, "", None, conn).await?; - write_snippet( - &message_id, - &user.id, - community_id, - origin.as_deref(), - &entries, - directory, - conn, - ) - .await?; - - Ok(vec![read(&message_id, conn).await?]) -} - -#[cfg(test)] -mod tests { - use common::error::Error as CommonError; - - use crate::{community, database, error::ServerError, message, test, user}; - - #[tokio::test] - async fn create() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - - let message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - - assert_eq!(community.id, message.community_id); - assert_eq!(user.id, message.user_id); - assert_eq!("Tahinli", message.body); - } - - #[tokio::test] - async fn read() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - - let searched_message = message::read(&created_message.id, &conn).await.unwrap(); - - assert_eq!(created_message, searched_message); - } - - #[tokio::test] - async fn read_page() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); - let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - - let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - - let newest = message::read_page(&community.id, None, &conn) - .await - .unwrap(); - let older = message::read_page(&community.id, Some(&message_3.id), &conn) - .await - .unwrap(); - - assert_eq!( - vec![message_1.clone(), message_2.clone(), message_3], - newest - ); - assert_eq!(vec![message_1, message_2], older); - } - - #[tokio::test] - async fn update() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - - let updated_message = message::update(&created_message.id, "Not Tahinli", &conn) - .await - .unwrap(); - let searched_message = message::read(&created_message.id, &conn).await.unwrap(); - - assert_eq!(created_message.user_id, updated_message.user_id); - assert_eq!(created_message.community_id, updated_message.community_id); - assert_eq!(updated_message, searched_message); - assert_eq!("Not Tahinli", searched_message.body); - } - - #[tokio::test] - async fn update_on_missing_message() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let updated_message = message::update("missing", "Tahinli", &conn).await; - - assert!(matches!( - updated_message, - Err(ServerError::Wire(CommonError::NotFound)) - )); - } - - #[tokio::test] - async fn delete() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) - .await - .unwrap(); - - let deleted_message = message::delete(&created_message.id, &conn).await.unwrap(); - - assert_eq!(created_message, deleted_message); - } - - #[tokio::test] - async fn forward_two_as_snippet() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("Tahinli", &conn).await.unwrap(); - let first = message::create(&user.id, &community.id, "First", &[], None, &conn) - .await - .unwrap(); - let second = message::create(&user.id, &community.id, "Second", &[], None, &conn) - .await - .unwrap(); - - let created = message::forward( - &user, - &community.id, - &[first, second], - message::ForwardMode::Snippet, - &test::directory(), - &conn, - ) - .await - .unwrap(); - - assert_eq!(1, created.len()); - assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len()); - } -} diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index 3e6794e..e350f7c 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -2,29 +2,30 @@ use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; use bytes::Bytes; use common::{ - call::Request, + call::{Login, Register, Request}, frame::{self, DOWN_MAX, Sending, UP_MAX}, model::User, open::Open, session::{Hello, Welcome}, transport::Close, + validate::validate_device, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; use tokio::sync::mpsc; use tracing::{info, warn}; use crate::{ - attachment, authentication, + authentication, call::{self, Cx}, - database::{self, DB}, datagram, + db::{self, Db}, error::ServerError, + files, hub::{Client, Hub, Presence, Signed}, - publish::publish, + publish, rate_limit::RateLimit, request, retention, rooms::Rooms, - server_ban, stats, user, }; const HELLO_DEADLINE: Duration = Duration::from_secs(5); @@ -38,7 +39,7 @@ pub struct Services { #[derive(Clone)] pub(crate) struct Shared { - pub(crate) db: DB, + pub(crate) db: Db, pub(crate) services: Services, pub(crate) directory: PathBuf, pub(crate) backups: PathBuf, @@ -54,7 +55,7 @@ struct Pending { pub async fn serve( server_address: &str, server_config: quinn::ServerConfig, - db: DB, + db: Db, directory: PathBuf, backups: PathBuf, ) -> Result<(), ServerError> { @@ -85,8 +86,11 @@ async fn handle_connection(incoming: Incoming, shared: Shared) { async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> { let ip = incoming.remote_address().ip().to_string(); - let conn = database::connect(&shared.db).await?; - if server_ban::ip_banned(&ip, &conn).await? { + let banned = shared + .db + .run(async |db| db::server_ban::ip_banned(&ip, db).await) + .await?; + if banned { incoming .accept()? .await? @@ -157,16 +161,19 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv let presence = hub.remove(client.id); if let Some(me) = &client.me { - let conn = database::connect(&shared.db).await?; - let mut broadcasts = match shared.services.rooms.leave(client.id) { - Some(departure) => request::departed(departure, &conn).await?, - None => Vec::new(), - }; - if let Presence::Offline(user_id) = &presence { - broadcasts.extend(request::presence_changed(hub, user_id, &conn).await?); - } - publish(&shared, broadcasts).await; - authentication::seen(&me.user_id, &me.token, &conn).await?; + publish::job(&shared, async |db| { + let mut broadcasts = match shared.services.rooms.leave(client.id) { + Some(departure) => request::departed(departure, db).await?, + None => Vec::new(), + }; + if let Presence::Offline(user_id) = presence { + broadcasts.extend(request::presence_changed(hub, user_id, db).await?); + } + db::session::seen(me.session_id, db).await?; + + Ok(broadcasts) + }) + .await?; } Ok(()) @@ -211,21 +218,28 @@ async fn admit( let Some(token) = hello.token else { return Ok((None, None)); }; - let conn = database::connect(&shared.db).await?; - let user = authentication::resume(&token, &conn).await?; - stats::mark_active(&user.id, &conn).await?; - user::set_last_ip( - &user.id, - &connection.remote_address().ip().to_string(), - &conn, - ) - .await?; - if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await { - warn!("device: {error}"); - } + let ip = connection.remote_address().ip().to_string(); + let (session_id, user) = shared + .db + .run(async |db| { + let (session_id, user) = authentication::resume(&token, db).await?; + db::stats::mark_active(user.id, db).await?; + db::user::set_last_ip(user.id, &ip, db).await?; + let device = async { + validate_device(&hello.device)?; + db::session::set_device(session_id, &hello.device, db).await + } + .await; + if let Err(error) = device { + warn!("device: {error}"); + } + + Ok((session_id, user)) + }) + .await?; let me = Signed { - user_id: user.id.clone(), - token, + user_id: user.id, + session_id, }; Ok((Some(me), Some(user))) @@ -238,10 +252,11 @@ async fn welcome( shared: &Shared, ) -> Result { let checked = match &client.me { - Some(me) => { - let conn = database::connect(&shared.db).await?; - authentication::resume(&me.token, &conn).await.map(Some) - } + Some(me) => shared + .db + .run(async |db| authentication::recheck(me.session_id, db).await) + .await + .map(Some), None => Ok(user.clone()), }; let accepted = checked.is_ok(); @@ -266,7 +281,7 @@ async fn route( Open::Call(request) => answer(client, request, send_stream, shared).await, Open::Upload(upload) => { let user = signed_user(&client, &shared).await?; - attachment::upload( + files::upload( user.as_ref(), upload, receive_stream, @@ -278,7 +293,7 @@ async fn route( } Open::Fetch(blob) => { let user = signed_user(&client, &shared).await?; - attachment::fetch( + files::fetch( user.as_ref(), blob, send_stream, @@ -292,12 +307,15 @@ async fn route( } async fn signed_user(client: &Client, shared: &Shared) -> Result, ServerError> { - let Some(me) = &client.me else { + if client.me.is_none() { return Ok(None); - }; - let conn = database::connect(&shared.db).await?; + } + let user = shared + .db + .run(async |db| request::authenticated(client, db).await) + .await?; - Ok(Some(user::read(&me.user_id, &conn).await?)) + Ok(Some(user)) } async fn answer( @@ -306,9 +324,21 @@ async fn answer( mut send_stream: Sending, shared: Shared, ) -> Result<(), ServerError> { - let db = database::connect(&shared.db).await?; - let mut cx = Cx::new(&client, &shared, db); - let reply = call::dispatch(request, &mut cx).await; + let reply = match request { + Request::Register(call) => { + call::encode::(authentication::register(call, &client, &shared).await) + } + Request::Login(call) => { + call::encode::(authentication::login(call, &client, &shared).await) + } + request => { + let db = shared.db.lock().await?; + let mut cx = Cx::new(&client, &shared, &db); + let reply = call::dispatch(request, &mut cx).await; + publish::publish(&shared, &db, std::mem::take(&mut cx.out)).await; + reply + } + }; send_stream.get().write_all(&reply).await?; send_stream.finish()?; @@ -327,13 +357,13 @@ async fn publish_presence(shared: &Shared, presence: Presence) { let (Presence::Online(user_id) | Presence::Offline(user_id)) = presence else { return; }; - let broadcasts = match database::connect(&shared.db).await { - Ok(conn) => request::presence_changed(&shared.services.hub, &user_id, &conn).await, - Err(error) => Err(error), - }; - match broadcasts { - Ok(broadcasts) => publish(shared, broadcasts).await, - Err(error) => warn!("presence: {error}"), + let hub = &shared.services.hub; + if let Err(error) = publish::job(shared, async |db| { + request::presence_changed(hub, user_id, db).await + }) + .await + { + warn!("presence: {error}"); } } diff --git a/crates/server/src/notes.rs b/crates/server/src/notes.rs deleted file mode 100644 index 3b8641e..0000000 --- a/crates/server/src/notes.rs +++ /dev/null @@ -1,36 +0,0 @@ -use common::model::{Community, Rank}; -use turso::Connection; - -use crate::{community, error::ServerError, user_community}; - -async fn find(user_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT community_id FROM notes WHERE user_id = ?1", - (user_id,), - ) - .await?; - - Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) -} - -pub async fn open(me: &str, conn: &mut Connection) -> Result { - let tx = conn.transaction().await?; - let community_id = match find(me, &tx).await? { - Some(community_id) => community_id, - None => { - let community_id = community::create_fixed(community::Kind::Notes, &tx).await?; - user_community::join(me, &community_id, Rank::Owner, &tx).await?; - tx.execute( - "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)", - (me, community_id.as_str()), - ) - .await?; - community_id - } - }; - let community = community::read(&community_id, me, &tx).await?; - tx.commit().await?; - - Ok(community) -} diff --git a/crates/server/src/overview.rs b/crates/server/src/overview.rs deleted file mode 100644 index 4dc4df3..0000000 --- a/crates/server/src/overview.rs +++ /dev/null @@ -1,36 +0,0 @@ -use common::model::{Overview, Role}; -use turso::Connection; - -use crate::{community::Kind, error::ServerError, hub::Hub, rooms::Rooms}; - -pub async fn read(hub: &Hub, rooms: &Rooms, conn: &Connection) -> Result { - let mut rows = conn - .query( - "SELECT - (SELECT COUNT(*) FROM user), - (SELECT COUNT(*) FROM user WHERE role = ?1), - (SELECT COUNT(*) FROM community WHERE kind = ?2), - (SELECT COALESCE(SUM(size), 0) FROM attachment) - + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar) - + (SELECT COALESCE(SUM(length(data)), 0) FROM community_avatar)", - (Role::Builder.as_str(), Kind::Group.as_str()), - ) - .await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let count = |index: usize| -> Result { - let value: i64 = row.get(index)?; - Ok(value as u64) - }; - - Ok(Overview { - users: count(0)?, - builders: count(1)?, - communities: count(2)?, - online: hub.online() as u64, - voice: rooms.count() as u64, - storage_bytes: count(3)?, - }) -} diff --git a/crates/server/src/publish.rs b/crates/server/src/publish.rs index fe8d0dc..5ae9f8e 100644 --- a/crates/server/src/publish.rs +++ b/crates/server/src/publish.rs @@ -4,20 +4,23 @@ use bytes::Bytes; use common::{ event::{Down, Event, Media}, frame::{self, DOWN_MAX}, + model::Id, }; use tracing::warn; use crate::{ - community, database, error::ServerError, friend, hub::ConnId, network::Shared, user, - user_community, + db::{self, Connection}, + error::ServerError, + hub::ConnId, + network::Shared, }; pub enum To { - User(String), - Users(Vec), - Community(String), - CommunityExcept(String, String), - Related(String), + User(Id), + Users(Vec), + Community(Id), + CommunityExcept(Id, Id), + Related(Id), Builders, Everyone, Conn(ConnId), @@ -44,9 +47,9 @@ impl Broadcast { } } -pub(crate) async fn publish(shared: &Shared, broadcasts: Vec) { +pub(crate) async fn publish(shared: &Shared, db: &Connection, broadcasts: Vec) { for broadcast in broadcasts { - let ids = match resolve(shared, &broadcast.to).await { + let ids = match resolve(shared, &broadcast.to, db).await { Ok(ids) => ids, Err(error) => { warn!("resolve: {error}"); @@ -63,52 +66,58 @@ pub(crate) async fn publish(shared: &Shared, broadcasts: Vec) { } } -async fn resolve(shared: &Shared, to: &To) -> Result, ServerError> { +pub(crate) async fn job( + shared: &Shared, + work: impl AsyncFnOnce(&Connection) -> Result, ServerError>, +) -> Result<(), ServerError> { + let db = shared.db.lock().await?; + let out = db::atomic(&db, work(&db)).await?; + publish(shared, &db, out).await; + + Ok(()) +} + +async fn resolve(shared: &Shared, to: &To, db: &Connection) -> Result, ServerError> { let hub = &shared.services.hub; let ids = match to { To::Conn(id) => vec![*id], To::Everyone => hub.all(), To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), To::Users(user_ids) => hub.conns_of(user_ids), - To::Builders => { - let conn = database::connect(&shared.db).await?; - hub.conns_of(&user::builder_ids(&conn).await?) - } - To::Community(community_id) => community_conns(shared, community_id).await?, + To::Builders => hub.conns_of(&db::user::builder_ids(db).await?), + To::Community(community_id) => community_conns(shared, *community_id, db).await?, To::CommunityExcept(community_id, user_id) => { - let mut ids = community_conns(shared, community_id).await?; + let mut ids = community_conns(shared, *community_id, db).await?; let own = hub.conns_of(std::slice::from_ref(user_id)); ids.retain(|id| !own.contains(id)); ids } - To::Related(user_id) => { - let conn = database::connect(&shared.db).await?; - hub.conns_of(&related_user_ids(user_id, &conn).await?) - } + To::Related(user_id) => hub.conns_of(&related_user_ids(*user_id, db).await?), }; Ok(ids) } -async fn community_conns(shared: &Shared, community_id: &str) -> Result, ServerError> { +async fn community_conns( + shared: &Shared, + community_id: Id, + db: &Connection, +) -> Result, ServerError> { let hub = &shared.services.hub; - let conn = database::connect(&shared.db).await?; - let mut ids = hub.conns_of(&user_community::member_ids(community_id, &conn).await?); + let mut ids = hub.conns_of(&db::member::member_ids(community_id, db).await?); ids.extend(hub.watchers(community_id)); ids.sort_unstable(); ids.dedup(); + Ok(ids) } -pub(crate) async fn related_user_ids( - user_id: &str, - conn: &turso::Connection, -) -> Result, ServerError> { - let mut user_ids = BTreeSet::from([user_id.to_string()]); - for community in community::communities_of(user_id, conn).await? { - user_ids.extend(user_community::member_ids(&community.id, conn).await?); +pub(crate) async fn related_user_ids(user_id: Id, db: &Connection) -> Result, ServerError> { + let mut user_ids = BTreeSet::from([user_id]); + for community in db::community::communities_of(user_id, db).await? { + user_ids.extend(db::member::member_ids(community.id, db).await?); } - for friend in friend::state(user_id, conn).await?.friends { + for friend in db::friend::state(user_id, db).await?.friends { user_ids.insert(friend.id); } diff --git a/crates/server/src/report.rs b/crates/server/src/report.rs deleted file mode 100644 index f2449f0..0000000 --- a/crates/server/src/report.rs +++ /dev/null @@ -1,92 +0,0 @@ -use common::{ - constant::LOG_PAGE_LIMIT, - error::Error as CommonError, - model::{Report, ReportStatus}, -}; -use turso::Connection; - -use crate::{ - database::{self, new_id}, - error::ServerError, - user, -}; - -pub async fn is_open( - reporter_id: &str, - target_id: &str, - message_id: Option<&str>, - conn: &Connection, -) -> Result { - database::exists( - conn, - "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", - (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), - ) - .await -} - -pub async fn insert( - reporter_id: &str, - target_id: &str, - message_id: Option<&str>, - community_id: Option<&str>, - body: Option<&str>, - reason: &str, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "INSERT INTO report (id, reporter_id, target_id, message_id, community_id, body, reason) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", - (new_id(), reporter_id, target_id, message_id, community_id, body, reason), - ) - .await?; - - Ok(()) -} - -pub async fn list( - status: Option, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT r.id, {}, {}, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, {} FROM report r LEFT JOIN user rp ON rp.id = r.reporter_id LEFT JOIN user t ON t.id = r.target_id LEFT JOIN community c ON c.id = r.community_id LEFT JOIN user h ON h.id = r.handled_by WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("rp"), user::user_columns("t"), user::user_columns("h")), - (status.map(ReportStatus::as_str),), - ) - .await?; - - let mut reports = Vec::new(); - while let Some(row) = rows.next().await? { - let text: String = row.get(16)?; - reports.push(Report { - id: row.get(0)?, - reporter: user::from_row_at(&row, 1)?, - target: user::from_row_at(&row, 6)?, - community: row.get(11)?, - message_id: row.get(12)?, - community_id: row.get(13)?, - body: row.get(14)?, - reason: row.get(15)?, - status: ReportStatus::parse(&text).ok_or(CommonError::Server)?, - handled_by: user::from_row_at(&row, 17)?, - }); - } - - Ok(reports) -} - -pub async fn handle( - report_id: &str, - status: ReportStatus, - handled_by: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", - (report_id, status.as_str(), handled_by, ReportStatus::Open.as_str()), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(row.get(0)?) -} diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index cf2b636..9cbddd0 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -1,29 +1,29 @@ +use std::collections::BTreeMap; + use common::{ error::Error as CommonError, event::Event, - model::{AdminAction, CallLog, Message, Presence, Rank, User}, + model::{AdminAction, CallLog, Id, Message, Presence, Rank, User}, permission, - share::Kind, + share::Kind as ShareKind, }; -use turso::Connection; use crate::{ - admin_log, community, - error::ServerError, + call::Cx, + db::{self, Connection, community::Kind}, + error::{ServerError, ensure}, hub::{Client, Hub}, - message, publish::{Broadcast, To}, rate_limit::RateLimit, rooms::{Departure, Rooms}, - server_settings, user, user_community, }; pub(crate) async fn limit_logins( rate_limit: &RateLimit, connection: Option<&quinn::Connection>, - conn: &Connection, + db: &Connection, ) -> Result<(), ServerError> { - let limit = server_settings::read(conn).await?.logins_per_minute; + let limit = db::settings::read(db).await?.logins_per_minute; let ip = connection .map(|connection| connection.remote_address().ip().to_string()) @@ -34,72 +34,65 @@ pub(crate) async fn limit_logins( pub(crate) async fn effective_presence( hub: &Hub, - user_id: &str, - conn: &Connection, + user_id: Id, + db: &Connection, ) -> Result { if !hub.is_online(user_id) { return Ok(Presence::Offline); } - user::presence(user_id, conn).await + db::user::presence(user_id, db).await } pub async fn presence_changed( hub: &Hub, - user_id: &str, - conn: &Connection, + user_id: Id, + db: &Connection, ) -> Result, ServerError> { - let presence = effective_presence(hub, user_id, conn).await?; - - let event = Event::PresenceChanged { - user_id: user_id.to_string(), - presence, - }; + let presence = effective_presence(hub, user_id, db).await?; + let event = Event::PresenceChanged { user_id, presence }; - Ok(vec![Broadcast::new( - To::Related(user_id.to_string()), - event, - )]) + Ok(vec![Broadcast::new(To::Related(user_id), event)]) } pub(crate) async fn leave_user_voice( rooms: &Rooms, - user_id: &str, - conn: &Connection, + user_id: Id, + db: &Connection, ) -> Result, ServerError> { match rooms.leave_user(user_id) { - Some(departure) => departed(departure, conn).await, + Some(departure) => departed(departure, db).await, None => Ok(Vec::new()), } } pub(crate) async fn leave_room_voice( rooms: &Rooms, - community_id: &str, - user_id: &str, - conn: &Connection, + community_id: Id, + user_id: Id, + db: &Connection, ) -> Result, ServerError> { match rooms.leave_room(community_id, user_id) { - Some(departure) => departed(departure, conn).await, + Some(departure) => departed(departure, db).await, None => Ok(Vec::new()), } } pub(crate) async fn voice_muted( - community_id: Option, - user_id: &str, + community_id: Option, + user_id: Id, muted: bool, - conn: &Connection, + db: &Connection, ) -> Result { - let mut user_ids = vec![user_id.to_string()]; - if let Some(community_id) = &community_id - && !user::is_ghost(user_id, conn).await? + let mut user_ids = vec![user_id]; + if let Some(community_id) = community_id + && !db::user::is_ghost(user_id, db).await? { - user_ids.extend(user_community::member_ids(community_id, conn).await?); + user_ids.extend(db::member::member_ids(community_id, db).await?); } let event = Event::VoiceMuted { community_id, - user_id: user_id.to_string(), + user_id, muted, }; @@ -108,37 +101,45 @@ pub(crate) async fn voice_muted( pub(crate) async fn voice_closed( rooms: &Rooms, - community_id: &str, - conn: &Connection, + community_id: Id, + db: &Connection, ) -> Result, ServerError> { let mut broadcasts = Vec::new(); for departure in rooms.close_room(community_id) { - broadcasts.extend(departed(departure, conn).await?); + broadcasts.extend(departed(departure, db).await?); } Ok(broadcasts) } +pub(crate) async fn delete_community(community_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let closed = voice_closed(&cx.sh.services.rooms, community_id, cx.db).await?; + cx.out.extend(closed); + db::community::delete(community_id, cx.db).await?; + + Ok(()) +} + pub(crate) async fn call_ended( - community_id: &str, - user_id: &str, + community_id: Id, + user_id: Id, call: Option, - conn: &Connection, + db: &Connection, ) -> Result, ServerError> { let Some(call) = call else { return Ok(Vec::new()); }; - if !community::is_direct(community_id, conn).await? { + if db::community::kind_of(community_id, db).await? != Some(Kind::Direct) { return Ok(Vec::new()); } - let created = message::create_call_log(community_id, user_id, call, conn).await?; + let created = db::message::create_call_log(community_id, user_id, call, db).await?; Ok(vec![message_event(&created, Event::MessageCreated)]) } pub async fn departed( mut departure: Departure, - conn: &Connection, + db: &Connection, ) -> Result, ServerError> { let mut broadcasts = shares_ended(&mut departure); if departure.quiet { @@ -152,63 +153,76 @@ pub async fn departed( .. } = departure; let Some(seconds) = ghost_seconds else { - broadcasts.extend(call_ended(&community_id, &user_id, call_log, conn).await?); + broadcasts.extend(call_ended(community_id, user_id, call_log, db).await?); let event = Event::VoiceLeft { - community_id: community_id.clone(), + community_id, user_id, }; broadcasts.push(Broadcast::new(To::Community(community_id), event)); return Ok(broadcasts); }; - record_ghost_voice(&user_id, &community_id, seconds, conn).await?; + record_ghost_voice(user_id, community_id, seconds, db).await?; Ok(broadcasts) } -pub(crate) fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast { +pub(crate) fn share_ended(community_id: Id, user_id: Id, kind: ShareKind) -> Broadcast { let event = Event::ShareStopped { - community_id: community_id.to_string(), - user_id: user_id.to_string(), + community_id, + user_id, kind, }; - Broadcast::new(To::Community(community_id.to_string()), event) + Broadcast::new(To::Community(community_id), event) } pub(crate) fn shares_ended(departure: &mut Departure) -> Vec { let mut broadcasts: Vec = departure .shares .iter() - .map(|kind| share_ended(&departure.community_id, &departure.user_id, *kind)) + .map(|kind| share_ended(departure.community_id, departure.user_id, *kind)) .collect(); broadcasts.append(&mut departure.media); broadcasts } -pub(crate) async fn authenticated(client: &Client, conn: &Connection) -> Result { - let user_id = client.user_id().ok_or(CommonError::Unauthenticated)?; +pub(crate) fn messages_deleted(rows: Vec<(Id, Id)>) -> Vec { + let mut deleted: BTreeMap> = BTreeMap::new(); + for (community_id, message_id) in rows { + deleted.entry(community_id).or_default().push(message_id); + } + + deleted + .into_iter() + .map(|(community_id, ids)| { + let event = Event::MessagesDeleted { community_id, ids }; + Broadcast::new(To::Community(community_id), event) + }) + .collect() +} + +pub(crate) async fn authenticated(client: &Client, db: &Connection) -> Result { + let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; - user::read(user_id, conn).await + Ok(db::session::user_of(me.session_id, db) + .await? + .ok_or(CommonError::Unauthenticated)?) } pub async fn actor_rank( me: &User, - community_id: &str, - conn: &Connection, + community_id: Id, + db: &Connection, ) -> Result, ServerError> { - let rank = user_community::rank(&me.id, community_id, conn).await?; + let rank = db::member::rank(me.id, community_id, db).await?; Ok(permission::effective_rank(me.role, rank)) } -pub(crate) async fn managed( - me: &User, - user_id: &str, - conn: &Connection, -) -> Result { - let target = user::read(user_id, conn).await?; +pub(crate) async fn managed(me: &User, user_id: Id, db: &Connection) -> Result { + let target = db::user::read(user_id, db).await?; ensure(permission::can_manage_user( me.role, me.id == user_id, @@ -218,66 +232,49 @@ pub(crate) async fn managed( Ok(target) } -pub fn ensure(allowed: bool) -> Result<(), ServerError> { - ensure_with(allowed, CommonError::Forbidden) -} - -pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError> { - if !allowed { - return Err(error.into()); - } - - Ok(()) -} - pub(crate) async fn allowed( me: &User, - community_id: &str, - conn: &Connection, + community_id: Id, + db: &Connection, check: fn(Option) -> bool, ) -> Result<(), ServerError> { - ensure(check(actor_rank(me, community_id, conn).await?)) + ensure(check(actor_rank(me, community_id, db).await?)) } pub(crate) async fn is_outsider( - user_id: &str, - community_id: &str, - conn: &Connection, + user_id: Id, + community_id: Id, + db: &Connection, ) -> Result { - Ok(user_community::rank(user_id, community_id, conn) - .await? - .is_none()) + Ok(db::member::rank(user_id, community_id, db).await?.is_none()) } -pub(crate) async fn ensure_editable( - community_id: &str, - conn: &Connection, -) -> Result<(), ServerError> { - ensure(!community::is_fixed(community_id, conn).await?) +pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result<(), ServerError> { + let kind = db::community::kind_of(community_id, db) + .await? + .ok_or(CommonError::NotFound)?; + + ensure(kind == Kind::Group) } pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { - Broadcast::new( - To::Community(message.community_id.clone()), - event(message.clone()), - ) + Broadcast::new(To::Community(message.community_id), event(message.clone())) } -pub(crate) fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec { - let to = || To::Community(community_id.to_string()); +pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec { let mut broadcasts = vec![Broadcast::new( - to(), + To::Community(community_id), Event::VoiceJoined { - community_id: community_id.to_string(), - user_id: user_id.to_string(), + community_id, + user_id, }, )]; if muted { broadcasts.push(Broadcast::new( - to(), + To::Community(community_id), Event::VoiceMuted { - community_id: Some(community_id.to_string()), - user_id: user_id.to_string(), + community_id: Some(community_id), + user_id, muted, }, )); @@ -287,18 +284,18 @@ pub(crate) fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Ve } pub(crate) async fn record_ghost_voice( - user_id: &str, - community_id: &str, + user_id: Id, + community_id: Id, seconds: u64, - conn: &Connection, + db: &Connection, ) -> Result<(), ServerError> { - let community = community::label(community_id, conn).await?; - admin_log::record( + let community = db::community::label(community_id, db).await?; + db::log::record_admin( Some(user_id), None, Some(&community), &AdminAction::GhostVoice { seconds }, - conn, + db, ) .await } @@ -310,23 +307,23 @@ mod tests { use common::{ call::{ AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, - DeleteCommunity, FindUser, Invite, ListCommunities, ListFriends, Register, - UpdateCommunity, + DeleteCommunity, FindUser, Invite, ListCommunities, ListFriends, UpdateCommunity, }, error::Error as CommonError, + model::{Id, Role}, }; use crate::{ + authentication::token_hash, call::{Cx, Handle, Me}, - database::{self, DB}, + db::{self, Db}, hub::{Client, Signed}, - message, network::{Services, Shared}, request::authenticated, test, }; - fn shared(db: &DB, services: &Services) -> Shared { + fn shared(db: &Db, services: &Services) -> Shared { Shared { db: db.clone(), services: services.clone(), @@ -338,43 +335,38 @@ mod tests { async fn call( call: C, client: &Arc, - db: &DB, + db: &Db, services: &Services, ) -> Result { let shared = shared(db, services); - let conn = database::connect(db).await.unwrap(); + let conn = db.lock().await.unwrap(); let me = authenticated(client, &conn).await?; - let mut cx = Cx::new(client, &shared, conn); + let mut cx = Cx::new(client, &shared, &conn); Ok(call.handle(Me::User(me), &mut cx).await?) } - async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc { - let guest = Client::detached(None); - let shared = shared(db, services); - let conn = database::connect(db).await.unwrap(); - let mut cx = Cx::new(&guest, &shared, conn); - let session = Register { - username: username.to_string(), - password: "password".to_string(), - invite: None, - } - .handle(Me::Guest, &mut cx) - .await - .unwrap(); + async fn signed_in(username: &str, db: &Db) -> Arc { + let conn = db.lock().await.unwrap(); + let user = db::user::create(username, "hash", Role::User, &conn) + .await + .unwrap(); + let session_id = db::session::insert(&token_hash(username), user.id, &conn) + .await + .unwrap(); Client::detached(Some(Signed { - user_id: session.user.id, - token: session.token, + user_id: user.id, + session_id, })) } async fn invite_and_accept( - community_id: &str, + community_id: Id, owner: &Arc, member: &Arc, username: &str, - db: &DB, + db: &Db, services: &Services, ) { let member_user = call( @@ -389,7 +381,7 @@ mod tests { .unwrap(); call( Invite { - community_id: community_id.to_string(), + community_id, user_id: member_user.id, }, owner, @@ -398,24 +390,17 @@ mod tests { ) .await .unwrap(); - call( - AcceptInvitation { - community_id: community_id.to_string(), - }, - member, - db, - services, - ) - .await - .unwrap(); + call(AcceptInvitation { community_id }, member, db, services) + .await + .unwrap(); } #[tokio::test] async fn plain_member_cannot_rename() { - let db = test::get_database().await; + let db = test::db().await; let services = Services::default(); - let owner = signed_in("Owner", &db, &services).await; - let member = signed_in("Member", &db, &services).await; + let owner = signed_in("Owner", &db).await; + let member = signed_in("Member", &db).await; let community = call( CreateCommunity { name: "The Community".to_string(), @@ -426,7 +411,7 @@ mod tests { ) .await .unwrap(); - invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; + invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; let response = call( UpdateCommunity { @@ -444,10 +429,10 @@ mod tests { #[tokio::test] async fn accepted_friend_request_befriends_both() { - let db = test::get_database().await; + let db = test::db().await; let services = Services::default(); - let first = signed_in("First", &db, &services).await; - let second = signed_in("Second", &db, &services).await; + let first = signed_in("First", &db).await; + let second = signed_in("Second", &db).await; let first_user = call( FindUser { username: "First".to_string(), @@ -470,7 +455,7 @@ mod tests { .unwrap(); call( AddFriend { - user_id: second_user.id.clone(), + user_id: second_user.id, }, &first, &db, @@ -480,7 +465,7 @@ mod tests { .unwrap(); call( AcceptFriend { - user_id: first_user.id.clone(), + user_id: first_user.id, }, &second, &db, @@ -498,10 +483,10 @@ mod tests { #[tokio::test] async fn invite_and_accept_makes_member() { - let db = test::get_database().await; + let db = test::db().await; let services = Services::default(); - let owner = signed_in("Owner", &db, &services).await; - let member = signed_in("Member", &db, &services).await; + let owner = signed_in("Owner", &db).await; + let member = signed_in("Member", &db).await; let community = call( CreateCommunity { name: "The Community".to_string(), @@ -513,7 +498,7 @@ mod tests { .await .unwrap(); - invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; + invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; let communities = call(ListCommunities, &member, &db, &services) .await @@ -523,9 +508,9 @@ mod tests { #[tokio::test] async fn delete_community_removes_messages() { - let db = test::get_database().await; + let db = test::db().await; let services = Services::default(); - let owner = signed_in("Owner", &db, &services).await; + let owner = signed_in("Owner", &db).await; let community = call( CreateCommunity { name: "The Community".to_string(), @@ -538,7 +523,7 @@ mod tests { .unwrap(); call( CreateMessage { - community_id: community.id.clone(), + community_id: community.id, body: "Tahinli".to_string(), attachments: Vec::new(), reply_to: None, @@ -552,7 +537,7 @@ mod tests { call( DeleteCommunity { - community_id: community.id.clone(), + community_id: community.id, }, &owner, &db, @@ -561,8 +546,8 @@ mod tests { .await .unwrap(); - let conn = database::connect(&db).await.unwrap(); - let remaining = message::read_page(&community.id, None, &conn) + let conn = db.lock().await.unwrap(); + let remaining = db::message::read_page(community.id, None, &conn) .await .unwrap(); diff --git a/crates/server/src/retention.rs b/crates/server/src/retention.rs index a04c16a..745304d 100644 --- a/crates/server/src/retention.rs +++ b/crates/server/src/retention.rs @@ -1,20 +1,12 @@ -use std::{collections::BTreeMap, path::Path, time::Duration}; +use std::time::Duration; -use common::{event::Event, time}; +use common::time; use tracing::{error, info}; -use turso::Connection; -use crate::{ - attachment, database, - error::ServerError, - message, - network::Shared, - publish::{Broadcast, To, publish}, - server_settings, -}; +use crate::{db, error::ServerError, network::Shared, publish::job, request::messages_deleted}; const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); -const BATCH_SIZE: i64 = 500; +const BATCH_SIZE: u32 = 500; pub(crate) async fn collect(shared: Shared) { let mut interval = tokio::time::interval(SWEEP_INTERVAL); @@ -26,99 +18,55 @@ pub(crate) async fn collect(shared: Shared) { } } -fn cutoff(now: u64, days: u32) -> String { - time::id_bound(now.saturating_sub(u64::from(days) * time::DAY_MILLIS)) +fn cutoff(days: u32) -> u64 { + time::now_ms().saturating_sub(u64::from(days) * time::DAY_MILLIS) } -async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT id FROM {table} WHERE id < ?1 ORDER BY id LIMIT ?2"), - (cutoff, BATCH_SIZE), - ) - .await?; - - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get(0)?); - } - - Ok(ids) -} - -async fn purge_messages( - cutoff: &str, - conn: &mut Connection, - shared: &Shared, -) -> Result { +async fn purge_messages(cutoff: u64, shared: &Shared) -> Result { let mut purged = 0; loop { - let ids = expired("message", cutoff, conn).await?; - if ids.is_empty() { - return Ok(purged); - } + let mut deleted = 0; + job(shared, async |db| { + let rows = db::message::delete_before(cutoff, BATCH_SIZE, db).await?; + deleted = rows.len() as u64; - let tx = conn.transaction().await?; - let mut files = Vec::new(); - let mut deleted: BTreeMap> = BTreeMap::new(); - for id in &ids { - files.extend(attachment::ids_of_message(id, &tx).await?); - let message = message::delete(id, &tx).await?; - deleted - .entry(message.community_id) - .or_default() - .push(message.id); + Ok(messages_deleted(rows)) + }) + .await?; + if deleted == 0 { + return Ok(purged); } - tx.commit().await?; - attachment::remove_files(&files, &shared.directory); - let broadcasts = deleted - .into_iter() - .map(|(community_id, ids)| { - let event = Event::MessagesDeleted { - community_id: community_id.clone(), - ids, - }; - Broadcast::new(To::Community(community_id), event) - }) - .collect(); - publish(shared, broadcasts).await; - purged += ids.len() as u64; + purged += deleted; } } -async fn purge_attachments( - cutoff: &str, - conn: &mut Connection, - directory: &Path, -) -> Result { +async fn purge_attachments(cutoff: u64, shared: &Shared) -> Result { let mut purged = 0; loop { - let ids = expired("attachment", cutoff, conn).await?; - if ids.is_empty() { - return Ok(purged); - } + let mut deleted = 0; + job(shared, async |db| { + deleted = db::attachment::delete_before(cutoff, BATCH_SIZE, db).await?; - for id in &ids { - attachment::delete(id, conn).await?; + Ok(Vec::new()) + }) + .await?; + if deleted == 0 { + return Ok(purged); } - attachment::remove_files(&ids, directory); - purged += ids.len() as u64; + purged += deleted; } } async fn sweep(shared: &Shared) -> Result<(), ServerError> { - let directory = &shared.directory; - let mut conn = database::connect(&shared.db).await?; - let settings = server_settings::read(&conn).await?; - let now = time::now_ms(); + let settings = shared.db.run(db::settings::read).await?; let messages = match settings.message_retention_days { 0 => 0, - days => purge_messages(&cutoff(now, days), &mut conn, shared).await?, + days => purge_messages(cutoff(days), shared).await?, }; let attachments = match settings.attachment_retention_days { 0 => 0, - days => purge_attachments(&cutoff(now, days), &mut conn, directory).await?, + days => purge_attachments(cutoff(days), shared).await?, }; if messages + attachments > 0 { diff --git a/crates/server/src/rooms.rs b/crates/server/src/rooms.rs index 8285f09..b6b8769 100644 --- a/crates/server/src/rooms.rs +++ b/crates/server/src/rooms.rs @@ -8,7 +8,7 @@ use common::{ datagram::{self, Packet, RELAY_PREFIX, relayed}, error::Error, event::{Event, Media}, - model::CallLog, + model::{CallLog, Id}, share::{Codec, Kind, Layer, Quality, Share, Source, choose}, time, }; @@ -67,7 +67,7 @@ impl Forward { } struct Viewer { - user_id: String, + user_id: Id, connection: Connection, quality: Quality, decode: Vec, @@ -87,7 +87,7 @@ impl Sharing { .collect() } - fn viewer(&self, user_id: &str) -> Option<&Viewer> { + fn viewer(&self, user_id: Id) -> Option<&Viewer> { self.viewers.iter().find(|viewer| viewer.user_id == user_id) } } @@ -111,10 +111,10 @@ fn layers_changed( }) } -struct Sharer<'a> { +struct Sharer { conn: ConnId, - user_id: &'a str, - community_id: &'a str, + user_id: Id, + community_id: Id, kind: Kind, } @@ -127,10 +127,10 @@ fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec { viewers.retain_mut(|viewer| { let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { stopped.push(Broadcast::new( - To::User(viewer.user_id.clone()), + To::User(viewer.user_id), Event::ShareStopped { - community_id: sharer.community_id.to_string(), - user_id: sharer.user_id.to_string(), + community_id: sharer.community_id, + user_id: sharer.user_id, kind: sharer.kind, }, )); @@ -164,7 +164,7 @@ fn remove_viewer( sharer: ConnId, kind: Kind, sharing: &mut Sharing, - viewer_id: &str, + viewer_id: Id, ) -> Option { let before = sharing.layers(); sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); @@ -173,8 +173,8 @@ fn remove_viewer( } struct Seat { - user_id: String, - uuid: [u8; RELAY_PREFIX], + user_id: Id, + prefix: [u8; RELAY_PREFIX], connection: Connection, muted: bool, ghost: bool, @@ -207,11 +207,11 @@ impl Room { self.seats.values().any(|seat| !seat.ghost) } - fn user_ids(&self, keep: impl Fn(&Seat) -> bool) -> Vec { + fn user_ids(&self, keep: impl Fn(&Seat) -> bool) -> Vec { self.seats .values() .filter(|seat| keep(seat)) - .map(|seat| seat.user_id.clone()) + .map(|seat| seat.user_id) .collect() } @@ -234,7 +234,7 @@ impl Room { } } - fn drop_viewer(&mut self, user_id: &str) -> Vec { + fn drop_viewer(&mut self, user_id: Id) -> Vec { let mut broadcasts = Vec::new(); for (conn, seat) in &mut self.seats { for (kind, sharing) in &mut seat.shares { @@ -247,8 +247,8 @@ impl Room { } pub struct Departure { - pub community_id: String, - pub user_id: String, + pub community_id: Id, + pub user_id: Id, pub ghost_seconds: Option, pub call_log: Option, pub shares: Vec, @@ -263,20 +263,20 @@ pub struct Joined { #[derive(Default)] struct Inner { - rooms: HashMap, - seat_of: HashMap, - conn_of_user: HashMap, + rooms: HashMap, + seat_of: HashMap, + conn_of_user: HashMap, } impl Inner { - fn seat_conn(&self, user_id: &str) -> Option { - self.conn_of_user.get(user_id).copied() + fn seat_conn(&self, user_id: Id) -> Option { + self.conn_of_user.get(&user_id).copied() } - fn seat_mut(&mut self, id: ConnId) -> Option<(&str, &mut Room)> { - let community_id = self.seat_of.get(&id)?; + fn seat_mut(&mut self, id: ConnId) -> Option<(Id, &mut Room)> { + let community_id = *self.seat_of.get(&id)?; - Some((community_id.as_str(), self.rooms.get_mut(community_id)?)) + Some((community_id, self.rooms.get_mut(&community_id)?)) } fn take(&mut self, id: ConnId, notify: bool, quiet: bool) -> Option { @@ -286,7 +286,7 @@ impl Inner { if self.conn_of_user.get(&seat.user_id) == Some(&id) { self.conn_of_user.remove(&seat.user_id); } - let mut media = room.drop_viewer(&seat.user_id); + let mut media = room.drop_viewer(seat.user_id); let call_log = (!quiet && !seat.ghost && !room.occupied()) .then(|| room.call_log()) .flatten(); @@ -316,15 +316,13 @@ impl Rooms { pub fn join( &self, client: &Client, - community_id: &str, + community_id: Id, muted: bool, ghost: bool, ) -> Result { let connection = client.conn.clone().ok_or(Error::Server)?; let user_id = client.user_id().ok_or(Error::Unauthenticated)?; - let uuid = *uuid::Uuid::parse_str(user_id) - .map_err(|_| Error::Server)? - .as_bytes(); + let prefix = user_id.to_be_bytes(); let mut inner = self.0.lock().unwrap(); if client.closed.load(Ordering::Acquire) { return Err(Error::Server); @@ -335,7 +333,7 @@ impl Rooms { if let Some(previous) = inner.seat_conn(user_id) { let kept = inner .rooms - .get(community_id) + .get(&community_id) .and_then(|room| room.seats.get(&previous)) .filter(|seat| seat.ghost == ghost) .map(|seat| seat.joined_at); @@ -343,18 +341,15 @@ impl Rooms { joined_at = kept.unwrap_or(joined_at); departure = inner.take(previous, previous != client.id, transferred); } - let room = inner - .rooms - .entry(community_id.to_string()) - .or_insert_with(Room::new); + let room = inner.rooms.entry(community_id).or_insert_with(Room::new); if !ghost && !transferred { room.admit(); } room.seats.insert( client.id, Seat { - user_id: user_id.to_string(), - uuid, + user_id, + prefix, connection, muted, ghost, @@ -362,8 +357,8 @@ impl Rooms { shares: BTreeMap::new(), }, ); - inner.seat_of.insert(client.id, community_id.to_string()); - inner.conn_of_user.insert(user_id.to_string(), client.id); + inner.seat_of.insert(client.id, community_id); + inner.conn_of_user.insert(user_id, client.id); Ok(Joined { departure, @@ -375,28 +370,28 @@ impl Rooms { self.0.lock().unwrap().take(id, false, false) } - pub fn leave_user(&self, user_id: &str) -> Option { + pub fn leave_user(&self, user_id: Id) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; inner.take(id, true, false) } - pub fn leave_room(&self, community_id: &str, user_id: &str) -> Option { + pub fn leave_room(&self, community_id: Id, user_id: Id) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; - if inner.seat_of.get(&id).map(String::as_str) != Some(community_id) { + if inner.seat_of.get(&id) != Some(&community_id) { return None; } inner.take(id, true, false) } - pub fn close_room(&self, community_id: &str) -> Vec { + pub fn close_room(&self, community_id: Id) -> Vec { let mut inner = self.0.lock().unwrap(); let ids: Vec = inner .rooms - .get(community_id) + .get(&community_id) .map(|room| room.seats.keys().copied().collect()) .unwrap_or_default(); @@ -409,24 +404,24 @@ impl Rooms { .collect() } - pub fn decline(&self, community_id: &str) { - if let Some(room) = self.0.lock().unwrap().rooms.get_mut(community_id) + pub fn decline(&self, community_id: Id) { + if let Some(room) = self.0.lock().unwrap().rooms.get_mut(&community_id) && matches!(room.outcome, Outcome::Ringing) { room.outcome = Outcome::Declined; } } - pub fn set_muted(&self, user_id: &str, muted: bool) -> Option { + pub fn set_muted(&self, user_id: Id, muted: bool) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; let (community_id, room) = inner.seat_mut(id)?; room.seats.get_mut(&id)?.muted = muted; - Some(community_id.to_string()) + Some(community_id) } - pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { + pub fn set_ghost(&self, user_id: Id, ghost: bool) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; let (community_id, room) = inner.seat_mut(id)?; @@ -453,8 +448,8 @@ impl Rooms { .flatten(); Some(Departure { - community_id: community_id.to_string(), - user_id: user_id.to_string(), + community_id, + user_id, ghost_seconds, call_log, shares, @@ -463,32 +458,32 @@ impl Rooms { }) } - pub fn room_of(&self, user_id: &str) -> Option { + pub fn room_of(&self, user_id: Id) -> Option { let inner = self.0.lock().unwrap(); - inner.seat_of.get(&inner.seat_conn(user_id)?).cloned() + inner.seat_of.get(&inner.seat_conn(user_id)?).copied() } - pub fn room_of_conn(&self, id: ConnId) -> Option { - self.0.lock().unwrap().seat_of.get(&id).cloned() + pub fn room_of_conn(&self, id: ConnId) -> Option { + self.0.lock().unwrap().seat_of.get(&id).copied() } - pub fn room_users(&self, community_id: &str) -> Vec { + pub fn room_users(&self, community_id: Id) -> Vec { self.0 .lock() .unwrap() .rooms - .get(community_id) + .get(&community_id) .map(|room| room.user_ids(|_| true)) .unwrap_or_default() } - pub fn participants(&self, community_id: &str) -> Vec { + pub fn participants(&self, community_id: Id) -> Vec { self.0 .lock() .unwrap() .rooms - .get(community_id) + .get(&community_id) .map(|room| room.user_ids(|seat| !seat.ghost)) .unwrap_or_default() } @@ -497,7 +492,7 @@ impl Rooms { self.0.lock().unwrap().seat_of.len() } - pub fn list(&self) -> Vec<(String, Vec, Vec)> { + pub fn list(&self) -> Vec<(Id, Vec, Vec)> { self.0 .lock() .unwrap() @@ -505,7 +500,7 @@ impl Rooms { .iter() .map(|(community_id, room)| { ( - community_id.clone(), + *community_id, room.user_ids(|_| true), room.user_ids(|seat| seat.ghost), ) @@ -513,9 +508,9 @@ impl Rooms { .collect() } - pub fn shares(&self, community_id: &str) -> Vec { + pub fn shares(&self, community_id: Id) -> Vec { let inner = self.0.lock().unwrap(); - let Some(room) = inner.rooms.get(community_id) else { + let Some(room) = inner.rooms.get(&community_id) else { return Vec::new(); }; @@ -523,7 +518,7 @@ impl Rooms { .values() .flat_map(|seat| { seat.shares.iter().map(|(kind, sharing)| Share { - user_id: seat.user_id.clone(), + user_id: seat.user_id, kind: *kind, source: sharing.source.clone(), }) @@ -537,7 +532,7 @@ impl Rooms { let seat = room.seats.get_mut(&id)?; let sharer = Sharer { conn: id, - user_id: &seat.user_id, + user_id: seat.user_id, community_id, kind, }; @@ -550,18 +545,18 @@ impl Rooms { Some(reroute(&sharer, sharing)) } - pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option { + pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option { let mut inner = self.0.lock().unwrap(); let (community_id, room) = inner.seat_mut(id)?; room.seats.get_mut(&id)?.shares.remove(&kind)?; - Some(community_id.to_string()) + Some(community_id) } pub fn watch( &self, id: ConnId, - sharer_id: &str, + sharer_id: Id, kind: Kind, quality: Quality, decode: &[Codec], @@ -570,13 +565,13 @@ impl Rooms { let sharer_conn = inner.seat_conn(sharer_id)?; let (_, room) = inner.seat_mut(id)?; let viewer_seat = room.seats.get(&id)?; - let (viewer_id, connection) = (viewer_seat.user_id.clone(), viewer_seat.connection.clone()); + let (viewer_id, connection) = (viewer_seat.user_id, viewer_seat.connection.clone()); let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; let before = sharing.layers(); let used: Vec = before.iter().copied().collect(); let layer = choose(&sharing.source, quality, decode, &used)?; let forward = sharing - .viewer(&viewer_id) + .viewer(viewer_id) .map_or(Forward::Waiting(layer), |viewer| { viewer.forward.retarget(layer) }); @@ -597,27 +592,27 @@ impl Rooms { Some(broadcasts) } - pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option { + pub fn unwatch(&self, id: ConnId, sharer_id: Id, kind: Kind) -> Option { let mut inner = self.0.lock().unwrap(); let sharer_conn = inner.seat_conn(sharer_id)?; let (_, room) = inner.seat_mut(id)?; - let viewer_id = room.seats.get(&id)?.user_id.clone(); + let viewer_id = room.seats.get(&id)?.user_id; let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; - remove_viewer(sharer_conn, kind, sharing, &viewer_id) + remove_viewer(sharer_conn, kind, sharing, viewer_id) } - pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option { + pub fn keyframe(&self, id: ConnId, sharer_id: Id, kind: Kind) -> Option { let mut inner = self.0.lock().unwrap(); let sharer_conn = inner.seat_conn(sharer_id)?; let (_, room) = inner.seat_mut(id)?; - let viewer_id = room.seats.get(&id)?.user_id.clone(); + let viewer_id = room.seats.get(&id)?.user_id; let viewer = room .seats .get(&sharer_conn)? .shares .get(&kind)? - .viewer(&viewer_id)?; + .viewer(viewer_id)?; Some(Broadcast::media( sharer_conn, @@ -655,8 +650,8 @@ fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) { } let mut echo = Vec::new(); Packet::Voice { seq, opus: &[] }.encode(&mut echo); - datagram::send(&sender.connection, relayed(&sender.uuid, &echo)); - let bytes = relayed(&sender.uuid, packet); + datagram::send(&sender.connection, relayed(&sender.prefix, &echo)); + let bytes = relayed(&sender.prefix, packet); for (other_id, seat) in &room.seats { if *other_id != id { datagram::send(&seat.connection, bytes.clone()); @@ -671,7 +666,7 @@ fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) { let Some(sharing) = seat.shares.get(&Kind::Screen) else { return; }; - let bytes = relayed(&seat.uuid, packet); + let bytes = relayed(&seat.prefix, packet); for viewer in &sharing.viewers { datagram::send(&viewer.connection, bytes.clone()); } @@ -691,7 +686,7 @@ fn relay_video( let Some(sharing) = seat.shares.get_mut(&kind) else { return Vec::new(); }; - let bytes = relayed(&seat.uuid, packet); + let bytes = relayed(&seat.prefix, packet); let before = keyframe.then(|| sharing.layers()); for viewer in &mut sharing.viewers { if keyframe { diff --git a/crates/server/src/server_ban.rs b/crates/server/src/server_ban.rs deleted file mode 100644 index f88ba95..0000000 --- a/crates/server/src/server_ban.rs +++ /dev/null @@ -1,80 +0,0 @@ -use common::{ - error::Error as CommonError, - model::{ServerBan, ServerBanKind}, -}; -use turso::Connection; - -use crate::{ - database::{self, new_id}, - error::ServerError, -}; - -pub async fn insert( - kind: ServerBanKind, - value: &str, - reason: Option<&str>, - created_by: &str, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "INSERT INTO server_ban (id, kind, value, reason, created_by) - SELECT ?1, ?2, ?3, ?4, ?5 WHERE NOT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?2 AND value = ?3)", - (new_id(), kind.as_str(), value, reason, created_by), - ) - .await?; - - Ok(()) -} - -pub async fn list(conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", - (), - ) - .await?; - - let mut bans = Vec::new(); - while let Some(row) = rows.next().await? { - let text: String = row.get(1)?; - bans.push(ServerBan { - id: row.get(0)?, - kind: ServerBanKind::parse(&text).ok_or(CommonError::Server)?, - value: row.get(2)?, - reason: row.get(3)?, - }); - } - - Ok(bans) -} - -async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result { - database::exists( - conn, - "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", - (kind.as_str(), value), - ) - .await -} - -pub async fn username_banned(username: &str, conn: &Connection) -> Result { - exists( - ServerBanKind::Username, - &username.to_ascii_lowercase(), - conn, - ) - .await -} - -pub async fn ip_banned(ip: &str, conn: &Connection) -> Result { - exists(ServerBanKind::Ip, ip, conn).await -} - -pub async fn remove(id: &str, conn: &Connection) -> Result<(), ServerError> { - let mut rows = conn - .query("DELETE FROM server_ban WHERE id = ?1 RETURNING id", (id,)) - .await?; - rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(()) -} diff --git a/crates/server/src/server_settings.rs b/crates/server/src/server_settings.rs deleted file mode 100644 index 4e55eb9..0000000 --- a/crates/server/src/server_settings.rs +++ /dev/null @@ -1,71 +0,0 @@ -use common::model::ServerSettings; -use turso::Connection; - -use crate::{error::ServerError, user}; - -const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute"; - -fn assignments() -> String { - COLUMNS - .split(", ") - .enumerate() - .map(|(index, column)| format!("{column} = ?{}", index + 1)) - .collect::>() - .join(", ") -} - -pub async fn read(conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"), - (), - ) - .await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let int = |index: usize| -> Result { Ok(row.get(index)?) }; - - Ok(ServerSettings { - name: row.get(0)?, - registration_open: user::bool_at(&row, 1)?, - max_attachment_bytes: int(2)? as u64, - maintenance: user::bool_at(&row, 3)?, - user_quota_bytes: int(4)? as u64, - community_quota_bytes: int(5)? as u64, - message_retention_days: int(6)? as u32, - attachment_retention_days: int(7)? as u32, - announcement: row.get(8)?, - max_communities_per_user: int(9)? as u32, - max_message_length: int(10)? as u32, - max_avatar_bytes: int(11)? as u64, - messages_per_minute: int(12)? as u32, - logins_per_minute: int(13)? as u32, - }) -} - -pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), ServerError> { - conn.execute( - &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()), - ( - settings.name.as_str(), - i64::from(settings.registration_open), - settings.max_attachment_bytes as i64, - i64::from(settings.maintenance), - settings.user_quota_bytes as i64, - settings.community_quota_bytes as i64, - i64::from(settings.message_retention_days), - i64::from(settings.attachment_retention_days), - settings.announcement.as_str(), - i64::from(settings.max_communities_per_user), - i64::from(settings.max_message_length), - settings.max_avatar_bytes as i64, - i64::from(settings.messages_per_minute), - i64::from(settings.logins_per_minute), - ), - ) - .await?; - - Ok(()) -} diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs deleted file mode 100644 index 867713c..0000000 --- a/crates/server/src/stats.rs +++ /dev/null @@ -1,61 +0,0 @@ -use common::{ - model::DayStat, - time::{self, DAY_MILLIS}, -}; -use turso::Connection; - -use crate::{database, error::ServerError, user}; - -const MAXIMUM_DAYS: u32 = 90; - -pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), ServerError> { - if user::is_ghost(user_id, conn).await? { - return Ok(()); - } - let day = (time::now_ms() / DAY_MILLIS) as i64; - conn.execute( - "INSERT OR IGNORE INTO daily_active (day, user_id) VALUES (?1, ?2)", - (day, user_id), - ) - .await?; - - Ok(()) -} - -pub async fn daily(days: u32, conn: &Connection) -> Result, ServerError> { - let days = u64::from(days.clamp(1, MAXIMUM_DAYS)); - let today = time::now_ms() / DAY_MILLIS; - let mut stats = Vec::new(); - - for day in (today + 1 - days)..=today { - let start = time::id_bound(day * DAY_MILLIS); - let end = time::id_bound((day + 1) * DAY_MILLIS); - let active_users = count( - conn, - "SELECT COUNT(*) FROM daily_active WHERE day = ?1", - (day as i64,), - ) - .await?; - let messages = count( - conn, - "SELECT COUNT(*) FROM message WHERE id >= ?1 AND id < ?2", - (start.as_str(), end.as_str()), - ) - .await?; - stats.push(DayStat { - day, - active_users, - messages, - }); - } - - Ok(stats) -} - -async fn count( - conn: &Connection, - sql: &str, - params: impl turso::IntoParams, -) -> Result { - Ok(database::scalar_i64(conn, sql, params).await? as u64) -} diff --git a/crates/server/src/test.rs b/crates/server/src/test.rs index f413ee0..7fca0b7 100644 --- a/crates/server/src/test.rs +++ b/crates/server/src/test.rs @@ -1,9 +1,9 @@ use std::path::PathBuf; -use crate::database::{self, DB}; +use crate::db::Db; -pub async fn get_database() -> DB { - database::open(":memory:").await.unwrap() +pub async fn db() -> Db { + Db::open(":memory:").await.unwrap() } pub fn directory() -> PathBuf { diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs deleted file mode 100644 index 50a7820..0000000 --- a/crates/server/src/user.rs +++ /dev/null @@ -1,555 +0,0 @@ -use common::{ - constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, - error::{Error as CommonError, Field, Problem}, - model::{Account, Presence, Role, User}, - permission, time, - validate::{validate_avatar_size, validate_status, validate_username}, -}; -use image::ImageFormat; -use turso::{Connection, Row}; - -use crate::{ - database::{self, new_id}, - error::ServerError, -}; - -pub fn user_columns(alias: &str) -> String { - format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") -} - -pub fn from_row_at(row: &Row, start: usize) -> Result, ServerError> { - let Some(id) = row.get::>(start)? else { - return Ok(None); - }; - let role: String = row.get(start + 2)?; - - Ok(Some(User { - id, - username: row.get(start + 1)?, - role: Role::parse(&role).ok_or(CommonError::Server)?, - status: row.get(start + 3)?, - avatar_id: row.get(start + 4)?, - })) -} - -pub fn from_row(row: &Row) -> Result { - Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?) -} - -pub fn bool_at(row: &Row, index: usize) -> Result { - let flag: i64 = row.get(index)?; - - Ok(flag != 0) -} - -async fn one( - sql: &str, - params: impl turso::IntoParams, - conn: &Connection, -) -> Result { - let mut rows = conn.query(sql, params).await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) -} - -async fn set( - column: &str, - params: impl turso::IntoParams, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"), - params, - ) - .await?; - - Ok(()) -} - -async fn set_returning( - column: &str, - params: impl turso::IntoParams, - conn: &Connection, -) -> Result { - one( - &format!( - "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - params, - conn, - ) - .await -} - -pub async fn create( - username: &str, - password_hash: &str, - conn: &Connection, -) -> Result { - one( - &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")), - ( - new_id(), - username, - password_hash, - Role::User.as_str(), - Role::Builder.as_str(), - ), - conn, - ) - .await -} - -pub async fn read(user_id: &str, conn: &Connection) -> Result { - one( - &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), - (user_id,), - conn, - ) - .await -} - -pub async fn any(conn: &Connection) -> Result { - database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await -} - -pub async fn by_username(username: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!( - "SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE", - user_columns("user") - ), - (username,), - ) - .await?; - - rows.next().await?.as_ref().map(from_row).transpose() -} - -pub async fn is_taken( - username: &str, - except_id: Option<&str>, - conn: &Connection, -) -> Result { - Ok(by_username(username, conn) - .await? - .is_some_and(|existing| Some(existing.id.as_str()) != except_id)) -} - -pub async fn by_session_token(token: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user_columns("user")), - (token,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?; - - from_row(&row) -} - -pub async fn credentials( - username: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - &format!( - "SELECT {}, password_hash FROM user WHERE username = ?1", - user_columns("user") - ), - (username,), - ) - .await?; - let Some(row) = rows.next().await? else { - return Ok(None); - }; - - Ok(Some((from_row(&row)?, row.get(5)?))) -} - -pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result { - validate_username(username)?; - - if is_taken(username, Some(user_id), conn).await? { - return Err(CommonError::Taken.into()); - } - - set_returning("username", (user_id, username), conn).await -} - -pub async fn update_status( - user_id: &str, - status: &str, - conn: &Connection, -) -> Result { - validate_status(status)?; - - set_returning("status", (user_id, status), conn).await -} - -pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> { - validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; - let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { - CommonError::Invalid { - field: Field::Avatar, - problem: Problem::NotJpeg, - } - })?; - if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { - return Err(CommonError::Invalid { - field: Field::Avatar, - problem: Problem::Dimensions { - expected: AVATAR_SIZE, - }, - } - .into()); - } - - Ok(()) -} - -pub async fn set_avatar( - user_id: &str, - avatar: Option<&[u8]>, - conn: &mut Connection, -) -> Result { - if let Some(bytes) = avatar { - check_avatar(bytes)?; - } - - let avatar_id = avatar.map(|_| new_id()); - let tx = conn.transaction().await?; - tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,)) - .await?; - if let (Some(avatar_id), Some(bytes)) = (&avatar_id, avatar) { - tx.execute( - "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)", - (avatar_id.as_str(), user_id, bytes), - ) - .await?; - } - let user = set_avatar_id(user_id, avatar_id.as_deref(), &tx).await?; - tx.commit().await?; - - Ok(user) -} - -async fn set_avatar_id( - user_id: &str, - avatar_id: Option<&str>, - conn: &Connection, -) -> Result { - set_returning("avatar_id", (user_id, avatar_id), conn).await -} - -pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT data FROM avatar WHERE id = ?1 UNION ALL SELECT data FROM community_avatar WHERE id = ?1", - (avatar_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(row.get(0)?) -} - -pub async fn set_role_by_id( - user_id: &str, - role: Role, - conn: &Connection, -) -> Result { - set_returning("role", (user_id, role.as_str()), conn).await -} - -pub async fn suspended( - user_id: &str, - conn: &Connection, -) -> Result>, ServerError> { - let mut rows = conn - .query( - "SELECT suspended, suspended_until FROM user WHERE id = ?1", - (user_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let until: Option = row.get::>(1)?.map(|until| until as u64); - - if bool_at(&row, 0)? { - return Ok(Some(None)); - } - - Ok(until.filter(|until| *until > time::now_ms()).map(Some)) -} - -pub async fn set_timeout( - user_id: &str, - until: Option, - conn: &Connection, -) -> Result<(), ServerError> { - set( - "suspended_until", - (user_id, until.map(|until| until as i64)), - conn, - ) - .await -} - -pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), ServerError> { - set("last_ip", (user_id, ip), conn).await -} - -pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query("SELECT last_ip FROM user WHERE id = ?1", (user_id,)) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - Ok(row.get(0)?) -} - -pub async fn builder_ids(conn: &Connection) -> Result, ServerError> { - database::ids( - conn, - "SELECT id FROM user WHERE role = ?1", - (Role::Builder.as_str(),), - ) - .await -} - -pub async fn set_suspended( - user_id: &str, - suspended: bool, - conn: &Connection, -) -> Result<(), ServerError> { - set("suspended", (user_id, i64::from(suspended)), conn).await -} - -pub async fn set_voice_muted( - user_id: &str, - muted: bool, - conn: &Connection, -) -> Result<(), ServerError> { - set("voice_muted", (user_id, i64::from(muted)), conn).await -} - -pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), ServerError> { - set("ghost", (user_id, i64::from(ghost)), conn).await -} - -pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query("SELECT ghost FROM user WHERE id = ?1", (user_id,)) - .await?; - let Some(row) = rows.next().await? else { - return Ok(false); - }; - - bool_at(&row, 0) -} - -pub async fn presence(user_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query("SELECT presence FROM user WHERE id = ?1", (user_id,)) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let text: String = row.get(0)?; - - Ok(Presence::parse(&text).ok_or(CommonError::Server)?) -} - -pub async fn update_presence( - user_id: &str, - presence: Presence, - conn: &Connection, -) -> Result<(), ServerError> { - set("presence", (user_id, presence.as_str()), conn).await -} - -pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - "SELECT voice_muted, role FROM user WHERE id = ?1", - (user_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let role: String = row.get(1)?; - let builder = Role::parse(&role).is_some_and(permission::is_builder); - - Ok(bool_at(&row, 0)? && !builder) -} - -pub async fn set_password_hash( - user_id: &str, - password_hash: &str, - conn: &Connection, -) -> Result<(), ServerError> { - set("password_hash", (user_id, password_hash), conn).await -} - -pub async fn all(conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT {}, suspended, last_seen, suspended_until, ghost FROM user ORDER BY username COLLATE NOCASE", user_columns("user")), - (), - ) - .await?; - let mut accounts = Vec::new(); - while let Some(row) = rows.next().await? { - let last_seen: Option = row.get(6)?; - let suspended_until: Option = row.get(7)?; - accounts.push(Account { - user: from_row(&row)?, - suspended: bool_at(&row, 5)?, - last_seen: last_seen.map(|millis| millis as u64), - suspended_until: suspended_until.map(|millis| millis as u64), - ghost: bool_at(&row, 8)?, - }); - } - - Ok(accounts) -} - -pub async fn delete(user_id: &str, conn: &Connection) -> Result { - one( - &format!( - "DELETE FROM user WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id,), - conn, - ) - .await -} - -#[cfg(test)] -mod tests { - use std::io::Cursor; - - use common::{ - constant::AVATAR_SIZE, - error::{Error as CommonError, Field}, - }; - use image::{ImageFormat, RgbImage}; - - use crate::{database, error::ServerError, test, user}; - - fn jpeg(size: u32) -> Vec { - let mut bytes = Cursor::new(Vec::new()); - RgbImage::new(size, size) - .write_to(&mut bytes, ImageFormat::Jpeg) - .unwrap(); - - bytes.into_inner() - } - - #[tokio::test] - async fn set_avatar_checks_jpeg_size() { - let db = test::get_database().await; - let mut conn = database::connect(&db).await.unwrap(); - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - - let small = - user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await; - let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await; - let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn) - .await - .unwrap(); - - assert!(matches!( - small, - Err(ServerError::Wire(CommonError::Invalid { - field: Field::Avatar, - .. - })) - )); - assert!(matches!( - not_jpeg, - Err(ServerError::Wire(CommonError::Invalid { - field: Field::Avatar, - .. - })) - )); - let avatar_id = valid.avatar_id.unwrap(); - assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty()); - } - - #[tokio::test] - async fn create() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); - - assert_eq!("Tahinli", user.username); - } - - #[tokio::test] - async fn read() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let searched_user = user::read(&created_user.id, &conn).await.unwrap(); - - assert_eq!(created_user, searched_user); - } - - #[tokio::test] - async fn read_by_username() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - - let searched_user = user::by_username("tahinli", &conn).await.unwrap(); - - assert_eq!(Some(created_user), searched_user); - } - - #[tokio::test] - async fn update() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let updated_user = user::update(&created_user.id, "Not Tahinli", &conn) - .await - .unwrap(); - let searched_user = user::read(&created_user.id, &conn).await.unwrap(); - - assert_eq!(created_user.id, searched_user.id); - assert_eq!(updated_user, searched_user); - assert_eq!("Not Tahinli", searched_user.username); - } - - #[tokio::test] - async fn update_on_missing_user() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let updated_user = user::update("missing", "Not Tahinli", &conn).await; - - assert!(matches!( - updated_user, - Err(ServerError::Wire(CommonError::NotFound)) - )); - } - - #[tokio::test] - async fn delete() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let deleted_user = user::delete(&created_user.id, &conn).await.unwrap(); - - assert_eq!(created_user, deleted_user); - } -} diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs deleted file mode 100644 index 2bf0309..0000000 --- a/crates/server/src/user_community.rs +++ /dev/null @@ -1,411 +0,0 @@ -use std::collections::HashMap; - -use common::{ - error::Error as CommonError, - model::{Ban, Member, Rank, Unread, mentions}, -}; -use turso::{Connection, Row}; - -use crate::{community, database, error::ServerError, user}; - -fn rank_of(row: &Row, index: usize) -> Result { - let text: String = row.get(index)?; - - Ok(Rank::parse(&text).ok_or(CommonError::Server)?) -} - -pub async fn join( - user_id: &str, - community_id: &str, - rank: Rank, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "INSERT INTO user_community (user_id, community_id, rank) VALUES (?1, ?2, ?3)", - (user_id, community_id, rank.as_str()), - ) - .await?; - - Ok(()) -} - -pub async fn leave( - user_id: &str, - community_id: &str, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", - (user_id, community_id), - ) - .await?; - - Ok(()) -} - -pub async fn rank( - user_id: &str, - community_id: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT rank FROM user_community WHERE user_id = ?1 AND community_id = ?2", - (user_id, community_id), - ) - .await?; - - rows.next() - .await? - .as_ref() - .map(|row| rank_of(row, 0)) - .transpose() -} - -pub async fn set_rank( - user_id: &str, - community_id: &str, - rank: Rank, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "UPDATE user_community SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", - (user_id, community_id, rank.as_str()), - ) - .await?; - - Ok(()) -} - -pub async fn mark_read( - user_id: &str, - community_id: &str, - message_id: &str, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", - (user_id, community_id, message_id), - ) - .await?; - - Ok(()) -} - -pub async fn unreads( - user_id: &str, - username: &str, - conn: &Connection, -) -> Result, ServerError> { - let mut rows = conn - .query( - "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), uc.last_read FROM user_community uc WHERE uc.user_id = ?1", - (user_id,), - ) - .await?; - - let mut unreads = Vec::new(); - while let Some(row) = rows.next().await? { - let messages: i64 = row.get(1)?; - unreads.push(Unread { - community_id: row.get(0)?, - messages: messages as u32, - mentions: 0, - last_read: row.get::>(2)?, - }); - } - - let mention = format!("@{}", username.to_lowercase()); - let mut rows = conn - .query( - "SELECT m.community_id, m.body FROM message m JOIN user_community uc ON uc.community_id = m.community_id AND uc.user_id = ?1 WHERE m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read) AND instr(lower(m.body), ?2) > 0", - (user_id, mention.as_str()), - ) - .await?; - - let mut mention_counts: HashMap = HashMap::new(); - while let Some(row) = rows.next().await? { - let body: String = row.get(1)?; - if mentions(&body, username) { - *mention_counts.entry(row.get::(0)?).or_default() += 1; - } - } - - for unread in &mut unreads { - unread.mentions = mention_counts - .get(&unread.community_id) - .copied() - .unwrap_or_default(); - } - - Ok(unreads) -} - -pub async fn member_ids(community_id: &str, conn: &Connection) -> Result, ServerError> { - database::ids( - conn, - "SELECT user_id FROM user_community WHERE community_id = ?1", - (community_id,), - ) - .await -} - -pub async fn members(community_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT {}, user_community.rank FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", user::user_columns("user")), - (community_id,), - ) - .await?; - - let mut members = Vec::new(); - while let Some(row) = rows.next().await? { - members.push(Member { - user: user::from_row(&row)?, - rank: rank_of(&row, 5)?, - }); - } - - Ok(members) -} - -pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result { - let count = database::scalar_i64( - conn, - "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3", - (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), - ) - .await?; - - Ok(count as usize) -} - -pub async fn owned(user_id: &str, conn: &Connection) -> Result, ServerError> { - database::ids( - conn, - "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", - (user_id, Rank::Owner.as_str()), - ) - .await -} - -pub async fn ban( - user_id: &str, - community_id: &str, - reason: Option<&str>, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "INSERT OR REPLACE INTO ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", - (user_id, community_id, reason), - ) - .await?; - - Ok(()) -} - -pub async fn unban( - user_id: &str, - community_id: &str, - conn: &Connection, -) -> Result<(), ServerError> { - conn.execute( - "DELETE FROM ban WHERE user_id = ?1 AND community_id = ?2", - (user_id, community_id), - ) - .await?; - - Ok(()) -} - -pub async fn is_banned( - user_id: &str, - community_id: &str, - conn: &Connection, -) -> Result { - database::exists( - conn, - "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)", - (user_id, community_id), - ) - .await -} - -pub async fn bans(community_id: &str, conn: &Connection) -> Result, ServerError> { - let mut rows = conn - .query( - &format!("SELECT {}, ban.reason FROM user JOIN ban ON ban.user_id = user.id WHERE ban.community_id = ?1 ORDER BY ban.rowid DESC", user::user_columns("user")), - (community_id,), - ) - .await?; - - let mut bans = Vec::new(); - while let Some(row) = rows.next().await? { - bans.push(Ban { - user: user::from_row(&row)?, - reason: row.get(5)?, - }); - } - - Ok(bans) -} - -#[cfg(test)] -mod tests { - use common::model::{Member, Rank}; - - use crate::{community, database, test, user, user_community}; - - #[tokio::test] - async fn join() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let member = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("The Community", &conn).await.unwrap(); - - user_community::join(&member.id, &community.id, Rank::Member, &conn) - .await - .unwrap(); - - assert_eq!( - Some(Rank::Member), - user_community::rank(&member.id, &community.id, &conn) - .await - .unwrap() - ); - assert_eq!( - None, - user_community::rank(&owner.id, &community.id, &conn) - .await - .unwrap() - ); - } - - #[tokio::test] - async fn join_again() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("The Community", &conn).await.unwrap(); - - user_community::join(&owner.id, &community.id, Rank::Owner, &conn) - .await - .unwrap(); - - assert!( - user_community::join(&owner.id, &community.id, Rank::Member, &conn) - .await - .is_err() - ); - } - - #[tokio::test] - async fn leave() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("The Community", &conn).await.unwrap(); - user_community::join(&owner.id, &community.id, Rank::Owner, &conn) - .await - .unwrap(); - - user_community::leave(&owner.id, &community.id, &conn) - .await - .unwrap(); - - assert_eq!( - None, - user_community::rank(&owner.id, &community.id, &conn) - .await - .unwrap() - ); - } - - #[tokio::test] - async fn members() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); - let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - let _user_3 = user::create("Third Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("The Community", &conn).await.unwrap(); - - user_community::join(&user_1.id, &community.id, Rank::Owner, &conn) - .await - .unwrap(); - user_community::join(&user_2.id, &community.id, Rank::Member, &conn) - .await - .unwrap(); - - let members = user_community::members(&community.id, &conn).await.unwrap(); - - assert_eq!( - vec![ - Member { - user: user_1, - rank: Rank::Owner - }, - Member { - user: user_2, - rank: Rank::Member - }, - ], - members - ); - } - - #[tokio::test] - async fn ban_and_unban() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let member = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - let community = community::create("The Community", &conn).await.unwrap(); - user_community::join(&member.id, &community.id, Rank::Member, &conn) - .await - .unwrap(); - - user_community::ban(&member.id, &community.id, None, &conn) - .await - .unwrap(); - let banned = user_community::is_banned(&member.id, &community.id, &conn) - .await - .unwrap(); - user_community::unban(&member.id, &community.id, &conn) - .await - .unwrap(); - - assert!(banned); - assert!( - !user_community::is_banned(&member.id, &community.id, &conn) - .await - .unwrap() - ); - assert!( - user_community::bans(&community.id, &conn) - .await - .unwrap() - .is_empty() - ); - } - - #[tokio::test] - async fn communities_of() { - let db = test::get_database().await; - let conn = database::connect(&db).await.unwrap(); - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); - let community_1 = community::create("The Community", &conn).await.unwrap(); - let community_2 = community::create("The Community", &conn).await.unwrap(); - - user_community::join(&owner.id, &community_1.id, Rank::Owner, &conn) - .await - .unwrap(); - user_community::join(&owner.id, &community_2.id, Rank::Owner, &conn) - .await - .unwrap(); - - let communities_of = community::communities_of(&owner.id, &conn).await.unwrap(); - - assert_eq!(vec![community_1, community_2], communities_of); - } -}