One clean schema, integer ids and one transaction per call
Browse files at this commit22b1bb749547306d0141d16b5073e40e78fc1e3bParent: 7bb542d- refactor
- one clean schema, integer ids and one transaction per call
107 changed files +5819 -6983
- crates/client/Cargo.toml +0 -1
- crates/client/src/accounts.rs +21 -17
- crates/client/src/gui.rs +62 -75
- crates/client/src/gui/auth.rs +5 -5
- crates/client/src/gui/builder.rs +9 -12
- crates/client/src/gui/builder/access.rs +5 -5
- crates/client/src/gui/builder/backups.rs +1 -1
- crates/client/src/gui/builder/communities.rs +31 -48
- crates/client/src/gui/builder/log.rs +26 -8
- crates/client/src/gui/builder/messages.rs +16 -21
- crates/client/src/gui/builder/reports.rs +18 -22
- crates/client/src/gui/builder/storage.rs +7 -8
- crates/client/src/gui/builder/ui.rs +3 -3
- crates/client/src/gui/builder/users.rs +75 -102
- crates/client/src/gui/builder/voice.rs +13 -14
- crates/client/src/gui/camera_view.rs +18 -20
- crates/client/src/gui/chat.rs +227 -274
- crates/client/src/gui/community_settings.rs +26 -37
- crates/client/src/gui/composer.rs +35 -43
- crates/client/src/gui/forward.rs +9 -9
- crates/client/src/gui/media_view.rs +25 -23
- crates/client/src/gui/message_actions.rs +23 -27
- crates/client/src/gui/poll.rs +12 -14
- crates/client/src/gui/profile.rs +50 -58
- crates/client/src/gui/settings_page.rs +1 -1
- crates/client/src/gui/share_view.rs +21 -22
- crates/client/src/gui/sidebar.rs +56 -62
- crates/client/src/gui/snippet.rs +8 -7
- crates/client/src/gui/social.rs +27 -40
- crates/client/src/gui/voice_note.rs +2 -2
- crates/client/src/gui/voice_stats.rs +5 -6
- crates/client/src/gui/wave.rs +16 -18
- crates/client/src/mutes.rs +6 -4
- crates/client/src/net/link.rs +5 -5
- crates/client/src/net/media.rs +37 -58
- crates/client/src/net/mod.rs +9 -10
- crates/client/src/settings.rs +3 -2
- crates/client/src/share/session.rs +2 -1
- crates/client/src/voice/engine.rs +8 -8
- crates/client/src/voice/mod.rs +2 -1
- crates/common/Cargo.toml +0 -1
- crates/common/src/call.rs +90 -90
- crates/common/src/datagram.rs +6 -2
- crates/common/src/event.rs +24 -23
- crates/common/src/model.rs +54 -52
- crates/common/src/open.rs +4 -4
- crates/common/src/share.rs +2 -2
- crates/common/src/time.rs +0 -20
- crates/server/Cargo.toml +2 -2
- crates/server/src/admin_log.rs +0 -117
- crates/server/src/attachment.rs +0 -746
- crates/server/src/authentication.rs +172 -171
- crates/server/src/backup.rs +27 -35
- crates/server/src/call/admin.rs +218 -285
- crates/server/src/call/community.rs +101 -132
- crates/server/src/call/message.rs +83 -90
- crates/server/src/call/mod.rs +21 -14
- crates/server/src/call/social.rs +82 -88
- crates/server/src/call/user.rs +31 -30
- crates/server/src/call/voice.rs +61 -59
- crates/server/src/community.rs +0 -405
- crates/server/src/database.rs +0 -375
- crates/server/src/datagram.rs +8 -2
- crates/server/src/db/attachment.rs +268 -0
- crates/server/src/db/avatar.rs +52 -0
- crates/server/src/db/community.rs +182 -0
- crates/server/src/db/direct.rs +47 -0
- crates/server/src/db/friend.rs +104 -0
- crates/server/src/db/invitation.rs +63 -0
- crates/server/src/db/log.rs +134 -0
- crates/server/src/db/member.rs +234 -0
- crates/server/src/db/message.rs +513 -0
- crates/server/src/db/mod.rs +167 -0
- crates/server/src/db/poll.rs +114 -0
- crates/server/src/db/registration_code.rs +60 -0
- crates/server/src/db/report.rs +126 -0
- crates/server/src/db/schema.sql +215 -0
- crates/server/src/db/server_ban.rs +63 -0
- crates/server/src/db/session.rs +109 -0
- crates/server/src/db/settings.rs +26 -0
- crates/server/src/db/snippet.rs +94 -0
- crates/server/src/db/stats.rs +69 -0
- crates/server/src/db/user.rs +314 -0
- crates/server/src/direct.rs +0 -51
- crates/server/src/error.rs +31 -1
- crates/server/src/files.rs +497 -0
- crates/server/src/friend.rs +0 -141
- crates/server/src/hub.rs +27 -38
- crates/server/src/invitation.rs +0 -72
- crates/server/src/invite.rs +0 -89
- crates/server/src/lib.rs +16 -29
- crates/server/src/log.rs +0 -105
- crates/server/src/message.rs +0 -860
- crates/server/src/network.rs +83 -53
- crates/server/src/notes.rs +0 -36
- crates/server/src/overview.rs +0 -36
- crates/server/src/publish.rs +40 -31
- crates/server/src/report.rs +0 -92
- crates/server/src/request.rs +152 -167
- crates/server/src/retention.rs +30 -82
- crates/server/src/rooms.rs +75 -80
- crates/server/src/server_ban.rs +0 -80
- crates/server/src/server_settings.rs +0 -71
- crates/server/src/stats.rs +0 -61
- crates/server/src/test.rs +3 -3
- crates/server/src/user.rs +0 -555
- crates/server/src/user_community.rs +0 -411
crates/client/Cargo.tomlmodified+0 -1
| @@ -25,7 +25,6 @@ ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d9 | |||
| 25 | ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 25 | ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 26 | ureq = "3.5.2" | 26 | ureq = "3.5.2" |
| 27 | bytes = "1.12.2" | 27 | bytes = "1.12.2" |
| 28 | -uuid = "1.29.3" | ||
| 29 | tracing = "0.1.44" | 28 | tracing = "0.1.44" |
| 30 | tracing-subscriber = "0.3.23" | 29 | tracing-subscriber = "0.3.23" |
| 31 | jiff = "1.0.2" | 30 | jiff = "1.0.2" |
crates/client/src/accounts.rsmodified+21 -17
| @@ -1,10 +1,10 @@ | |||
| 1 | -use common::model::User; | 1 | +use common::model::{Id, User}; |
| 2 | 2 | ||
| 3 | use crate::{read_config, write_config}; | 3 | use crate::{read_config, write_config}; |
| 4 | 4 | ||
| 5 | #[derive(Debug, Clone, PartialEq, Eq)] | 5 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 6 | pub struct Account { | 6 | pub struct Account { |
| 7 | - pub user_id: String, | 7 | + pub user_id: Id, |
| 8 | pub username: String, | 8 | pub username: String, |
| 9 | pub token: String, | 9 | pub token: String, |
| 10 | } | 10 | } |
| @@ -12,28 +12,28 @@ pub struct Account { | |||
| 12 | #[derive(Debug, Clone, Default)] | 12 | #[derive(Debug, Clone, Default)] |
| 13 | pub struct Accounts { | 13 | pub struct Accounts { |
| 14 | pub list: Vec<Account>, | 14 | pub list: Vec<Account>, |
| 15 | - pub active: Option<String>, | 15 | + pub active: Option<Id>, |
| 16 | } | 16 | } |
| 17 | 17 | ||
| 18 | impl Accounts { | 18 | impl Accounts { |
| 19 | - pub fn get(&self, user_id: &str) -> Option<&Account> { | 19 | + pub fn get(&self, user_id: Id) -> Option<&Account> { |
| 20 | self.list.iter().find(|account| account.user_id == user_id) | 20 | self.list.iter().find(|account| account.user_id == user_id) |
| 21 | } | 21 | } |
| 22 | 22 | ||
| 23 | pub fn others(&self) -> impl Iterator<Item = &Account> { | 23 | pub fn others(&self) -> impl Iterator<Item = &Account> { |
| 24 | self.list | 24 | self.list |
| 25 | .iter() | 25 | .iter() |
| 26 | - .filter(|account| Some(&account.user_id) != self.active.as_ref()) | 26 | + .filter(|account| Some(account.user_id) != self.active) |
| 27 | } | 27 | } |
| 28 | 28 | ||
| 29 | pub fn sign_in(&mut self, user: &User, token: String) { | 29 | pub fn sign_in(&mut self, user: &User, token: String) { |
| 30 | - self.remove(&user.id); | 30 | + self.remove(user.id); |
| 31 | self.list.push(Account { | 31 | self.list.push(Account { |
| 32 | - user_id: user.id.clone(), | 32 | + user_id: user.id, |
| 33 | username: user.username.clone(), | 33 | username: user.username.clone(), |
| 34 | token, | 34 | token, |
| 35 | }); | 35 | }); |
| 36 | - self.active = Some(user.id.clone()); | 36 | + self.active = Some(user.id); |
| 37 | save(self); | 37 | save(self); |
| 38 | } | 38 | } |
| 39 | 39 | ||
| @@ -57,15 +57,15 @@ impl Accounts { | |||
| 57 | save(self); | 57 | save(self); |
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | - pub fn forget(&mut self, user_id: &str) { | 60 | + pub fn forget(&mut self, user_id: Id) { |
| 61 | self.remove(user_id); | 61 | self.remove(user_id); |
| 62 | - if self.active.as_deref() == Some(user_id) { | 62 | + if self.active == Some(user_id) { |
| 63 | self.active = None; | 63 | self.active = None; |
| 64 | } | 64 | } |
| 65 | save(self); | 65 | save(self); |
| 66 | } | 66 | } |
| 67 | 67 | ||
| 68 | - fn remove(&mut self, user_id: &str) { | 68 | + fn remove(&mut self, user_id: Id) { |
| 69 | self.list.retain(|account| account.user_id != user_id); | 69 | self.list.retain(|account| account.user_id != user_id); |
| 70 | } | 70 | } |
| 71 | } | 71 | } |
| @@ -78,12 +78,16 @@ pub fn load() -> Accounts { | |||
| 78 | 78 | ||
| 79 | for line in content.lines() { | 79 | for line in content.lines() { |
| 80 | match line.split('\t').collect::<Vec<_>>().as_slice() { | 80 | match line.split('\t').collect::<Vec<_>>().as_slice() { |
| 81 | - ["active", user_id] => accounts.active = Some(user_id.to_string()), | 81 | + ["active", user_id] => accounts.active = user_id.parse().ok(), |
| 82 | - [user_id, username, token] => accounts.list.push(Account { | 82 | + [user_id, username, token] => { |
| 83 | - user_id: user_id.to_string(), | 83 | + if let Ok(user_id) = user_id.parse() { |
| 84 | - username: username.to_string(), | 84 | + accounts.list.push(Account { |
| 85 | - token: token.to_string(), | 85 | + user_id, |
| 86 | - }), | 86 | + username: username.to_string(), |
| 87 | + token: token.to_string(), | ||
| 88 | + }); | ||
| 89 | + } | ||
| 90 | + } | ||
| 87 | _ => {} | 91 | _ => {} |
| 88 | } | 92 | } |
| 89 | } | 93 | } |
crates/client/src/gui.rsmodified+62 -75
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::{ | 2 | use std::{ |
| 2 | collections::HashMap, | 3 | collections::HashMap, |
| 3 | fmt::Display, | 4 | fmt::Display, |
| @@ -15,7 +16,6 @@ use common::{ | |||
| 15 | BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, | 16 | BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, |
| 16 | ServerSettings, Unread, User, mentions, | 17 | ServerSettings, Unread, User, mentions, |
| 17 | }, | 18 | }, |
| 18 | - time::created_at_ms, | ||
| 19 | }; | 19 | }; |
| 20 | use gpui_kit::{ | 20 | use gpui_kit::{ |
| 21 | Anchor, Animation, AnimationElement, AnimationExt, AnyElement, AnyWindowHandle, App, | 21 | Anchor, Animation, AnimationElement, AnimationExt, AnyElement, AnyWindowHandle, App, |
| @@ -100,7 +100,7 @@ pub struct Palette { | |||
| 100 | } | 100 | } |
| 101 | 101 | ||
| 102 | impl Palette { | 102 | impl Palette { |
| 103 | - pub fn tinted(self, id: &str) -> Hsla { | 103 | + pub fn tinted(self, id: Id) -> Hsla { |
| 104 | let color = tint(id); | 104 | let color = tint(id); |
| 105 | if self.dark { | 105 | if self.dark { |
| 106 | color | 106 | color |
| @@ -109,7 +109,7 @@ impl Palette { | |||
| 109 | } | 109 | } |
| 110 | } | 110 | } |
| 111 | 111 | ||
| 112 | - pub fn for_community(self, community: Option<&Community>, hues: &HashMap<String, f32>) -> Self { | 112 | + pub fn for_community(self, community: Option<&Community>, hues: &HashMap<Id, f32>) -> Self { |
| 113 | let Some(community) = community else { | 113 | let Some(community) = community else { |
| 114 | return self; | 114 | return self; |
| 115 | }; | 115 | }; |
| @@ -120,7 +120,7 @@ impl Palette { | |||
| 120 | let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) { | 120 | let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) { |
| 121 | Some(&hue) if self.dark => hsla(hue, 0.75, 0.55, 1.), | 121 | Some(&hue) if self.dark => hsla(hue, 0.75, 0.55, 1.), |
| 122 | Some(&hue) => hsla(hue, 0.75, 0.4, 1.), | 122 | Some(&hue) => hsla(hue, 0.75, 0.4, 1.), |
| 123 | - None => self.tinted(id), | 123 | + None => self.tinted(*id), |
| 124 | }; | 124 | }; |
| 125 | Palette { accent, ..self } | 125 | Palette { accent, ..self } |
| 126 | } | 126 | } |
| @@ -216,13 +216,13 @@ pub fn sync_theme(cx: &mut App) { | |||
| 216 | const FIND_KEY: &str = "ctrl-k"; | 216 | const FIND_KEY: &str = "ctrl-k"; |
| 217 | pub const FIND_HINT: &str = "Ctrl K"; | 217 | pub const FIND_HINT: &str = "Ctrl K"; |
| 218 | 218 | ||
| 219 | -pub fn tint(id: &str) -> Hsla { | 219 | +pub fn tint(id: Id) -> Hsla { |
| 220 | let mut hasher = DefaultHasher::new(); | 220 | let mut hasher = DefaultHasher::new(); |
| 221 | id.hash(&mut hasher); | 221 | id.hash(&mut hasher); |
| 222 | rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into() | 222 | rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into() |
| 223 | } | 223 | } |
| 224 | 224 | ||
| 225 | -pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Rems) -> Div { | 225 | +pub fn badge(palette: Palette, id: Id, name: &str, size: Pixels, font: Rems) -> Div { |
| 226 | let initial = name | 226 | let initial = name |
| 227 | .chars() | 227 | .chars() |
| 228 | .next() | 228 | .next() |
| @@ -248,10 +248,10 @@ pub fn avatar( | |||
| 248 | user: &User, | 248 | user: &User, |
| 249 | size: Pixels, | 249 | size: Pixels, |
| 250 | font: Rems, | 250 | font: Rems, |
| 251 | - avatars: &HashMap<String, Arc<Image>>, | 251 | + avatars: &HashMap<Id, Arc<Image>>, |
| 252 | ) -> Div { | 252 | ) -> Div { |
| 253 | let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else { | 253 | let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else { |
| 254 | - return badge(palette, &user.id, &user.username, size, font).rounded_full(); | 254 | + return badge(palette, user.id, &user.username, size, font).rounded_full(); |
| 255 | }; | 255 | }; |
| 256 | 256 | ||
| 257 | div() | 257 | div() |
| @@ -276,7 +276,7 @@ pub fn community_icon( | |||
| 276 | community: &Community, | 276 | community: &Community, |
| 277 | size: Pixels, | 277 | size: Pixels, |
| 278 | font: Rems, | 278 | font: Rems, |
| 279 | - avatars: &HashMap<String, Arc<Image>>, | 279 | + avatars: &HashMap<Id, Arc<Image>>, |
| 280 | ) -> Div { | 280 | ) -> Div { |
| 281 | match &community.kind { | 281 | match &community.kind { |
| 282 | CommunityKind::Group => match community.avatar_id.as_ref().and_then(|id| avatars.get(id)) { | 282 | CommunityKind::Group => match community.avatar_id.as_ref().and_then(|id| avatars.get(id)) { |
| @@ -286,10 +286,10 @@ pub fn community_icon( | |||
| 286 | .rounded(px(4.)) | 286 | .rounded(px(4.)) |
| 287 | .overflow_hidden() | 287 | .overflow_hidden() |
| 288 | .child(img(image.clone()).size_full()), | 288 | .child(img(image.clone()).size_full()), |
| 289 | - None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)), | 289 | + None => badge(palette, community.id, &community.name, size, font).rounded(px(4.)), |
| 290 | }, | 290 | }, |
| 291 | CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars), | 291 | CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars), |
| 292 | - CommunityKind::Notes => badge(palette, &community.id, "Notes", size, font).rounded(px(4.)), | 292 | + CommunityKind::Notes => badge(palette, community.id, "Notes", size, font).rounded(px(4.)), |
| 293 | } | 293 | } |
| 294 | } | 294 | } |
| 295 | 295 | ||
| @@ -315,12 +315,6 @@ pub fn storage(bytes: u64) -> String { | |||
| 315 | } | 315 | } |
| 316 | } | 316 | } |
| 317 | 317 | ||
| 318 | -pub fn id_time(id: &str, format: &str) -> String { | ||
| 319 | - created_at_ms(id) | ||
| 320 | - .map(|millis| millis_time(millis, format)) | ||
| 321 | - .unwrap_or_default() | ||
| 322 | -} | ||
| 323 | - | ||
| 324 | pub fn millis_time(millis: u64, format: &str) -> String { | 318 | pub fn millis_time(millis: u64, format: &str) -> String { |
| 325 | let Ok(timestamp) = Timestamp::from_millisecond(millis as i64) else { | 319 | let Ok(timestamp) = Timestamp::from_millisecond(millis as i64) else { |
| 326 | return String::new(); | 320 | return String::new(); |
| @@ -709,7 +703,7 @@ impl Yumush { | |||
| 709 | ) { | 703 | ) { |
| 710 | self.accounts.sign_in(&user, token); | 704 | self.accounts.sign_in(&user, token); |
| 711 | self.request_user_avatar(&user, cx); | 705 | self.request_user_avatar(&user, cx); |
| 712 | - self.chat.muted = mutes::load(&user.id); | 706 | + self.chat.muted = mutes::load(user.id); |
| 713 | self.user = Some(user); | 707 | self.user = Some(user); |
| 714 | self.change_page(Route::Chat, window, cx); | 708 | self.change_page(Route::Chat, window, cx); |
| 715 | self.load_communities(window, cx); | 709 | self.load_communities(window, cx); |
| @@ -719,11 +713,11 @@ impl Yumush { | |||
| 719 | 713 | ||
| 720 | pub(super) fn switch_account( | 714 | pub(super) fn switch_account( |
| 721 | &mut self, | 715 | &mut self, |
| 722 | - user_id: String, | 716 | + user_id: Id, |
| 723 | window: &mut Window, | 717 | window: &mut Window, |
| 724 | cx: &mut Context<Self>, | 718 | cx: &mut Context<Self>, |
| 725 | ) { | 719 | ) { |
| 726 | - let Some(account) = self.accounts.get(&user_id).cloned() else { | 720 | + let Some(account) = self.accounts.get(user_id).cloned() else { |
| 727 | return; | 721 | return; |
| 728 | }; | 722 | }; |
| 729 | if !self.connection.is_connected() { | 723 | if !self.connection.is_connected() { |
| @@ -741,7 +735,7 @@ impl Yumush { | |||
| 741 | let _ = this.update_in(cx, |yumush, window, cx| match result { | 735 | let _ = this.update_in(cx, |yumush, window, cx| match result { |
| 742 | Ok((user, token)) => yumush.enter_session(user, token, window, cx), | 736 | Ok((user, token)) => yumush.enter_session(user, token, window, cx), |
| 743 | Err(error @ Fail::Server(Error::NotFound | Error::Unauthenticated)) => { | 737 | Err(error @ Fail::Server(Error::NotFound | Error::Unauthenticated)) => { |
| 744 | - yumush.accounts.forget(&account.user_id); | 738 | + yumush.accounts.forget(account.user_id); |
| 745 | window.push_notification(Notification::error(error.to_string()), cx); | 739 | window.push_notification(Notification::error(error.to_string()), cx); |
| 746 | cx.notify(); | 740 | cx.notify(); |
| 747 | } | 741 | } |
| @@ -766,19 +760,19 @@ impl Yumush { | |||
| 766 | .detach(); | 760 | .detach(); |
| 767 | } | 761 | } |
| 768 | 762 | ||
| 769 | - pub(super) fn forget_account(&mut self, user_id: &str, cx: &mut Context<Self>) { | 763 | + pub(super) fn forget_account(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 770 | self.accounts.forget(user_id); | 764 | self.accounts.forget(user_id); |
| 771 | cx.notify(); | 765 | cx.notify(); |
| 772 | } | 766 | } |
| 773 | 767 | ||
| 774 | - pub(super) fn toggle_community_mute(&mut self, community_id: String, cx: &mut Context<Self>) { | 768 | + pub(super) fn toggle_community_mute(&mut self, community_id: Id, cx: &mut Context<Self>) { |
| 775 | - let Some(me) = self.user.as_ref().map(|me| me.id.clone()) else { | 769 | + let Some(me) = self.user.as_ref().map(|me| me.id) else { |
| 776 | return; | 770 | return; |
| 777 | }; | 771 | }; |
| 778 | if !self.chat.muted.remove(&community_id) { | 772 | if !self.chat.muted.remove(&community_id) { |
| 779 | self.chat.muted.insert(community_id); | 773 | self.chat.muted.insert(community_id); |
| 780 | } | 774 | } |
| 781 | - mutes::save(&me, &self.chat.muted); | 775 | + mutes::save(me, &self.chat.muted); |
| 782 | cx.notify(); | 776 | cx.notify(); |
| 783 | } | 777 | } |
| 784 | 778 | ||
| @@ -786,7 +780,7 @@ impl Yumush { | |||
| 786 | let Some(user) = self.user.clone() else { | 780 | let Some(user) = self.user.clone() else { |
| 787 | return; | 781 | return; |
| 788 | }; | 782 | }; |
| 789 | - self.accounts.forget(&user.id); | 783 | + self.accounts.forget(user.id); |
| 790 | self.end_session(window, cx); | 784 | self.end_session(window, cx); |
| 791 | let network = self.network.clone(); | 785 | let network = self.network.clone(); |
| 792 | 786 | ||
| @@ -871,45 +865,40 @@ impl Yumush { | |||
| 871 | let icon = community_icon(palette, community, size, font, &self.chat.avatars); | 865 | let icon = community_icon(palette, community, size, font, &self.chat.avatars); |
| 872 | match &community.kind { | 866 | match &community.kind { |
| 873 | CommunityKind::Direct { peer } => { | 867 | CommunityKind::Direct { peer } => { |
| 874 | - presence_avatar(icon, self.presence_of(&peer.id), size, palette) | 868 | + presence_avatar(icon, self.presence_of(peer.id), size, palette) |
| 875 | } | 869 | } |
| 876 | CommunityKind::Group | CommunityKind::Notes => icon, | 870 | CommunityKind::Group | CommunityKind::Notes => icon, |
| 877 | } | 871 | } |
| 878 | } | 872 | } |
| 879 | 873 | ||
| 880 | - pub fn presence_of(&self, user_id: &str) -> Presence { | 874 | + pub fn presence_of(&self, user_id: Id) -> Presence { |
| 881 | if self.is_me(user_id) && !self.connection.is_connected() { | 875 | if self.is_me(user_id) && !self.connection.is_connected() { |
| 882 | return Presence::Offline; | 876 | return Presence::Offline; |
| 883 | } | 877 | } |
| 884 | self.chat | 878 | self.chat |
| 885 | .presences | 879 | .presences |
| 886 | - .get(user_id) | 880 | + .get(&user_id) |
| 887 | .copied() | 881 | .copied() |
| 888 | .unwrap_or(Presence::Offline) | 882 | .unwrap_or(Presence::Offline) |
| 889 | } | 883 | } |
| 890 | 884 | ||
| 891 | - pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context<Self>) { | 885 | + pub fn request_avatar(&mut self, avatar_id: Id, cx: &mut Context<Self>) { |
| 892 | - if self.chat.avatars.contains_key(avatar_id) | 886 | + if self.chat.avatars.contains_key(&avatar_id) |
| 893 | - || self.chat.avatar_requests.contains(avatar_id) | 887 | + || self.chat.avatar_requests.contains(&avatar_id) |
| 894 | { | 888 | { |
| 895 | return; | 889 | return; |
| 896 | } | 890 | } |
| 897 | - self.chat.avatar_requests.insert(avatar_id.to_string()); | 891 | + self.chat.avatar_requests.insert(avatar_id); |
| 898 | 892 | ||
| 899 | let network = self.network.clone(); | 893 | let network = self.network.clone(); |
| 900 | - let avatar_id = avatar_id.to_string(); | ||
| 901 | 894 | ||
| 902 | cx.spawn(async move |this, cx| { | 895 | cx.spawn(async move |this, cx| { |
| 903 | - let result = network | 896 | + let result = network.call(GetAvatar { avatar_id }).await; |
| 904 | - .call(GetAvatar { | ||
| 905 | - avatar_id: avatar_id.clone(), | ||
| 906 | - }) | ||
| 907 | - .await; | ||
| 908 | let _ = this.update(cx, |yumush, cx| { | 897 | let _ = this.update(cx, |yumush, cx| { |
| 909 | yumush.chat.avatar_requests.remove(&avatar_id); | 898 | yumush.chat.avatar_requests.remove(&avatar_id); |
| 910 | if let Ok(bytes) = result { | 899 | if let Ok(bytes) = result { |
| 911 | if let Some(hue) = crate::avatar::dominant_hue(&bytes) { | 900 | if let Some(hue) = crate::avatar::dominant_hue(&bytes) { |
| 912 | - yumush.chat.hues.insert(avatar_id.clone(), hue); | 901 | + yumush.chat.hues.insert(avatar_id, hue); |
| 913 | } | 902 | } |
| 914 | yumush.chat.avatars.insert( | 903 | yumush.chat.avatars.insert( |
| 915 | avatar_id, | 904 | avatar_id, |
| @@ -923,7 +912,7 @@ impl Yumush { | |||
| 923 | } | 912 | } |
| 924 | 913 | ||
| 925 | pub fn request_user_avatar(&mut self, user: &User, cx: &mut Context<Self>) { | 914 | pub fn request_user_avatar(&mut self, user: &User, cx: &mut Context<Self>) { |
| 926 | - if let Some(avatar_id) = &user.avatar_id { | 915 | + if let Some(avatar_id) = user.avatar_id { |
| 927 | self.request_avatar(avatar_id, cx); | 916 | self.request_avatar(avatar_id, cx); |
| 928 | } | 917 | } |
| 929 | } | 918 | } |
| @@ -932,7 +921,7 @@ impl Yumush { | |||
| 932 | match &event { | 921 | match &event { |
| 933 | Event::MemberJoined { member, .. } => self.request_user_avatar(&member.user, cx), | 922 | Event::MemberJoined { member, .. } => self.request_user_avatar(&member.user, cx), |
| 934 | Event::UserUpdated(user) => { | 923 | Event::UserUpdated(user) => { |
| 935 | - if self.is_me(&user.id) { | 924 | + if self.is_me(user.id) { |
| 936 | self.user = Some(user.clone()); | 925 | self.user = Some(user.clone()); |
| 937 | self.accounts.rename(user); | 926 | self.accounts.rename(user); |
| 938 | if !self.is_builder() && self.chat.view == View::Builder { | 927 | if !self.is_builder() && self.chat.view == View::Builder { |
| @@ -944,13 +933,13 @@ impl Yumush { | |||
| 944 | Event::VoiceLeft { | 933 | Event::VoiceLeft { |
| 945 | community_id, | 934 | community_id, |
| 946 | user_id, | 935 | user_id, |
| 947 | - } if self.is_me(user_id) => self.leave_voice_in(community_id, cx), | 936 | + } if self.is_me(*user_id) => self.leave_voice_in(*community_id, cx), |
| 948 | Event::VoiceMuted { | 937 | Event::VoiceMuted { |
| 949 | user_id, | 938 | user_id, |
| 950 | muted: true, | 939 | muted: true, |
| 951 | .. | 940 | .. |
| 952 | - } if self.is_me(user_id) => self.set_muted(true, cx), | 941 | + } if self.is_me(*user_id) => self.set_muted(true, cx), |
| 953 | - Event::ShareStopped { user_id, kind, .. } if self.is_watching(user_id, *kind) => { | 942 | + Event::ShareStopped { user_id, kind, .. } if self.is_watching(*user_id, *kind) => { |
| 954 | self.close_viewer(cx) | 943 | self.close_viewer(cx) |
| 955 | } | 944 | } |
| 956 | Event::Typing { .. } => { | 945 | Event::Typing { .. } => { |
| @@ -963,17 +952,15 @@ impl Yumush { | |||
| 963 | _ => {} | 952 | _ => {} |
| 964 | } | 953 | } |
| 965 | self.chat | 954 | self.chat |
| 966 | - .apply_event(event, self.user.as_ref().map(|user| user.id.as_str())); | 955 | + .apply_event(event, self.user.as_ref().map(|user| user.id)); |
| 967 | self.request_authors(cx); | 956 | self.request_authors(cx); |
| 968 | self.request_social_avatars(cx); | 957 | self.request_social_avatars(cx); |
| 969 | self.request_media(cx); | 958 | self.request_media(cx); |
| 970 | } | 959 | } |
| 971 | 960 | ||
| 972 | - fn mark_read(&mut self, community_id: &str, message_id: &str, cx: &mut Context<Self>) { | 961 | + fn mark_read(&mut self, community_id: Id, message_id: Id, cx: &mut Context<Self>) { |
| 973 | self.chat.mark_read(community_id, message_id); | 962 | self.chat.mark_read(community_id, message_id); |
| 974 | let network = self.network.clone(); | 963 | let network = self.network.clone(); |
| 975 | - let community_id = community_id.to_string(); | ||
| 976 | - let message_id = message_id.to_string(); | ||
| 977 | 964 | ||
| 978 | cx.spawn(async move |_, _| { | 965 | cx.spawn(async move |_, _| { |
| 979 | let _ = network | 966 | let _ = network |
| @@ -987,10 +974,10 @@ impl Yumush { | |||
| 987 | } | 974 | } |
| 988 | 975 | ||
| 989 | fn read_selected(&mut self, cx: &mut Context<Self>) { | 976 | fn read_selected(&mut self, cx: &mut Context<Self>) { |
| 990 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 977 | + let Some(community_id) = self.chat.selected_community_id else { |
| 991 | return; | 978 | return; |
| 992 | }; | 979 | }; |
| 993 | - let Some(message_id) = self.chat.messages.last().map(|message| message.id.clone()) else { | 980 | + let Some(message_id) = self.chat.messages.last().map(|message| message.id) else { |
| 994 | return; | 981 | return; |
| 995 | }; | 982 | }; |
| 996 | if self | 983 | if self |
| @@ -999,7 +986,7 @@ impl Yumush { | |||
| 999 | .get(&community_id) | 986 | .get(&community_id) |
| 1000 | .is_some_and(|unread| unread.messages > 0) | 987 | .is_some_and(|unread| unread.messages > 0) |
| 1001 | { | 988 | { |
| 1002 | - self.mark_read(&community_id, &message_id, cx); | 989 | + self.mark_read(community_id, message_id, cx); |
| 1003 | } | 990 | } |
| 1004 | } | 991 | } |
| 1005 | 992 | ||
| @@ -1010,16 +997,16 @@ impl Yumush { | |||
| 1010 | if message.user_id == me.id { | 997 | if message.user_id == me.id { |
| 1011 | return; | 998 | return; |
| 1012 | } | 999 | } |
| 1013 | - if active && self.chat.is_selected(&message.community_id) { | 1000 | + if active && self.chat.is_selected(message.community_id) { |
| 1014 | - self.mark_read(&message.community_id, &message.id, cx); | 1001 | + self.mark_read(message.community_id, message.id, cx); |
| 1015 | return; | 1002 | return; |
| 1016 | } | 1003 | } |
| 1017 | let unread = self | 1004 | let unread = self |
| 1018 | .chat | 1005 | .chat |
| 1019 | .unread | 1006 | .unread |
| 1020 | - .entry(message.community_id.clone()) | 1007 | + .entry(message.community_id) |
| 1021 | .or_insert_with(|| Unread { | 1008 | .or_insert_with(|| Unread { |
| 1022 | - community_id: message.community_id.clone(), | 1009 | + community_id: message.community_id, |
| 1023 | ..Default::default() | 1010 | ..Default::default() |
| 1024 | }); | 1011 | }); |
| 1025 | unread.messages += 1; | 1012 | unread.messages += 1; |
| @@ -1032,22 +1019,22 @@ impl Yumush { | |||
| 1032 | let Some(me) = self.user.as_ref() else { | 1019 | let Some(me) = self.user.as_ref() else { |
| 1033 | return false; | 1020 | return false; |
| 1034 | }; | 1021 | }; |
| 1035 | - let viewing = active && self.chat.is_selected(&message.community_id); | 1022 | + let viewing = active && self.chat.is_selected(message.community_id); |
| 1036 | 1023 | ||
| 1037 | message.user_id != me.id | 1024 | message.user_id != me.id |
| 1038 | && message.call.is_none() | 1025 | && message.call.is_none() |
| 1039 | && !self.chat.muted.contains(&message.community_id) | 1026 | && !self.chat.muted.contains(&message.community_id) |
| 1040 | - && self.presence_of(&me.id) == Presence::Online | 1027 | + && self.presence_of(me.id) == Presence::Online |
| 1041 | && !viewing | 1028 | && !viewing |
| 1042 | } | 1029 | } |
| 1043 | 1030 | ||
| 1044 | - fn starts_call(&self, community_id: &str, user_id: &str) -> bool { | 1031 | + fn starts_call(&self, community_id: Id, user_id: Id) -> bool { |
| 1045 | !self.is_me(user_id) | 1032 | !self.is_me(user_id) |
| 1046 | && self.chat.voice_ids(community_id).is_empty() | 1033 | && self.chat.voice_ids(community_id).is_empty() |
| 1047 | && self.is_direct(community_id) | 1034 | && self.is_direct(community_id) |
| 1048 | } | 1035 | } |
| 1049 | 1036 | ||
| 1050 | - fn ends_call(&self, community_id: &str, user_id: &str) -> bool { | 1037 | + fn ends_call(&self, community_id: Id, user_id: Id) -> bool { |
| 1051 | !self.is_me(user_id) | 1038 | !self.is_me(user_id) |
| 1052 | && self.chat.in_voice(community_id) | 1039 | && self.chat.in_voice(community_id) |
| 1053 | && self.is_direct(community_id) | 1040 | && self.is_direct(community_id) |
| @@ -1055,17 +1042,17 @@ impl Yumush { | |||
| 1055 | .chat | 1042 | .chat |
| 1056 | .voice_ids(community_id) | 1043 | .voice_ids(community_id) |
| 1057 | .iter() | 1044 | .iter() |
| 1058 | - .all(|id| id == user_id || self.is_me(id)) | 1045 | + .all(|id| *id == user_id || self.is_me(*id)) |
| 1059 | } | 1046 | } |
| 1060 | 1047 | ||
| 1061 | - pub(super) fn is_direct(&self, community_id: &str) -> bool { | 1048 | + pub(super) fn is_direct(&self, community_id: Id) -> bool { |
| 1062 | self.chat | 1049 | self.chat |
| 1063 | .communities() | 1050 | .communities() |
| 1064 | .iter() | 1051 | .iter() |
| 1065 | .any(|community| community.id == community_id && community.kind.is_direct()) | 1052 | .any(|community| community.id == community_id && community.kind.is_direct()) |
| 1066 | } | 1053 | } |
| 1067 | 1054 | ||
| 1068 | - fn is_me(&self, user_id: &str) -> bool { | 1055 | + fn is_me(&self, user_id: Id) -> bool { |
| 1069 | self.user.as_ref().is_some_and(|me| me.id == user_id) | 1056 | self.user.as_ref().is_some_and(|me| me.id == user_id) |
| 1070 | } | 1057 | } |
| 1071 | 1058 | ||
| @@ -1148,7 +1135,7 @@ impl Yumush { | |||
| 1148 | self.load_server_settings(window, cx); | 1135 | self.load_server_settings(window, cx); |
| 1149 | if self.user.is_some() { | 1136 | if self.user.is_some() { |
| 1150 | self.reload(window, cx); | 1137 | self.reload(window, cx); |
| 1151 | - } else if let Some(active) = self.accounts.active.clone() { | 1138 | + } else if let Some(active) = self.accounts.active { |
| 1152 | self.switch_account(active, window, cx); | 1139 | self.switch_account(active, window, cx); |
| 1153 | } | 1140 | } |
| 1154 | } | 1141 | } |
| @@ -1157,7 +1144,7 @@ impl Yumush { | |||
| 1157 | NetworkEvent::VoiceEnded => self.chat.set_voice_off(), | 1144 | NetworkEvent::VoiceEnded => self.chat.set_voice_off(), |
| 1158 | NetworkEvent::SessionLost => { | 1145 | NetworkEvent::SessionLost => { |
| 1159 | if let Some(user) = &self.user { | 1146 | if let Some(user) = &self.user { |
| 1160 | - self.accounts.forget(&user.id); | 1147 | + self.accounts.forget(user.id); |
| 1161 | } | 1148 | } |
| 1162 | self.end_session(window, cx); | 1149 | self.end_session(window, cx); |
| 1163 | } | 1150 | } |
| @@ -1165,9 +1152,9 @@ impl Yumush { | |||
| 1165 | Event::MemberLeft { | 1152 | Event::MemberLeft { |
| 1166 | community_id, | 1153 | community_id, |
| 1167 | user_id, | 1154 | user_id, |
| 1168 | - } if self.is_me(&user_id) => { | 1155 | + } if self.is_me(user_id) => { |
| 1169 | - self.leave_voice_in(&community_id, cx); | 1156 | + self.leave_voice_in(community_id, cx); |
| 1170 | - self.chat.remove_community(&community_id); | 1157 | + self.chat.remove_community(community_id); |
| 1171 | } | 1158 | } |
| 1172 | Event::Removed { | 1159 | Event::Removed { |
| 1173 | community_id, | 1160 | community_id, |
| @@ -1175,8 +1162,8 @@ impl Yumush { | |||
| 1175 | sanction, | 1162 | sanction, |
| 1176 | reason, | 1163 | reason, |
| 1177 | } => { | 1164 | } => { |
| 1178 | - self.leave_voice_in(&community_id, cx); | 1165 | + self.leave_voice_in(community_id, cx); |
| 1179 | - self.chat.remove_community(&community_id); | 1166 | + self.chat.remove_community(community_id); |
| 1180 | let action = match sanction { | 1167 | let action = match sanction { |
| 1181 | Sanction::Ban => "Banned from", | 1168 | Sanction::Ban => "Banned from", |
| 1182 | Sanction::Kick => "Kicked from", | 1169 | Sanction::Kick => "Kicked from", |
| @@ -1188,7 +1175,7 @@ impl Yumush { | |||
| 1188 | window.push_notification(Notification::warning(text), cx); | 1175 | window.push_notification(Notification::warning(text), cx); |
| 1189 | } | 1176 | } |
| 1190 | Event::CommunityDeleted { community_id } => { | 1177 | Event::CommunityDeleted { community_id } => { |
| 1191 | - self.leave_voice_in(&community_id, cx); | 1178 | + self.leave_voice_in(community_id, cx); |
| 1192 | self.apply_pushed(Event::CommunityDeleted { community_id }, cx); | 1179 | self.apply_pushed(Event::CommunityDeleted { community_id }, cx); |
| 1193 | } | 1180 | } |
| 1194 | Event::ReportCreated => self.report_created(window, cx), | 1181 | Event::ReportCreated => self.report_created(window, cx), |
| @@ -1220,7 +1207,7 @@ impl Yumush { | |||
| 1220 | } | 1207 | } |
| 1221 | self.count_message(message, active, cx); | 1208 | self.count_message(message, active, cx); |
| 1222 | if message.call == Some(CallLog::Declined) | 1209 | if message.call == Some(CallLog::Declined) |
| 1223 | - && self.chat.in_voice(&message.community_id) | 1210 | + && self.chat.in_voice(message.community_id) |
| 1224 | { | 1211 | { |
| 1225 | self.end_voice(cx); | 1212 | self.end_voice(cx); |
| 1226 | } | 1213 | } |
| @@ -1228,13 +1215,13 @@ impl Yumush { | |||
| 1228 | Event::VoiceJoined { | 1215 | Event::VoiceJoined { |
| 1229 | community_id, | 1216 | community_id, |
| 1230 | user_id, | 1217 | user_id, |
| 1231 | - } if self.starts_call(community_id, user_id) => { | 1218 | + } if self.starts_call(*community_id, *user_id) => { |
| 1232 | - self.chat.ringing.insert(community_id.clone()); | 1219 | + self.chat.ringing.insert(*community_id); |
| 1233 | } | 1220 | } |
| 1234 | Event::VoiceLeft { | 1221 | Event::VoiceLeft { |
| 1235 | community_id, | 1222 | community_id, |
| 1236 | user_id, | 1223 | user_id, |
| 1237 | - } if self.ends_call(community_id, user_id) => { | 1224 | + } if self.ends_call(*community_id, *user_id) => { |
| 1238 | self.end_voice(cx); | 1225 | self.end_voice(cx); |
| 1239 | } | 1226 | } |
| 1240 | _ => {} | 1227 | _ => {} |
crates/client/src/gui/auth.rsmodified+5 -5
| @@ -174,8 +174,8 @@ impl Yumush { | |||
| 174 | .map(|account| { | 174 | .map(|account| { |
| 175 | let switch_entity = entity.clone(); | 175 | let switch_entity = entity.clone(); |
| 176 | let forget_entity = entity.clone(); | 176 | let forget_entity = entity.clone(); |
| 177 | - let switch_id = account.user_id.clone(); | 177 | + let switch_id = account.user_id; |
| 178 | - let forget_id = account.user_id.clone(); | 178 | + let forget_id = account.user_id; |
| 179 | 179 | ||
| 180 | hoverable( | 180 | hoverable( |
| 181 | format!("saved_{}", account.user_id), | 181 | format!("saved_{}", account.user_id), |
| @@ -189,7 +189,7 @@ impl Yumush { | |||
| 189 | .child( | 189 | .child( |
| 190 | badge( | 190 | badge( |
| 191 | palette, | 191 | palette, |
| 192 | - &account.user_id, | 192 | + account.user_id, |
| 193 | &account.username, | 193 | &account.username, |
| 194 | px(22.), | 194 | px(22.), |
| 195 | text(11.), | 195 | text(11.), |
| @@ -204,7 +204,7 @@ impl Yumush { | |||
| 204 | move |_, cx| { | 204 | move |_, cx| { |
| 205 | cx.stop_propagation(); | 205 | cx.stop_propagation(); |
| 206 | forget_entity.update(cx, |yumush, cx| { | 206 | forget_entity.update(cx, |yumush, cx| { |
| 207 | - yumush.forget_account(&forget_id, cx) | 207 | + yumush.forget_account(forget_id, cx) |
| 208 | }); | 208 | }); |
| 209 | }, | 209 | }, |
| 210 | ) | 210 | ) |
| @@ -221,7 +221,7 @@ impl Yumush { | |||
| 221 | ) | 221 | ) |
| 222 | .on_click(move |_, window, cx| { | 222 | .on_click(move |_, window, cx| { |
| 223 | switch_entity.update(cx, |yumush, cx| { | 223 | switch_entity.update(cx, |yumush, cx| { |
| 224 | - yumush.switch_account(switch_id.clone(), window, cx) | 224 | + yumush.switch_account(switch_id, window, cx) |
| 225 | }) | 225 | }) |
| 226 | }) | 226 | }) |
| 227 | .into_any_element() | 227 | .into_any_element() |
crates/client/src/gui/builder.rsmodified+9 -12
| @@ -11,6 +11,7 @@ mod ui; | |||
| 11 | mod users; | 11 | mod users; |
| 12 | mod voice; | 12 | mod voice; |
| 13 | 13 | ||
| 14 | +use common::model::Id; | ||
| 14 | use std::{fmt::Display, future::Future, path::PathBuf}; | 15 | use std::{fmt::Display, future::Future, path::PathBuf}; |
| 15 | 16 | ||
| 16 | use common::{ | 17 | use common::{ |
| @@ -99,9 +100,9 @@ impl BuilderTab { | |||
| 99 | } | 100 | } |
| 100 | 101 | ||
| 101 | pub(super) struct Transfer { | 102 | pub(super) struct Transfer { |
| 102 | - pub(super) community_id: String, | 103 | + pub(super) community_id: Id, |
| 103 | pub(super) members: Vec<Member>, | 104 | pub(super) members: Vec<Member>, |
| 104 | - pub(super) pending: Option<String>, | 105 | + pub(super) pending: Option<Id>, |
| 105 | } | 106 | } |
| 106 | 107 | ||
| 107 | impl Yumush { | 108 | impl Yumush { |
| @@ -405,15 +406,15 @@ impl Yumush { | |||
| 405 | } | 406 | } |
| 406 | } | 407 | } |
| 407 | 408 | ||
| 408 | - fn resolve_user(&self, username: &str) -> Option<String> { | 409 | + fn resolve_user(&self, username: &str) -> Option<Id> { |
| 409 | self.chat | 410 | self.chat |
| 410 | .builder_users | 411 | .builder_users |
| 411 | .iter() | 412 | .iter() |
| 412 | .find(|account| account.user.username.to_lowercase() == username) | 413 | .find(|account| account.user.username.to_lowercase() == username) |
| 413 | - .map(|account| account.user.id.clone()) | 414 | + .map(|account| account.user.id) |
| 414 | } | 415 | } |
| 415 | 416 | ||
| 416 | - fn resolve_community(&self, name: &str) -> Option<String> { | 417 | + fn resolve_community(&self, name: &str) -> Option<Id> { |
| 417 | self.chat | 418 | self.chat |
| 418 | .builder_communities | 419 | .builder_communities |
| 419 | .iter() | 420 | .iter() |
| @@ -421,14 +422,10 @@ impl Yumush { | |||
| 421 | summary.community.kind == CommunityKind::Group | 422 | summary.community.kind == CommunityKind::Group |
| 422 | && summary.community.name.to_lowercase() == name | 423 | && summary.community.name.to_lowercase() == name |
| 423 | }) | 424 | }) |
| 424 | - .map(|summary| summary.community.id.clone()) | 425 | + .map(|summary| summary.community.id) |
| 425 | } | 426 | } |
| 426 | 427 | ||
| 427 | - pub(super) fn filter_user( | 428 | + pub(super) fn filter_user(&self, input: &Entity<InputState>, cx: &App) -> Option<Option<Id>> { |
| 428 | - &self, | ||
| 429 | - input: &Entity<InputState>, | ||
| 430 | - cx: &App, | ||
| 431 | - ) -> Option<Option<String>> { | ||
| 432 | let name = search_text(input, cx); | 429 | let name = search_text(input, cx); |
| 433 | if name.is_empty() { | 430 | if name.is_empty() { |
| 434 | return Some(None); | 431 | return Some(None); |
| @@ -440,7 +437,7 @@ impl Yumush { | |||
| 440 | &self, | 437 | &self, |
| 441 | input: &Entity<InputState>, | 438 | input: &Entity<InputState>, |
| 442 | cx: &App, | 439 | cx: &App, |
| 443 | - ) -> Option<Option<String>> { | 440 | + ) -> Option<Option<Id>> { |
| 444 | let name = search_text(input, cx); | 441 | let name = search_text(input, cx); |
| 445 | if name.is_empty() { | 442 | if name.is_empty() { |
| 446 | return Some(None); | 443 | return Some(None); |
crates/client/src/gui/builder/access.rsmodified+5 -5
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use common::{ | 2 | use common::{ |
| 2 | call::{CreateInviteCode, DeleteInviteCode, ListInviteCodes, ListServerBans, RemoveServerBan}, | 3 | call::{CreateInviteCode, DeleteInviteCode, ListInviteCodes, ListServerBans, RemoveServerBan}, |
| 3 | model::{InviteCode, ServerBan, ServerBanKind}, | 4 | model::{InviteCode, ServerBan, ServerBanKind}, |
| @@ -102,7 +103,7 @@ fn invite_row( | |||
| 102 | } | 103 | } |
| 103 | 104 | ||
| 104 | fn ban_row(ban: &ServerBan, entity: &Entity<Yumush>, palette: Palette) -> Div { | 105 | fn ban_row(ban: &ServerBan, entity: &Entity<Yumush>, palette: Palette) -> Div { |
| 105 | - let remove_id = ban.id.clone(); | 106 | + let remove_id = ban.id; |
| 106 | let kind = match ban.kind { | 107 | let kind = match ban.kind { |
| 107 | ServerBanKind::Ip => "IP", | 108 | ServerBanKind::Ip => "IP", |
| 108 | ServerBanKind::Username => "Username", | 109 | ServerBanKind::Username => "Username", |
| @@ -143,7 +144,7 @@ fn ban_row(ban: &ServerBan, entity: &Entity<Yumush>, palette: Palette) -> Div { | |||
| 143 | palette.muted, | 144 | palette.muted, |
| 144 | palette, | 145 | palette, |
| 145 | entity_action(entity, move |yumush, window, cx| { | 146 | entity_action(entity, move |yumush, window, cx| { |
| 146 | - yumush.remove_ban(&remove_id, window, cx) | 147 | + yumush.remove_ban(remove_id, window, cx) |
| 147 | }), | 148 | }), |
| 148 | )) | 149 | )) |
| 149 | } | 150 | } |
| @@ -211,7 +212,7 @@ impl Yumush { | |||
| 211 | window: &mut Window, | 212 | window: &mut Window, |
| 212 | cx: &mut Context<Self>, | 213 | cx: &mut Context<Self>, |
| 213 | ) { | 214 | ) { |
| 214 | - if !confirmed(&mut self.chat.pending_invite_delete, code) { | 215 | + if !confirmed(&mut self.chat.pending_invite_delete, code.to_string()) { |
| 215 | cx.notify(); | 216 | cx.notify(); |
| 216 | return; | 217 | return; |
| 217 | } | 218 | } |
| @@ -234,9 +235,8 @@ impl Yumush { | |||
| 234 | cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); | 235 | cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); |
| 235 | } | 236 | } |
| 236 | 237 | ||
| 237 | - pub(super) fn remove_ban(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) { | 238 | + pub(super) fn remove_ban(&mut self, id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 238 | let network = self.network.clone(); | 239 | let network = self.network.clone(); |
| 239 | - let id = id.to_string(); | ||
| 240 | 240 | ||
| 241 | cx.spawn_in(window, async move |this, cx| { | 241 | cx.spawn_in(window, async move |this, cx| { |
| 242 | match network.call(RemoveServerBan { id }).await { | 242 | match network.call(RemoveServerBan { id }).await { |
crates/client/src/gui/builder/backups.rsmodified+1 -1
| @@ -145,7 +145,7 @@ impl Yumush { | |||
| 145 | } | 145 | } |
| 146 | 146 | ||
| 147 | fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) { | 147 | fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 148 | - if !confirmed(&mut self.pending_backup_delete, name) { | 148 | + if !confirmed(&mut self.pending_backup_delete, name.to_string()) { |
| 149 | cx.notify(); | 149 | cx.notify(); |
| 150 | return; | 150 | return; |
| 151 | } | 151 | } |
crates/client/src/gui/builder/communities.rsmodified+31 -48
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use common::{ | 2 | use common::{ |
| 2 | call::{ | 3 | call::{ |
| 3 | DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, SetCommunityVoice, | 4 | DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, SetCommunityVoice, |
| @@ -22,13 +23,12 @@ use crate::gui::{ | |||
| 22 | impl Yumush { | 23 | impl Yumush { |
| 23 | pub(super) fn set_builder_community_voice( | 24 | pub(super) fn set_builder_community_voice( |
| 24 | &mut self, | 25 | &mut self, |
| 25 | - community_id: &str, | 26 | + community_id: Id, |
| 26 | enabled: bool, | 27 | enabled: bool, |
| 27 | window: &mut Window, | 28 | window: &mut Window, |
| 28 | cx: &mut Context<Self>, | 29 | cx: &mut Context<Self>, |
| 29 | ) { | 30 | ) { |
| 30 | let network = self.network.clone(); | 31 | let network = self.network.clone(); |
| 31 | - let community_id = community_id.to_string(); | ||
| 32 | 32 | ||
| 33 | cx.spawn_in(window, async move |this, cx| { | 33 | cx.spawn_in(window, async move |this, cx| { |
| 34 | match network | 34 | match network |
| @@ -56,7 +56,7 @@ impl Yumush { | |||
| 56 | |network| async move { network.call(ListAllCommunities).await }, | 56 | |network| async move { network.call(ListAllCommunities).await }, |
| 57 | |yumush, summaries, cx| { | 57 | |yumush, summaries, cx| { |
| 58 | for summary in &summaries { | 58 | for summary in &summaries { |
| 59 | - if let Some(avatar_id) = &summary.community.avatar_id { | 59 | + if let Some(avatar_id) = summary.community.avatar_id { |
| 60 | yumush.request_avatar(avatar_id, cx); | 60 | yumush.request_avatar(avatar_id, cx); |
| 61 | } | 61 | } |
| 62 | if let Some(owner) = &summary.owner { | 62 | if let Some(owner) = &summary.owner { |
| @@ -71,7 +71,7 @@ impl Yumush { | |||
| 71 | 71 | ||
| 72 | pub(super) fn delete_builder_community( | 72 | pub(super) fn delete_builder_community( |
| 73 | &mut self, | 73 | &mut self, |
| 74 | - community_id: &str, | 74 | + community_id: Id, |
| 75 | window: &mut Window, | 75 | window: &mut Window, |
| 76 | cx: &mut Context<Self>, | 76 | cx: &mut Context<Self>, |
| 77 | ) { | 77 | ) { |
| @@ -80,18 +80,12 @@ impl Yumush { | |||
| 80 | return; | 80 | return; |
| 81 | } | 81 | } |
| 82 | let network = self.network.clone(); | 82 | let network = self.network.clone(); |
| 83 | - let community_id = community_id.to_string(); | ||
| 84 | 83 | ||
| 85 | cx.spawn_in(window, async move |this, cx| { | 84 | cx.spawn_in(window, async move |this, cx| { |
| 86 | - match network | 85 | + match network.call(DeleteCommunity { community_id }).await { |
| 87 | - .call(DeleteCommunity { | ||
| 88 | - community_id: community_id.clone(), | ||
| 89 | - }) | ||
| 90 | - .await | ||
| 91 | - { | ||
| 92 | Ok(()) => { | 86 | Ok(()) => { |
| 93 | let _ = this.update_in(cx, |yumush, window, cx| { | 87 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 94 | - yumush.chat.remove_community(&community_id); | 88 | + yumush.chat.remove_community(community_id); |
| 95 | yumush.load_builder_communities(window, cx); | 89 | yumush.load_builder_communities(window, cx); |
| 96 | }); | 90 | }); |
| 97 | } | 91 | } |
| @@ -103,7 +97,7 @@ impl Yumush { | |||
| 103 | 97 | ||
| 104 | pub(super) fn open_transfer( | 98 | pub(super) fn open_transfer( |
| 105 | &mut self, | 99 | &mut self, |
| 106 | - community_id: String, | 100 | + community_id: Id, |
| 107 | window: &mut Window, | 101 | window: &mut Window, |
| 108 | cx: &mut Context<Self>, | 102 | cx: &mut Context<Self>, |
| 109 | ) { | 103 | ) { |
| @@ -118,7 +112,7 @@ impl Yumush { | |||
| 118 | return; | 112 | return; |
| 119 | } | 113 | } |
| 120 | self.chat.transfer = Some(Transfer { | 114 | self.chat.transfer = Some(Transfer { |
| 121 | - community_id: community_id.clone(), | 115 | + community_id, |
| 122 | members: Vec::new(), | 116 | members: Vec::new(), |
| 123 | pending: None, | 117 | pending: None, |
| 124 | }); | 118 | }); |
| @@ -128,19 +122,14 @@ impl Yumush { | |||
| 128 | 122 | ||
| 129 | pub(super) fn load_transfer_members( | 123 | pub(super) fn load_transfer_members( |
| 130 | &self, | 124 | &self, |
| 131 | - community_id: String, | 125 | + community_id: Id, |
| 132 | window: &mut Window, | 126 | window: &mut Window, |
| 133 | cx: &mut Context<Self>, | 127 | cx: &mut Context<Self>, |
| 134 | ) { | 128 | ) { |
| 135 | let network = self.network.clone(); | 129 | let network = self.network.clone(); |
| 136 | 130 | ||
| 137 | cx.spawn_in(window, async move |this, cx| { | 131 | cx.spawn_in(window, async move |this, cx| { |
| 138 | - let members = match network | 132 | + let members = match network.call(ListMembers { community_id }).await { |
| 139 | - .call(ListMembers { | ||
| 140 | - community_id: community_id.clone(), | ||
| 141 | - }) | ||
| 142 | - .await | ||
| 143 | - { | ||
| 144 | Ok(members) => members, | 133 | Ok(members) => members, |
| 145 | Err(error) => { | 134 | Err(error) => { |
| 146 | notify_error(&this, cx, error); | 135 | notify_error(&this, cx, error); |
| @@ -175,19 +164,14 @@ impl Yumush { | |||
| 175 | .iter() | 164 | .iter() |
| 176 | .filter(|member| member.rank != Rank::Owner) | 165 | .filter(|member| member.rank != Rank::Owner) |
| 177 | .map(|member| { | 166 | .map(|member| { |
| 178 | - let pending = transfer.pending.as_deref() == Some(member.user.id.as_str()); | 167 | + let pending = transfer.pending == Some(member.user.id); |
| 179 | self.transfer_row(member, pending, entity, palette) | 168 | self.transfer_row(member, pending, entity, palette) |
| 180 | .into_any_element() | 169 | .into_any_element() |
| 181 | }) | 170 | }) |
| 182 | .collect() | 171 | .collect() |
| 183 | } | 172 | } |
| 184 | 173 | ||
| 185 | - pub(super) fn transfer_to( | 174 | + pub(super) fn transfer_to(&mut self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 186 | - &mut self, | ||
| 187 | - user_id: &str, | ||
| 188 | - window: &mut Window, | ||
| 189 | - cx: &mut Context<Self>, | ||
| 190 | - ) { | ||
| 191 | let Some(transfer) = self.chat.transfer.as_mut() else { | 175 | let Some(transfer) = self.chat.transfer.as_mut() else { |
| 192 | return; | 176 | return; |
| 193 | }; | 177 | }; |
| @@ -196,9 +180,8 @@ impl Yumush { | |||
| 196 | cx.notify(); | 180 | cx.notify(); |
| 197 | return; | 181 | return; |
| 198 | } | 182 | } |
| 199 | - let community_id = transfer.community_id.clone(); | 183 | + let community_id = transfer.community_id; |
| 200 | let network = self.network.clone(); | 184 | let network = self.network.clone(); |
| 201 | - let user_id = user_id.to_string(); | ||
| 202 | 185 | ||
| 203 | cx.spawn_in(window, async move |this, cx| { | 186 | cx.spawn_in(window, async move |this, cx| { |
| 204 | match network | 187 | match network |
| @@ -222,7 +205,7 @@ impl Yumush { | |||
| 222 | 205 | ||
| 223 | pub(super) fn jump_to( | 206 | pub(super) fn jump_to( |
| 224 | &mut self, | 207 | &mut self, |
| 225 | - community_id: String, | 208 | + community_id: Id, |
| 226 | voice: bool, | 209 | voice: bool, |
| 227 | window: &mut Window, | 210 | window: &mut Window, |
| 228 | cx: &mut Context<Self>, | 211 | cx: &mut Context<Self>, |
| @@ -259,14 +242,14 @@ impl Yumush { | |||
| 259 | window: &mut Window, | 242 | window: &mut Window, |
| 260 | cx: &mut Context<Self>, | 243 | cx: &mut Context<Self>, |
| 261 | ) { | 244 | ) { |
| 262 | - let community_id = community.id.clone(); | 245 | + let community_id = community.id; |
| 263 | - if self.chat.joined(&community_id) { | 246 | + if self.chat.joined(community_id) { |
| 264 | let direct = community.kind.is_direct(); | 247 | let direct = community.kind.is_direct(); |
| 265 | - self.go_to_community(community_id.clone(), direct, window, cx); | 248 | + self.go_to_community(community_id, direct, window, cx); |
| 266 | } else { | 249 | } else { |
| 267 | self.open_builder_community(community, window, cx); | 250 | self.open_builder_community(community, window, cx); |
| 268 | } | 251 | } |
| 269 | - if voice && !self.chat.in_voice(&community_id) { | 252 | + if voice && !self.chat.in_voice(community_id) { |
| 270 | self.toggle_voice(community_id, window, cx); | 253 | self.toggle_voice(community_id, window, cx); |
| 271 | } | 254 | } |
| 272 | } | 255 | } |
| @@ -277,7 +260,7 @@ impl Yumush { | |||
| 277 | window: &mut Window, | 260 | window: &mut Window, |
| 278 | cx: &mut Context<Self>, | 261 | cx: &mut Context<Self>, |
| 279 | ) { | 262 | ) { |
| 280 | - let community_id = community.id.clone(); | 263 | + let community_id = community.id; |
| 281 | self.chat.opened = Some(community); | 264 | self.chat.opened = Some(community); |
| 282 | self.show_view(View::Chat, window, cx); | 265 | self.show_view(View::Chat, window, cx); |
| 283 | self.select_community(community_id, window, cx); | 266 | self.select_community(community_id, window, cx); |
| @@ -332,7 +315,7 @@ impl Yumush { | |||
| 332 | entity: &Entity<Self>, | 315 | entity: &Entity<Self>, |
| 333 | palette: Palette, | 316 | palette: Palette, |
| 334 | ) -> Div { | 317 | ) -> Div { |
| 335 | - let user_id = member.user.id.clone(); | 318 | + let user_id = member.user.id; |
| 336 | 319 | ||
| 337 | div() | 320 | div() |
| 338 | .h(px(40.)) | 321 | .h(px(40.)) |
| @@ -369,7 +352,7 @@ impl Yumush { | |||
| 369 | if pending { "Confirm" } else { "Transfer" }, | 352 | if pending { "Confirm" } else { "Transfer" }, |
| 370 | palette, | 353 | palette, |
| 371 | entity_action(entity, move |yumush, window, cx| { | 354 | entity_action(entity, move |yumush, window, cx| { |
| 372 | - yumush.transfer_to(&user_id, window, cx) | 355 | + yumush.transfer_to(user_id, window, cx) |
| 373 | }), | 356 | }), |
| 374 | )) | 357 | )) |
| 375 | } | 358 | } |
| @@ -382,13 +365,13 @@ impl Yumush { | |||
| 382 | ) -> Div { | 365 | ) -> Div { |
| 383 | let community = &summary.community; | 366 | let community = &summary.community; |
| 384 | let opened = community.clone(); | 367 | let opened = community.clone(); |
| 385 | - let id = community.id.clone(); | 368 | + let id = community.id; |
| 386 | - let log_id = id.clone(); | 369 | + let log_id = id; |
| 387 | - let transfer_id = id.clone(); | 370 | + let transfer_id = id; |
| 388 | - let delete_id = id.clone(); | 371 | + let delete_id = id; |
| 389 | - let voice_id = id.clone(); | 372 | + let voice_id = id; |
| 390 | let voice_enabled = community.voice_enabled; | 373 | let voice_enabled = community.voice_enabled; |
| 391 | - let pending_delete = self.chat.pending_community_delete.as_deref() == Some(id.as_str()); | 374 | + let pending_delete = self.chat.pending_community_delete == Some(id); |
| 392 | let expanded = self | 375 | let expanded = self |
| 393 | .chat | 376 | .chat |
| 394 | .transfer | 377 | .transfer |
| @@ -453,7 +436,7 @@ impl Yumush { | |||
| 453 | palette.muted, | 436 | palette.muted, |
| 454 | palette, | 437 | palette, |
| 455 | entity_action(entity, move |yumush, window, cx| { | 438 | entity_action(entity, move |yumush, window, cx| { |
| 456 | - yumush.show_logs(log_id.clone(), window, cx) | 439 | + yumush.show_logs(log_id, window, cx) |
| 457 | }), | 440 | }), |
| 458 | )) | 441 | )) |
| 459 | .child(icon_button( | 442 | .child(icon_button( |
| @@ -471,7 +454,7 @@ impl Yumush { | |||
| 471 | palette.muted, | 454 | palette.muted, |
| 472 | palette, | 455 | palette, |
| 473 | entity_action(entity, move |yumush, window, cx| { | 456 | entity_action(entity, move |yumush, window, cx| { |
| 474 | - yumush.set_builder_community_voice(&voice_id, !voice_enabled, window, cx) | 457 | + yumush.set_builder_community_voice(voice_id, !voice_enabled, window, cx) |
| 475 | }), | 458 | }), |
| 476 | )) | 459 | )) |
| 477 | .child(icon_button( | 460 | .child(icon_button( |
| @@ -485,7 +468,7 @@ impl Yumush { | |||
| 485 | }, | 468 | }, |
| 486 | palette, | 469 | palette, |
| 487 | entity_action(entity, move |yumush, window, cx| { | 470 | entity_action(entity, move |yumush, window, cx| { |
| 488 | - yumush.open_transfer(transfer_id.clone(), window, cx) | 471 | + yumush.open_transfer(transfer_id, window, cx) |
| 489 | }), | 472 | }), |
| 490 | )) | 473 | )) |
| 491 | .child( | 474 | .child( |
| @@ -504,7 +487,7 @@ impl Yumush { | |||
| 504 | }, | 487 | }, |
| 505 | palette, | 488 | palette, |
| 506 | entity_action(entity, move |yumush, window, cx| { | 489 | entity_action(entity, move |yumush, window, cx| { |
| 507 | - yumush.delete_builder_community(&delete_id, window, cx) | 490 | + yumush.delete_builder_community(delete_id, window, cx) |
| 508 | }), | 491 | }), |
| 509 | ) | 492 | ) |
| 510 | .when(pending_delete, |this| this.bg(palette.danger)), | 493 | .when(pending_delete, |this| this.bg(palette.danger)), |
crates/client/src/gui/builder/log.rsmodified+26 -8
| @@ -1,7 +1,7 @@ | |||
| 1 | use common::{ | 1 | use common::{ |
| 2 | call::ListAdminLogs, | 2 | call::ListAdminLogs, |
| 3 | - model::{AdminAction, AdminLogEntry, action_detail}, | 3 | + model::{AdminAction, AdminActionKind, AdminLogEntry}, |
| 4 | - time::{created_at_ms, now_ms}, | 4 | + time::now_ms, |
| 5 | }; | 5 | }; |
| 6 | use gpui_kit::{ | 6 | use gpui_kit::{ |
| 7 | AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, | 7 | AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, |
| @@ -21,7 +21,7 @@ use crate::gui::STAMP; | |||
| 21 | use crate::gui::{ | 21 | use crate::gui::{ |
| 22 | Palette, Yumush, | 22 | Palette, Yumush, |
| 23 | community_settings::user_name, | 23 | community_settings::user_name, |
| 24 | - entity_action, id_time, millis_time, notify_error, text, | 24 | + entity_action, millis_time, notify_error, text, |
| 25 | widget::{field, search_text}, | 25 | widget::{field, search_text}, |
| 26 | }; | 26 | }; |
| 27 | 27 | ||
| @@ -86,6 +86,24 @@ fn builder_log_text(entry: &AdminLogEntry) -> String { | |||
| 86 | } | 86 | } |
| 87 | } | 87 | } |
| 88 | 88 | ||
| 89 | +fn action_detail(action: &AdminAction) -> Option<String> { | ||
| 90 | + match action { | ||
| 91 | + AdminAction::RoleChanged { role } => Some(role.as_str().to_string()), | ||
| 92 | + AdminAction::UserRenamed { from } => Some(from.clone()), | ||
| 93 | + AdminAction::UserTimedOut { minutes } => Some(minutes.to_string()), | ||
| 94 | + AdminAction::UserBanned { reason } => reason.clone(), | ||
| 95 | + AdminAction::ReportHandled { status } => Some(status.as_str().to_string()), | ||
| 96 | + AdminAction::UserPurged { messages } => Some(messages.to_string()), | ||
| 97 | + AdminAction::VoiceMuted { muted } => Some(muted.to_string()), | ||
| 98 | + AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()), | ||
| 99 | + AdminAction::GhostVoice { seconds } => Some(seconds.to_string()), | ||
| 100 | + AdminAction::BackupCreated { name } | ||
| 101 | + | AdminAction::BackupDeleted { name } | ||
| 102 | + | AdminAction::BackupDownloaded { name } => Some(name.clone()), | ||
| 103 | + _ => None, | ||
| 104 | + } | ||
| 105 | +} | ||
| 106 | + | ||
| 89 | fn csv_field(text: &str) -> String { | 107 | fn csv_field(text: &str) -> String { |
| 90 | format!("\"{}\"", text.replace('"', "\"\"")) | 108 | format!("\"{}\"", text.replace('"', "\"\"")) |
| 91 | } | 109 | } |
| @@ -93,8 +111,8 @@ fn csv_field(text: &str) -> String { | |||
| 93 | fn builder_log_csv(entries: &[AdminLogEntry]) -> String { | 111 | fn builder_log_csv(entries: &[AdminLogEntry]) -> String { |
| 94 | let mut lines = vec!["time,actor,action,target,community,detail".to_string()]; | 112 | let mut lines = vec!["time,actor,action,target,community,detail".to_string()]; |
| 95 | for entry in entries { | 113 | for entry in entries { |
| 96 | - let time = created_at_ms(&entry.id) | 114 | + let time = Timestamp::from_millisecond(entry.created_at as i64) |
| 97 | - .and_then(|millis| Timestamp::from_millisecond(millis as i64).ok()) | 115 | + .ok() |
| 98 | .map(|timestamp| timestamp.to_string()) | 116 | .map(|timestamp| timestamp.to_string()) |
| 99 | .unwrap_or_default(); | 117 | .unwrap_or_default(); |
| 100 | let actor = entry | 118 | let actor = entry |
| @@ -108,7 +126,7 @@ fn builder_log_csv(entries: &[AdminLogEntry]) -> String { | |||
| 108 | let fields = [ | 126 | let fields = [ |
| 109 | time, | 127 | time, |
| 110 | actor, | 128 | actor, |
| 111 | - entry.action.name().to_string(), | 129 | + entry.action.kind().as_str().to_string(), |
| 112 | target, | 130 | target, |
| 113 | entry.community.clone().unwrap_or_default(), | 131 | entry.community.clone().unwrap_or_default(), |
| 114 | action_detail(&entry.action).unwrap_or_default(), | 132 | action_detail(&entry.action).unwrap_or_default(), |
| @@ -185,7 +203,7 @@ fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { | |||
| 185 | div() | 203 | div() |
| 186 | .text_size(text(11.)) | 204 | .text_size(text(11.)) |
| 187 | .text_color(palette.muted) | 205 | .text_color(palette.muted) |
| 188 | - .child(id_time(&entry.id, STAMP)), | 206 | + .child(millis_time(entry.created_at, STAMP)), |
| 189 | ), | 207 | ), |
| 190 | ) | 208 | ) |
| 191 | .children( | 209 | .children( |
| @@ -215,7 +233,7 @@ impl Yumush { | |||
| 215 | .selected_value() | 233 | .selected_value() |
| 216 | .copied() | 234 | .copied() |
| 217 | .filter(|name| *name != "All") | 235 | .filter(|name| *name != "All") |
| 218 | - .map(str::to_string); | 236 | + .and_then(AdminActionKind::parse); |
| 219 | let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx)); | 237 | let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx)); |
| 220 | let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx)); | 238 | let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx)); |
| 221 | self.fetch_builder( | 239 | self.fetch_builder( |
crates/client/src/gui/builder/messages.rsmodified+16 -21
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use common::{ | 2 | use common::{ |
| 2 | call::{DeleteMessage, SearchMessages}, | 3 | call::{DeleteMessage, SearchMessages}, |
| 3 | model::MessageHit, | 4 | model::MessageHit, |
| @@ -19,7 +20,7 @@ use crate::gui::YEAR_STAMP; | |||
| 19 | use crate::gui::{ | 20 | use crate::gui::{ |
| 20 | Palette, Yumush, avatar, | 21 | Palette, Yumush, avatar, |
| 21 | community_settings::user_name, | 22 | community_settings::user_name, |
| 22 | - entity_action, id_time, notify_error, | 23 | + entity_action, millis_time, notify_error, |
| 23 | profile::user_link, | 24 | profile::user_link, |
| 24 | text, | 25 | text, |
| 25 | widget::{field, search_text}, | 26 | widget::{field, search_text}, |
| @@ -33,8 +34,8 @@ fn message_hit_row( | |||
| 33 | entity: &Entity<Yumush>, | 34 | entity: &Entity<Yumush>, |
| 34 | palette: Palette, | 35 | palette: Palette, |
| 35 | ) -> Div { | 36 | ) -> Div { |
| 36 | - let message_id = hit.message.id.clone(); | 37 | + let message_id = hit.message.id; |
| 37 | - let community_id = hit.message.community_id.clone(); | 38 | + let community_id = hit.message.community_id; |
| 38 | let open = icon_button( | 39 | let open = icon_button( |
| 39 | format!("open_message_{}", hit.message.id), | 40 | format!("open_message_{}", hit.message.id), |
| 40 | IconName::MessageSquare, | 41 | IconName::MessageSquare, |
| @@ -42,7 +43,7 @@ fn message_hit_row( | |||
| 42 | palette.muted, | 43 | palette.muted, |
| 43 | palette, | 44 | palette, |
| 44 | entity_action(entity, move |yumush, window, cx| { | 45 | entity_action(entity, move |yumush, window, cx| { |
| 45 | - yumush.jump_to(community_id.clone(), false, window, cx) | 46 | + yumush.jump_to(community_id, false, window, cx) |
| 46 | }), | 47 | }), |
| 47 | ); | 48 | ); |
| 48 | let delete = delete_icon_button( | 49 | let delete = delete_icon_button( |
| @@ -50,11 +51,11 @@ fn message_hit_row( | |||
| 50 | pending, | 51 | pending, |
| 51 | palette, | 52 | palette, |
| 52 | entity_action(entity, move |yumush, window, cx| { | 53 | entity_action(entity, move |yumush, window, cx| { |
| 53 | - yumush.delete_builder_message(&message_id, window, cx) | 54 | + yumush.delete_builder_message(message_id, window, cx) |
| 54 | }), | 55 | }), |
| 55 | ); | 56 | ); |
| 56 | let purge = hit.author.as_ref().map(|author| { | 57 | let purge = hit.author.as_ref().map(|author| { |
| 57 | - let user_id = author.id.clone(); | 58 | + let user_id = author.id; |
| 58 | icon_button( | 59 | icon_button( |
| 59 | format!("purge_message_user_{}", hit.message.id), | 60 | format!("purge_message_user_{}", hit.message.id), |
| 60 | IconName::UserX, | 61 | IconName::UserX, |
| @@ -66,7 +67,7 @@ fn message_hit_row( | |||
| 66 | palette.danger, | 67 | palette.danger, |
| 67 | palette, | 68 | palette, |
| 68 | entity_action(entity, move |yumush, window, cx| { | 69 | entity_action(entity, move |yumush, window, cx| { |
| 69 | - yumush.purge_builder_user(&user_id, window, cx) | 70 | + yumush.purge_builder_user(user_id, window, cx) |
| 70 | }), | 71 | }), |
| 71 | ) | 72 | ) |
| 72 | .when(purge_pending, |this| { | 73 | .when(purge_pending, |this| { |
| @@ -118,7 +119,7 @@ fn message_hit_row( | |||
| 118 | .flex_shrink_0() | 119 | .flex_shrink_0() |
| 119 | .text_size(text(11.)) | 120 | .text_size(text(11.)) |
| 120 | .text_color(palette.muted) | 121 | .text_color(palette.muted) |
| 121 | - .child(id_time(&hit.message.id, YEAR_STAMP)), | 122 | + .child(millis_time(hit.message.created_at, YEAR_STAMP)), |
| 122 | ), | 123 | ), |
| 123 | ) | 124 | ) |
| 124 | .child( | 125 | .child( |
| @@ -186,11 +187,11 @@ impl Yumush { | |||
| 186 | .builder_messages | 187 | .builder_messages |
| 187 | .iter() | 188 | .iter() |
| 188 | .map(|hit| { | 189 | .map(|hit| { |
| 189 | - let pending = | 190 | + let pending = self.chat.pending_message_delete == Some(hit.message.id); |
| 190 | - self.chat.pending_message_delete.as_deref() == Some(hit.message.id.as_str()); | 191 | + let purge_pending = hit |
| 191 | - let purge_pending = hit.author.as_ref().is_some_and(|author| { | 192 | + .author |
| 192 | - self.chat.pending_builder_purge.as_deref() == Some(author.id.as_str()) | 193 | + .as_ref() |
| 193 | - }); | 194 | + .is_some_and(|author| self.chat.pending_builder_purge == Some(author.id)); |
| 194 | let picture = match &hit.author { | 195 | let picture = match &hit.author { |
| 195 | Some(author) => avatar(palette, author, px(28.), text(11.), &self.chat.avatars), | 196 | Some(author) => avatar(palette, author, px(28.), text(11.), &self.chat.avatars), |
| 196 | None => div() | 197 | None => div() |
| @@ -253,7 +254,7 @@ impl Yumush { | |||
| 253 | 254 | ||
| 254 | pub(super) fn delete_builder_message( | 255 | pub(super) fn delete_builder_message( |
| 255 | &mut self, | 256 | &mut self, |
| 256 | - message_id: &str, | 257 | + message_id: Id, |
| 257 | window: &mut Window, | 258 | window: &mut Window, |
| 258 | cx: &mut Context<Self>, | 259 | cx: &mut Context<Self>, |
| 259 | ) { | 260 | ) { |
| @@ -262,15 +263,9 @@ impl Yumush { | |||
| 262 | return; | 263 | return; |
| 263 | } | 264 | } |
| 264 | let network = self.network.clone(); | 265 | let network = self.network.clone(); |
| 265 | - let message_id = message_id.to_string(); | ||
| 266 | 266 | ||
| 267 | cx.spawn_in(window, async move |this, cx| { | 267 | cx.spawn_in(window, async move |this, cx| { |
| 268 | - match network | 268 | + match network.call(DeleteMessage { message_id }).await { |
| 269 | - .call(DeleteMessage { | ||
| 270 | - message_id: message_id.clone(), | ||
| 271 | - }) | ||
| 272 | - .await | ||
| 273 | - { | ||
| 274 | Ok(()) => { | 269 | Ok(()) => { |
| 275 | let _ = this.update(cx, |yumush, cx| { | 270 | let _ = this.update(cx, |yumush, cx| { |
| 276 | yumush | 271 | yumush |
crates/client/src/gui/builder/reports.rsmodified+18 -22
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::future::Future; | 2 | use std::future::Future; |
| 2 | 3 | ||
| 3 | use common::{ | 4 | use common::{ |
| @@ -15,7 +16,7 @@ use crate::{ | |||
| 15 | gui::{ | 16 | gui::{ |
| 16 | Palette, Yumush, avatar, badge, clickable, | 17 | Palette, Yumush, avatar, badge, clickable, |
| 17 | community_settings::user_name, | 18 | community_settings::user_name, |
| 18 | - entity_action, id_time, notify_error, | 19 | + entity_action, millis_time, notify_error, |
| 19 | profile::user_link, | 20 | profile::user_link, |
| 20 | settings_page::{segment, segment_track}, | 21 | settings_page::{segment, segment_track}, |
| 21 | text, | 22 | text, |
| @@ -108,12 +109,11 @@ impl Yumush { | |||
| 108 | 109 | ||
| 109 | pub(super) fn handle_report( | 110 | pub(super) fn handle_report( |
| 110 | &mut self, | 111 | &mut self, |
| 111 | - report_id: &str, | 112 | + report_id: Id, |
| 112 | status: ReportStatus, | 113 | status: ReportStatus, |
| 113 | window: &mut Window, | 114 | window: &mut Window, |
| 114 | cx: &mut Context<Self>, | 115 | cx: &mut Context<Self>, |
| 115 | ) { | 116 | ) { |
| 116 | - let report_id = report_id.to_string(); | ||
| 117 | self.report_action(window, cx, move |network| async move { | 117 | self.report_action(window, cx, move |network| async move { |
| 118 | network.call(HandleReport { report_id, status }).await | 118 | network.call(HandleReport { report_id, status }).await |
| 119 | }); | 119 | }); |
| @@ -121,11 +121,10 @@ impl Yumush { | |||
| 121 | 121 | ||
| 122 | pub(super) fn delete_report_message( | 122 | pub(super) fn delete_report_message( |
| 123 | &mut self, | 123 | &mut self, |
| 124 | - message_id: &str, | 124 | + message_id: Id, |
| 125 | window: &mut Window, | 125 | window: &mut Window, |
| 126 | cx: &mut Context<Self>, | 126 | cx: &mut Context<Self>, |
| 127 | ) { | 127 | ) { |
| 128 | - let message_id = message_id.to_string(); | ||
| 129 | self.report_action(window, cx, move |network| async move { | 128 | self.report_action(window, cx, move |network| async move { |
| 130 | network.call(DeleteMessage { message_id }).await | 129 | network.call(DeleteMessage { message_id }).await |
| 131 | }); | 130 | }); |
| @@ -133,11 +132,10 @@ impl Yumush { | |||
| 133 | 132 | ||
| 134 | pub(super) fn timeout_report_target( | 133 | pub(super) fn timeout_report_target( |
| 135 | &mut self, | 134 | &mut self, |
| 136 | - user_id: &str, | 135 | + user_id: Id, |
| 137 | window: &mut Window, | 136 | window: &mut Window, |
| 138 | cx: &mut Context<Self>, | 137 | cx: &mut Context<Self>, |
| 139 | ) { | 138 | ) { |
| 140 | - let user_id = user_id.to_string(); | ||
| 141 | self.report_action(window, cx, move |network| async move { | 139 | self.report_action(window, cx, move |network| async move { |
| 142 | network | 140 | network |
| 143 | .call(TimeoutUser { | 141 | .call(TimeoutUser { |
| @@ -150,12 +148,11 @@ impl Yumush { | |||
| 150 | 148 | ||
| 151 | pub(super) fn ban_report_target( | 149 | pub(super) fn ban_report_target( |
| 152 | &mut self, | 150 | &mut self, |
| 153 | - user_id: &str, | 151 | + user_id: Id, |
| 154 | reason: &str, | 152 | reason: &str, |
| 155 | window: &mut Window, | 153 | window: &mut Window, |
| 156 | cx: &mut Context<Self>, | 154 | cx: &mut Context<Self>, |
| 157 | ) { | 155 | ) { |
| 158 | - let user_id = user_id.to_string(); | ||
| 159 | let reason = reason.to_string(); | 156 | let reason = reason.to_string(); |
| 160 | self.report_action(window, cx, move |network| async move { | 157 | self.report_action(window, cx, move |network| async move { |
| 161 | network | 158 | network |
| @@ -213,7 +210,7 @@ impl Yumush { | |||
| 213 | Some(user) => { | 210 | Some(user) => { |
| 214 | avatar(palette, user, px(20.), text(9.), &self.chat.avatars).into_any_element() | 211 | avatar(palette, user, px(20.), text(9.), &self.chat.avatars).into_any_element() |
| 215 | } | 212 | } |
| 216 | - None => badge(palette, &report.id, "someone", px(20.), text(9.)).into_any_element(), | 213 | + None => badge(palette, report.id, "someone", px(20.), text(9.)).into_any_element(), |
| 217 | }; | 214 | }; |
| 218 | let head = div() | 215 | let head = div() |
| 219 | .flex_1() | 216 | .flex_1() |
| @@ -259,7 +256,7 @@ impl Yumush { | |||
| 259 | .child(format!( | 256 | .child(format!( |
| 260 | "{} · {}", | 257 | "{} · {}", |
| 261 | report.community.as_deref().unwrap_or("deleted community"), | 258 | report.community.as_deref().unwrap_or("deleted community"), |
| 262 | - id_time(&report.id, STAMP) | 259 | + millis_time(report.created_at, STAMP) |
| 263 | )); | 260 | )); |
| 264 | let actions = self.report_actions(report, entity, palette); | 261 | let actions = self.report_actions(report, entity, palette); |
| 265 | let handled = (report.status != ReportStatus::Open).then(|| { | 262 | let handled = (report.status != ReportStatus::Open).then(|| { |
| @@ -320,15 +317,15 @@ impl Yumush { | |||
| 320 | if report.status != ReportStatus::Open { | 317 | if report.status != ReportStatus::Open { |
| 321 | return Vec::new(); | 318 | return Vec::new(); |
| 322 | } | 319 | } |
| 323 | - let resolve_id = report.id.clone(); | 320 | + let resolve_id = report.id; |
| 324 | - let dismiss_id = report.id.clone(); | 321 | + let dismiss_id = report.id; |
| 325 | let mut buttons = vec![ | 322 | let mut buttons = vec![ |
| 326 | plain_button( | 323 | plain_button( |
| 327 | format!("resolve_report_{}", report.id), | 324 | format!("resolve_report_{}", report.id), |
| 328 | "Resolve", | 325 | "Resolve", |
| 329 | palette, | 326 | palette, |
| 330 | entity_action(entity, move |yumush, window, cx| { | 327 | entity_action(entity, move |yumush, window, cx| { |
| 331 | - yumush.handle_report(&resolve_id, ReportStatus::Resolved, window, cx) | 328 | + yumush.handle_report(resolve_id, ReportStatus::Resolved, window, cx) |
| 332 | }), | 329 | }), |
| 333 | ) | 330 | ) |
| 334 | .into_any_element(), | 331 | .into_any_element(), |
| @@ -337,28 +334,27 @@ impl Yumush { | |||
| 337 | "Dismiss", | 334 | "Dismiss", |
| 338 | palette, | 335 | palette, |
| 339 | entity_action(entity, move |yumush, window, cx| { | 336 | entity_action(entity, move |yumush, window, cx| { |
| 340 | - yumush.handle_report(&dismiss_id, ReportStatus::Dismissed, window, cx) | 337 | + yumush.handle_report(dismiss_id, ReportStatus::Dismissed, window, cx) |
| 341 | }), | 338 | }), |
| 342 | ) | 339 | ) |
| 343 | .into_any_element(), | 340 | .into_any_element(), |
| 344 | ]; | 341 | ]; |
| 345 | - if let (Some(message_id), Some(_)) = (&report.message_id, &report.community_id) { | 342 | + if let (Some(message_id), Some(_)) = (report.message_id, report.community_id) { |
| 346 | - let message_id = message_id.clone(); | ||
| 347 | buttons.push( | 343 | buttons.push( |
| 348 | plain_button( | 344 | plain_button( |
| 349 | format!("delete_report_message_{}", report.id), | 345 | format!("delete_report_message_{}", report.id), |
| 350 | "Delete message", | 346 | "Delete message", |
| 351 | palette, | 347 | palette, |
| 352 | entity_action(entity, move |yumush, window, cx| { | 348 | entity_action(entity, move |yumush, window, cx| { |
| 353 | - yumush.delete_report_message(&message_id, window, cx) | 349 | + yumush.delete_report_message(message_id, window, cx) |
| 354 | }), | 350 | }), |
| 355 | ) | 351 | ) |
| 356 | .into_any_element(), | 352 | .into_any_element(), |
| 357 | ); | 353 | ); |
| 358 | } | 354 | } |
| 359 | if let Some(target) = &report.target { | 355 | if let Some(target) = &report.target { |
| 360 | - let timeout_id = target.id.clone(); | 356 | + let timeout_id = target.id; |
| 361 | - let ban_id = target.id.clone(); | 357 | + let ban_id = target.id; |
| 362 | let ban_reason = report.reason.clone(); | 358 | let ban_reason = report.reason.clone(); |
| 363 | buttons.push( | 359 | buttons.push( |
| 364 | plain_button( | 360 | plain_button( |
| @@ -366,7 +362,7 @@ impl Yumush { | |||
| 366 | "Timeout 1h", | 362 | "Timeout 1h", |
| 367 | palette, | 363 | palette, |
| 368 | entity_action(entity, move |yumush, window, cx| { | 364 | entity_action(entity, move |yumush, window, cx| { |
| 369 | - yumush.timeout_report_target(&timeout_id, window, cx) | 365 | + yumush.timeout_report_target(timeout_id, window, cx) |
| 370 | }), | 366 | }), |
| 371 | ) | 367 | ) |
| 372 | .into_any_element(), | 368 | .into_any_element(), |
| @@ -377,7 +373,7 @@ impl Yumush { | |||
| 377 | "Ban", | 373 | "Ban", |
| 378 | palette, | 374 | palette, |
| 379 | entity_action(entity, move |yumush, window, cx| { | 375 | entity_action(entity, move |yumush, window, cx| { |
| 380 | - yumush.ban_report_target(&ban_id, &ban_reason, window, cx) | 376 | + yumush.ban_report_target(ban_id, &ban_reason, window, cx) |
| 381 | }), | 377 | }), |
| 382 | ) | 378 | ) |
| 383 | .into_any_element(), | 379 | .into_any_element(), |
crates/client/src/gui/builder/storage.rsmodified+7 -8
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use common::{ | 2 | use common::{ |
| 2 | call::{DeleteAttachment, ListAttachments}, | 3 | call::{DeleteAttachment, ListAttachments}, |
| 3 | model::AttachmentInfo, | 4 | model::AttachmentInfo, |
| @@ -16,7 +17,7 @@ use super::ui::{ | |||
| 16 | toolbar, | 17 | toolbar, |
| 17 | }; | 18 | }; |
| 18 | use crate::gui::{ | 19 | use crate::gui::{ |
| 19 | - DATE, Palette, Yumush, community_settings::user_name, entity_action, id_time, notify_error, | 20 | + DATE, Palette, Yumush, community_settings::user_name, entity_action, millis_time, notify_error, |
| 20 | storage, text, widget::field, | 21 | storage, text, widget::field, |
| 21 | }; | 22 | }; |
| 22 | 23 | ||
| @@ -85,13 +86,13 @@ fn attachment_row( | |||
| 85 | entity: &Entity<Yumush>, | 86 | entity: &Entity<Yumush>, |
| 86 | palette: Palette, | 87 | palette: Palette, |
| 87 | ) -> Div { | 88 | ) -> Div { |
| 88 | - let attachment_id = info.attachment.id.clone(); | 89 | + let attachment_id = info.attachment.id; |
| 89 | let delete = delete_icon_button( | 90 | let delete = delete_icon_button( |
| 90 | format!("delete_attachment_{}", info.attachment.id), | 91 | format!("delete_attachment_{}", info.attachment.id), |
| 91 | pending, | 92 | pending, |
| 92 | palette, | 93 | palette, |
| 93 | entity_action(entity, move |yumush, window, cx| { | 94 | entity_action(entity, move |yumush, window, cx| { |
| 94 | - yumush.delete_builder_attachment(&attachment_id, window, cx) | 95 | + yumush.delete_builder_attachment(attachment_id, window, cx) |
| 95 | }), | 96 | }), |
| 96 | ); | 97 | ); |
| 97 | 98 | ||
| @@ -126,7 +127,7 @@ fn attachment_row( | |||
| 126 | "{} · {} · {}", | 127 | "{} · {} · {}", |
| 127 | user_name(&info.uploader), | 128 | user_name(&info.uploader), |
| 128 | info.community, | 129 | info.community, |
| 129 | - id_time(&info.attachment.id, DATE) | 130 | + millis_time(info.attachment.created_at, DATE) |
| 130 | )), | 131 | )), |
| 131 | ), | 132 | ), |
| 132 | ) | 133 | ) |
| @@ -220,8 +221,7 @@ impl Yumush { | |||
| 220 | .builder_attachments | 221 | .builder_attachments |
| 221 | .iter() | 222 | .iter() |
| 222 | .map(|info| { | 223 | .map(|info| { |
| 223 | - let pending = self.chat.pending_attachment_delete.as_deref() | 224 | + let pending = self.chat.pending_attachment_delete == Some(info.attachment.id); |
| 224 | - == Some(info.attachment.id.as_str()); | ||
| 225 | attachment_row(info, pending, entity, palette) | 225 | attachment_row(info, pending, entity, palette) |
| 226 | }) | 226 | }) |
| 227 | .collect(); | 227 | .collect(); |
| @@ -309,7 +309,7 @@ impl Yumush { | |||
| 309 | 309 | ||
| 310 | pub(super) fn delete_builder_attachment( | 310 | pub(super) fn delete_builder_attachment( |
| 311 | &mut self, | 311 | &mut self, |
| 312 | - attachment_id: &str, | 312 | + attachment_id: Id, |
| 313 | window: &mut Window, | 313 | window: &mut Window, |
| 314 | cx: &mut Context<Self>, | 314 | cx: &mut Context<Self>, |
| 315 | ) { | 315 | ) { |
| @@ -318,7 +318,6 @@ impl Yumush { | |||
| 318 | return; | 318 | return; |
| 319 | } | 319 | } |
| 320 | let network = self.network.clone(); | 320 | let network = self.network.clone(); |
| 321 | - let attachment_id = attachment_id.to_string(); | ||
| 322 | 321 | ||
| 323 | cx.spawn_in(window, async move |this, cx| { | 322 | cx.spawn_in(window, async move |this, cx| { |
| 324 | match network.call(DeleteAttachment { attachment_id }).await { | 323 | match network.call(DeleteAttachment { attachment_id }).await { |
crates/client/src/gui/builder/ui.rsmodified+3 -3
| @@ -13,12 +13,12 @@ pub(super) fn to_units(bytes: u64, unit: u64) -> String { | |||
| 13 | (bytes / unit).to_string() | 13 | (bytes / unit).to_string() |
| 14 | } | 14 | } |
| 15 | 15 | ||
| 16 | -pub(super) fn confirmed(pending: &mut Option<String>, id: &str) -> bool { | 16 | +pub(super) fn confirmed<T: PartialEq>(pending: &mut Option<T>, id: T) -> bool { |
| 17 | - if pending.as_deref() == Some(id) { | 17 | + if pending.as_ref() == Some(&id) { |
| 18 | *pending = None; | 18 | *pending = None; |
| 19 | true | 19 | true |
| 20 | } else { | 20 | } else { |
| 21 | - *pending = Some(id.to_string()); | 21 | + *pending = Some(id); |
| 22 | false | 22 | false |
| 23 | } | 23 | } |
| 24 | } | 24 | } |
crates/client/src/gui/builder/users.rsmodified+75 -102
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::future::Future; | 2 | use std::future::Future; |
| 2 | 3 | ||
| 3 | use common::{ | 4 | use common::{ |
| @@ -23,8 +24,8 @@ use super::ui::{ | |||
| 23 | }; | 24 | }; |
| 24 | use crate::{ | 25 | use crate::{ |
| 25 | gui::{ | 26 | gui::{ |
| 26 | - DATE, DAY, Palette, Tooltip as _, Yumush, avatar, clickable, entity_action, id_time, | 27 | + DATE, DAY, Palette, Tooltip as _, Yumush, avatar, clickable, entity_action, millis_time, |
| 27 | - millis_time, notify_error, | 28 | + notify_error, |
| 28 | profile::user_link, | 29 | profile::user_link, |
| 29 | text, | 30 | text, |
| 30 | widget::{field, search_text}, | 31 | widget::{field, search_text}, |
| @@ -81,13 +82,12 @@ impl Yumush { | |||
| 81 | 82 | ||
| 82 | pub(super) fn set_builder_role( | 83 | pub(super) fn set_builder_role( |
| 83 | &mut self, | 84 | &mut self, |
| 84 | - user_id: &str, | 85 | + user_id: Id, |
| 85 | role: Role, | 86 | role: Role, |
| 86 | window: &mut Window, | 87 | window: &mut Window, |
| 87 | cx: &mut Context<Self>, | 88 | cx: &mut Context<Self>, |
| 88 | ) { | 89 | ) { |
| 89 | let network = self.network.clone(); | 90 | let network = self.network.clone(); |
| 90 | - let user_id = user_id.to_string(); | ||
| 91 | 91 | ||
| 92 | cx.spawn_in(window, async move |this, cx| { | 92 | cx.spawn_in(window, async move |this, cx| { |
| 93 | match network.call(SetRole { user_id, role }).await { | 93 | match network.call(SetRole { user_id, role }).await { |
| @@ -112,7 +112,7 @@ impl Yumush { | |||
| 112 | 112 | ||
| 113 | pub(super) fn delete_builder_user( | 113 | pub(super) fn delete_builder_user( |
| 114 | &mut self, | 114 | &mut self, |
| 115 | - user_id: &str, | 115 | + user_id: Id, |
| 116 | window: &mut Window, | 116 | window: &mut Window, |
| 117 | cx: &mut Context<Self>, | 117 | cx: &mut Context<Self>, |
| 118 | ) { | 118 | ) { |
| @@ -121,15 +121,9 @@ impl Yumush { | |||
| 121 | return; | 121 | return; |
| 122 | } | 122 | } |
| 123 | let network = self.network.clone(); | 123 | let network = self.network.clone(); |
| 124 | - let user_id = user_id.to_string(); | ||
| 125 | 124 | ||
| 126 | cx.spawn_in(window, async move |this, cx| { | 125 | cx.spawn_in(window, async move |this, cx| { |
| 127 | - match network | 126 | + match network.call(DeleteUser { user_id }).await { |
| 128 | - .call(DeleteUser { | ||
| 129 | - user_id: user_id.clone(), | ||
| 130 | - }) | ||
| 131 | - .await | ||
| 132 | - { | ||
| 133 | Ok(()) => { | 127 | Ok(()) => { |
| 134 | let _ = this.update(cx, |yumush, cx| { | 128 | let _ = this.update(cx, |yumush, cx| { |
| 135 | yumush | 129 | yumush |
| @@ -166,12 +160,11 @@ impl Yumush { | |||
| 166 | 160 | ||
| 167 | pub(super) fn suspend_builder_user( | 161 | pub(super) fn suspend_builder_user( |
| 168 | &mut self, | 162 | &mut self, |
| 169 | - user_id: &str, | 163 | + user_id: Id, |
| 170 | suspended: bool, | 164 | suspended: bool, |
| 171 | window: &mut Window, | 165 | window: &mut Window, |
| 172 | cx: &mut Context<Self>, | 166 | cx: &mut Context<Self>, |
| 173 | ) { | 167 | ) { |
| 174 | - let user_id = user_id.to_string(); | ||
| 175 | self.builder_user_action(window, cx, move |network| async move { | 168 | self.builder_user_action(window, cx, move |network| async move { |
| 176 | network.call(SuspendUser { user_id, suspended }).await | 169 | network.call(SuspendUser { user_id, suspended }).await |
| 177 | }); | 170 | }); |
| @@ -179,11 +172,10 @@ impl Yumush { | |||
| 179 | 172 | ||
| 180 | pub(super) fn revoke_builder_sessions( | 173 | pub(super) fn revoke_builder_sessions( |
| 181 | &mut self, | 174 | &mut self, |
| 182 | - user_id: &str, | 175 | + user_id: Id, |
| 183 | window: &mut Window, | 176 | window: &mut Window, |
| 184 | cx: &mut Context<Self>, | 177 | cx: &mut Context<Self>, |
| 185 | ) { | 178 | ) { |
| 186 | - let user_id = user_id.to_string(); | ||
| 187 | self.builder_user_action(window, cx, move |network| async move { | 179 | self.builder_user_action(window, cx, move |network| async move { |
| 188 | network.call(RevokeSessions { user_id }).await | 180 | network.call(RevokeSessions { user_id }).await |
| 189 | }); | 181 | }); |
| @@ -191,21 +183,20 @@ impl Yumush { | |||
| 191 | 183 | ||
| 192 | pub(super) fn clear_builder_profile( | 184 | pub(super) fn clear_builder_profile( |
| 193 | &mut self, | 185 | &mut self, |
| 194 | - user_id: &str, | 186 | + user_id: Id, |
| 195 | window: &mut Window, | 187 | window: &mut Window, |
| 196 | cx: &mut Context<Self>, | 188 | cx: &mut Context<Self>, |
| 197 | ) { | 189 | ) { |
| 198 | - let user_id = user_id.to_string(); | ||
| 199 | self.builder_user_action(window, cx, move |network| async move { | 190 | self.builder_user_action(window, cx, move |network| async move { |
| 200 | network.call(ClearProfile { user_id }).await.map(|_| ()) | 191 | network.call(ClearProfile { user_id }).await.map(|_| ()) |
| 201 | }); | 192 | }); |
| 202 | } | 193 | } |
| 203 | 194 | ||
| 204 | - pub(super) fn toggle_builder_password(&mut self, user_id: &str, cx: &mut Context<Self>) { | 195 | + pub(super) fn toggle_builder_password(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 205 | - if self.chat.pending_builder_password.as_deref() == Some(user_id) { | 196 | + if self.chat.pending_builder_password == Some(user_id) { |
| 206 | self.chat.pending_builder_password = None; | 197 | self.chat.pending_builder_password = None; |
| 207 | } else { | 198 | } else { |
| 208 | - self.chat.pending_builder_password = Some(user_id.to_string()); | 199 | + self.chat.pending_builder_password = Some(user_id); |
| 209 | } | 200 | } |
| 210 | cx.notify(); | 201 | cx.notify(); |
| 211 | } | 202 | } |
| @@ -223,21 +214,11 @@ impl Yumush { | |||
| 223 | }); | 214 | }); |
| 224 | } | 215 | } |
| 225 | 216 | ||
| 226 | - pub(super) fn load_sessions( | 217 | + pub(super) fn load_sessions(&self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 227 | - &self, | ||
| 228 | - user_id: String, | ||
| 229 | - window: &mut Window, | ||
| 230 | - cx: &mut Context<Self>, | ||
| 231 | - ) { | ||
| 232 | let network = self.network.clone(); | 218 | let network = self.network.clone(); |
| 233 | 219 | ||
| 234 | cx.spawn_in(window, async move |this, cx| { | 220 | cx.spawn_in(window, async move |this, cx| { |
| 235 | - match network | 221 | + match network.call(ListSessions { user_id }).await { |
| 236 | - .call(ListSessions { | ||
| 237 | - user_id: user_id.clone(), | ||
| 238 | - }) | ||
| 239 | - .await | ||
| 240 | - { | ||
| 241 | Ok(sessions) => { | 222 | Ok(sessions) => { |
| 242 | let _ = this.update(cx, |yumush, cx| { | 223 | let _ = this.update(cx, |yumush, cx| { |
| 243 | yumush.chat.builder_sessions = Some((user_id, sessions)); | 224 | yumush.chat.builder_sessions = Some((user_id, sessions)); |
| @@ -252,7 +233,7 @@ impl Yumush { | |||
| 252 | 233 | ||
| 253 | pub(super) fn toggle_builder_sessions( | 234 | pub(super) fn toggle_builder_sessions( |
| 254 | &mut self, | 235 | &mut self, |
| 255 | - user_id: &str, | 236 | + user_id: Id, |
| 256 | window: &mut Window, | 237 | window: &mut Window, |
| 257 | cx: &mut Context<Self>, | 238 | cx: &mut Context<Self>, |
| 258 | ) { | 239 | ) { |
| @@ -260,30 +241,28 @@ impl Yumush { | |||
| 260 | .chat | 241 | .chat |
| 261 | .builder_sessions | 242 | .builder_sessions |
| 262 | .as_ref() | 243 | .as_ref() |
| 263 | - .is_some_and(|(open, _)| open == user_id) | 244 | + .is_some_and(|(open, _)| *open == user_id) |
| 264 | { | 245 | { |
| 265 | self.chat.builder_sessions = None; | 246 | self.chat.builder_sessions = None; |
| 266 | cx.notify(); | 247 | cx.notify(); |
| 267 | return; | 248 | return; |
| 268 | } | 249 | } |
| 269 | - self.load_sessions(user_id.to_string(), window, cx); | 250 | + self.load_sessions(user_id, window, cx); |
| 270 | } | 251 | } |
| 271 | 252 | ||
| 272 | pub(super) fn revoke_builder_session( | 253 | pub(super) fn revoke_builder_session( |
| 273 | &mut self, | 254 | &mut self, |
| 274 | - user_id: &str, | 255 | + user_id: Id, |
| 275 | - session_id: &str, | 256 | + session_id: Id, |
| 276 | window: &mut Window, | 257 | window: &mut Window, |
| 277 | cx: &mut Context<Self>, | 258 | cx: &mut Context<Self>, |
| 278 | ) { | 259 | ) { |
| 279 | let network = self.network.clone(); | 260 | let network = self.network.clone(); |
| 280 | - let user_id = user_id.to_string(); | ||
| 281 | - let session_id = session_id.to_string(); | ||
| 282 | 261 | ||
| 283 | cx.spawn_in(window, async move |this, cx| { | 262 | cx.spawn_in(window, async move |this, cx| { |
| 284 | match network | 263 | match network |
| 285 | .call(RevokeSession { | 264 | .call(RevokeSession { |
| 286 | - user_id: user_id.clone(), | 265 | + user_id, |
| 287 | session_id, | 266 | session_id, |
| 288 | }) | 267 | }) |
| 289 | .await | 268 | .await |
| @@ -299,11 +278,11 @@ impl Yumush { | |||
| 299 | .detach(); | 278 | .detach(); |
| 300 | } | 279 | } |
| 301 | 280 | ||
| 302 | - pub(super) fn toggle_builder_rename(&mut self, user_id: &str, cx: &mut Context<Self>) { | 281 | + pub(super) fn toggle_builder_rename(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 303 | - if self.chat.pending_builder_rename.as_deref() == Some(user_id) { | 282 | + if self.chat.pending_builder_rename == Some(user_id) { |
| 304 | self.chat.pending_builder_rename = None; | 283 | self.chat.pending_builder_rename = None; |
| 305 | } else { | 284 | } else { |
| 306 | - self.chat.pending_builder_rename = Some(user_id.to_string()); | 285 | + self.chat.pending_builder_rename = Some(user_id); |
| 307 | } | 286 | } |
| 308 | cx.notify(); | 287 | cx.notify(); |
| 309 | } | 288 | } |
| @@ -324,17 +303,17 @@ impl Yumush { | |||
| 324 | }); | 303 | }); |
| 325 | } | 304 | } |
| 326 | 305 | ||
| 327 | - pub(super) fn toggle_builder_timeout(&mut self, user_id: &str, cx: &mut Context<Self>) { | 306 | + pub(super) fn toggle_builder_timeout(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 328 | - if self.chat.pending_builder_timeout.as_deref() == Some(user_id) { | 307 | + if self.chat.pending_builder_timeout == Some(user_id) { |
| 329 | self.chat.pending_builder_timeout = None; | 308 | self.chat.pending_builder_timeout = None; |
| 330 | } else { | 309 | } else { |
| 331 | - self.chat.pending_builder_timeout = Some(user_id.to_string()); | 310 | + self.chat.pending_builder_timeout = Some(user_id); |
| 332 | } | 311 | } |
| 333 | cx.notify(); | 312 | cx.notify(); |
| 334 | } | 313 | } |
| 335 | 314 | ||
| 336 | pub(super) fn confirm_builder_timeout(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 315 | pub(super) fn confirm_builder_timeout(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 337 | - let Some(user_id) = self.chat.pending_builder_timeout.clone() else { | 316 | + let Some(user_id) = self.chat.pending_builder_timeout else { |
| 338 | return; | 317 | return; |
| 339 | }; | 318 | }; |
| 340 | let minutes = self.chat.builder_timeout.read(cx).text().to_string(); | 319 | let minutes = self.chat.builder_timeout.read(cx).text().to_string(); |
| @@ -350,11 +329,11 @@ impl Yumush { | |||
| 350 | }); | 329 | }); |
| 351 | } | 330 | } |
| 352 | 331 | ||
| 353 | - pub(super) fn toggle_builder_ban(&mut self, user_id: &str, cx: &mut Context<Self>) { | 332 | + pub(super) fn toggle_builder_ban(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 354 | - if self.chat.pending_builder_ban.as_deref() == Some(user_id) { | 333 | + if self.chat.pending_builder_ban == Some(user_id) { |
| 355 | self.chat.pending_builder_ban = None; | 334 | self.chat.pending_builder_ban = None; |
| 356 | } else { | 335 | } else { |
| 357 | - self.chat.pending_builder_ban = Some(user_id.to_string()); | 336 | + self.chat.pending_builder_ban = Some(user_id); |
| 358 | } | 337 | } |
| 359 | cx.notify(); | 338 | cx.notify(); |
| 360 | } | 339 | } |
| @@ -391,7 +370,7 @@ impl Yumush { | |||
| 391 | 370 | ||
| 392 | pub(super) fn purge_builder_user( | 371 | pub(super) fn purge_builder_user( |
| 393 | &mut self, | 372 | &mut self, |
| 394 | - user_id: &str, | 373 | + user_id: Id, |
| 395 | window: &mut Window, | 374 | window: &mut Window, |
| 396 | cx: &mut Context<Self>, | 375 | cx: &mut Context<Self>, |
| 397 | ) { | 376 | ) { |
| @@ -400,15 +379,9 @@ impl Yumush { | |||
| 400 | return; | 379 | return; |
| 401 | } | 380 | } |
| 402 | let network = self.network.clone(); | 381 | let network = self.network.clone(); |
| 403 | - let user_id = user_id.to_string(); | ||
| 404 | 382 | ||
| 405 | cx.spawn_in(window, async move |this, cx| { | 383 | cx.spawn_in(window, async move |this, cx| { |
| 406 | - match network | 384 | + match network.call(PurgeUser { user_id }).await { |
| 407 | - .call(PurgeUser { | ||
| 408 | - user_id: user_id.clone(), | ||
| 409 | - }) | ||
| 410 | - .await | ||
| 411 | - { | ||
| 412 | Ok(()) => { | 385 | Ok(()) => { |
| 413 | let _ = this.update_in(cx, |yumush, window, cx| { | 386 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 414 | yumush | 387 | yumush |
| @@ -508,7 +481,7 @@ impl Yumush { | |||
| 508 | 481 | ||
| 509 | pub(super) fn builder_timeout_row( | 482 | pub(super) fn builder_timeout_row( |
| 510 | &self, | 483 | &self, |
| 511 | - user_id: &str, | 484 | + user_id: Id, |
| 512 | entity: &Entity<Self>, | 485 | entity: &Entity<Self>, |
| 513 | palette: Palette, | 486 | palette: Palette, |
| 514 | ) -> Div { | 487 | ) -> Div { |
| @@ -536,7 +509,7 @@ impl Yumush { | |||
| 536 | 509 | ||
| 537 | pub(super) fn builder_ban_row( | 510 | pub(super) fn builder_ban_row( |
| 538 | &self, | 511 | &self, |
| 539 | - user_id: &str, | 512 | + user_id: Id, |
| 540 | entity: &Entity<Self>, | 513 | entity: &Entity<Self>, |
| 541 | palette: Palette, | 514 | palette: Palette, |
| 542 | ) -> Div { | 515 | ) -> Div { |
| @@ -576,13 +549,13 @@ impl Yumush { | |||
| 576 | 549 | ||
| 577 | pub(super) fn builder_session_row( | 550 | pub(super) fn builder_session_row( |
| 578 | &self, | 551 | &self, |
| 579 | - user_id: &str, | 552 | + user_id: Id, |
| 580 | session: &SessionInfo, | 553 | session: &SessionInfo, |
| 581 | entity: &Entity<Self>, | 554 | entity: &Entity<Self>, |
| 582 | palette: Palette, | 555 | palette: Palette, |
| 583 | ) -> Div { | 556 | ) -> Div { |
| 584 | - let revoke_user_id = user_id.to_string(); | 557 | + let revoke_user_id = user_id; |
| 585 | - let session_id = session.id.clone(); | 558 | + let session_id = session.id; |
| 586 | let revoke_button = action_button( | 559 | let revoke_button = action_button( |
| 587 | format!("revoke_session_{}", session.id), | 560 | format!("revoke_session_{}", session.id), |
| 588 | IconName::LogOut, | 561 | IconName::LogOut, |
| @@ -591,7 +564,7 @@ impl Yumush { | |||
| 591 | palette.muted, | 564 | palette.muted, |
| 592 | palette, | 565 | palette, |
| 593 | entity_action(entity, move |yumush, window, cx| { | 566 | entity_action(entity, move |yumush, window, cx| { |
| 594 | - yumush.revoke_builder_session(&revoke_user_id, &session_id, window, cx) | 567 | + yumush.revoke_builder_session(revoke_user_id, session_id, window, cx) |
| 595 | }), | 568 | }), |
| 596 | ); | 569 | ); |
| 597 | let device = if session.device.is_empty() { | 570 | let device = if session.device.is_empty() { |
| @@ -632,7 +605,7 @@ impl Yumush { | |||
| 632 | 605 | ||
| 633 | pub(super) fn builder_rename_row( | 606 | pub(super) fn builder_rename_row( |
| 634 | &self, | 607 | &self, |
| 635 | - user_id: &str, | 608 | + user_id: Id, |
| 636 | entity: &Entity<Self>, | 609 | entity: &Entity<Self>, |
| 637 | palette: Palette, | 610 | palette: Palette, |
| 638 | ) -> Div { | 611 | ) -> Div { |
| @@ -660,7 +633,7 @@ impl Yumush { | |||
| 660 | 633 | ||
| 661 | pub(super) fn builder_password_row( | 634 | pub(super) fn builder_password_row( |
| 662 | &self, | 635 | &self, |
| 663 | - user_id: &str, | 636 | + user_id: Id, |
| 664 | entity: &Entity<Self>, | 637 | entity: &Entity<Self>, |
| 665 | palette: Palette, | 638 | palette: Palette, |
| 666 | ) -> Div { | 639 | ) -> Div { |
| @@ -711,20 +684,20 @@ impl Yumush { | |||
| 711 | .filter(|(open, _)| *open == user.id) | 684 | .filter(|(open, _)| *open == user.id) |
| 712 | .map(|(_, sessions)| sessions); | 685 | .map(|(_, sessions)| sessions); |
| 713 | let expanded = expanded_sessions.is_some(); | 686 | let expanded = expanded_sessions.is_some(); |
| 714 | - let pending_delete = self.chat.pending_builder_delete.as_deref() == Some(user.id.as_str()); | 687 | + let pending_delete = self.chat.pending_builder_delete == Some(user.id); |
| 715 | - let pending_purge = self.chat.pending_builder_purge.as_deref() == Some(user.id.as_str()); | 688 | + let pending_purge = self.chat.pending_builder_purge == Some(user.id); |
| 716 | - let role_id = user.id.clone(); | 689 | + let role_id = user.id; |
| 717 | - let delete_id = user.id.clone(); | 690 | + let delete_id = user.id; |
| 718 | - let suspend_id = user.id.clone(); | 691 | + let suspend_id = user.id; |
| 719 | - let sessions_id = user.id.clone(); | 692 | + let sessions_id = user.id; |
| 720 | - let password_id = user.id.clone(); | 693 | + let password_id = user.id; |
| 721 | - let profile_id = user.id.clone(); | 694 | + let profile_id = user.id; |
| 722 | - let sessions_list_id = user.id.clone(); | 695 | + let sessions_list_id = user.id; |
| 723 | - let rename_id = user.id.clone(); | 696 | + let rename_id = user.id; |
| 724 | - let timeout_id = user.id.clone(); | 697 | + let timeout_id = user.id; |
| 725 | - let ban_id = user.id.clone(); | 698 | + let ban_id = user.id; |
| 726 | - let purge_id = user.id.clone(); | 699 | + let purge_id = user.id; |
| 727 | - let joined = id_time(&user.id, DATE); | 700 | + let joined = millis_time(user.created_at, DATE); |
| 728 | let seen = seen_text(account.last_seen); | 701 | let seen = seen_text(account.last_seen); |
| 729 | let next_role = if builder { Role::User } else { Role::Builder }; | 702 | let next_role = if builder { Role::User } else { Role::Builder }; |
| 730 | 703 | ||
| @@ -749,7 +722,7 @@ impl Yumush { | |||
| 749 | tone, | 722 | tone, |
| 750 | palette, | 723 | palette, |
| 751 | entity_action(entity, move |yumush, window, cx| { | 724 | entity_action(entity, move |yumush, window, cx| { |
| 752 | - yumush.set_builder_role(&role_id, next_role, window, cx) | 725 | + yumush.set_builder_role(role_id, next_role, window, cx) |
| 753 | }), | 726 | }), |
| 754 | ); | 727 | ); |
| 755 | 728 | ||
| @@ -765,7 +738,7 @@ impl Yumush { | |||
| 765 | tone, | 738 | tone, |
| 766 | palette, | 739 | palette, |
| 767 | entity_action(entity, move |yumush, window, cx| { | 740 | entity_action(entity, move |yumush, window, cx| { |
| 768 | - yumush.suspend_builder_user(&suspend_id, !suspended, window, cx) | 741 | + yumush.suspend_builder_user(suspend_id, !suspended, window, cx) |
| 769 | }), | 742 | }), |
| 770 | ); | 743 | ); |
| 771 | 744 | ||
| @@ -777,7 +750,7 @@ impl Yumush { | |||
| 777 | tone, | 750 | tone, |
| 778 | palette, | 751 | palette, |
| 779 | entity_action(entity, move |yumush, window, cx| { | 752 | entity_action(entity, move |yumush, window, cx| { |
| 780 | - yumush.revoke_builder_sessions(&sessions_id, window, cx) | 753 | + yumush.revoke_builder_sessions(sessions_id, window, cx) |
| 781 | }), | 754 | }), |
| 782 | ); | 755 | ); |
| 783 | 756 | ||
| @@ -789,7 +762,7 @@ impl Yumush { | |||
| 789 | tone, | 762 | tone, |
| 790 | palette, | 763 | palette, |
| 791 | entity_action(entity, move |yumush, _, cx| { | 764 | entity_action(entity, move |yumush, _, cx| { |
| 792 | - yumush.toggle_builder_password(&password_id, cx) | 765 | + yumush.toggle_builder_password(password_id, cx) |
| 793 | }), | 766 | }), |
| 794 | ); | 767 | ); |
| 795 | 768 | ||
| @@ -797,7 +770,7 @@ impl Yumush { | |||
| 797 | format!("sessions_list_user_{}", user.id), | 770 | format!("sessions_list_user_{}", user.id), |
| 798 | palette, | 771 | palette, |
| 799 | entity_action(entity, move |yumush, window, cx| { | 772 | entity_action(entity, move |yumush, window, cx| { |
| 800 | - yumush.toggle_builder_sessions(&sessions_list_id, window, cx) | 773 | + yumush.toggle_builder_sessions(sessions_list_id, window, cx) |
| 801 | }), | 774 | }), |
| 802 | ) | 775 | ) |
| 803 | .tip("Manage") | 776 | .tip("Manage") |
| @@ -819,7 +792,7 @@ impl Yumush { | |||
| 819 | tone, | 792 | tone, |
| 820 | palette, | 793 | palette, |
| 821 | entity_action(entity, move |yumush, _, cx| { | 794 | entity_action(entity, move |yumush, _, cx| { |
| 822 | - yumush.toggle_builder_rename(&rename_id, cx) | 795 | + yumush.toggle_builder_rename(rename_id, cx) |
| 823 | }), | 796 | }), |
| 824 | ); | 797 | ); |
| 825 | 798 | ||
| @@ -831,7 +804,7 @@ impl Yumush { | |||
| 831 | tone, | 804 | tone, |
| 832 | palette, | 805 | palette, |
| 833 | entity_action(entity, move |yumush, _, cx| { | 806 | entity_action(entity, move |yumush, _, cx| { |
| 834 | - yumush.toggle_builder_timeout(&timeout_id, cx) | 807 | + yumush.toggle_builder_timeout(timeout_id, cx) |
| 835 | }), | 808 | }), |
| 836 | ); | 809 | ); |
| 837 | 810 | ||
| @@ -843,7 +816,7 @@ impl Yumush { | |||
| 843 | tone, | 816 | tone, |
| 844 | palette, | 817 | palette, |
| 845 | entity_action(entity, move |yumush, _, cx| { | 818 | entity_action(entity, move |yumush, _, cx| { |
| 846 | - yumush.toggle_builder_ban(&ban_id, cx) | 819 | + yumush.toggle_builder_ban(ban_id, cx) |
| 847 | }), | 820 | }), |
| 848 | ); | 821 | ); |
| 849 | 822 | ||
| @@ -855,7 +828,7 @@ impl Yumush { | |||
| 855 | palette.danger, | 828 | palette.danger, |
| 856 | palette, | 829 | palette, |
| 857 | entity_action(entity, move |yumush, window, cx| { | 830 | entity_action(entity, move |yumush, window, cx| { |
| 858 | - yumush.clear_builder_profile(&profile_id, window, cx) | 831 | + yumush.clear_builder_profile(profile_id, window, cx) |
| 859 | }), | 832 | }), |
| 860 | ); | 833 | ); |
| 861 | 834 | ||
| @@ -867,7 +840,7 @@ impl Yumush { | |||
| 867 | pending_purge, | 840 | pending_purge, |
| 868 | palette, | 841 | palette, |
| 869 | entity_action(entity, move |yumush, window, cx| { | 842 | entity_action(entity, move |yumush, window, cx| { |
| 870 | - yumush.purge_builder_user(&purge_id, window, cx) | 843 | + yumush.purge_builder_user(purge_id, window, cx) |
| 871 | }), | 844 | }), |
| 872 | ); | 845 | ); |
| 873 | 846 | ||
| @@ -879,7 +852,7 @@ impl Yumush { | |||
| 879 | pending_delete, | 852 | pending_delete, |
| 880 | palette, | 853 | palette, |
| 881 | entity_action(entity, move |yumush, window, cx| { | 854 | entity_action(entity, move |yumush, window, cx| { |
| 882 | - yumush.delete_builder_user(&delete_id, window, cx) | 855 | + yumush.delete_builder_user(delete_id, window, cx) |
| 883 | }), | 856 | }), |
| 884 | ); | 857 | ); |
| 885 | 858 | ||
| @@ -944,11 +917,11 @@ impl Yumush { | |||
| 944 | .children(has_actions.then_some(toggle_button)); | 917 | .children(has_actions.then_some(toggle_button)); |
| 945 | 918 | ||
| 946 | let panel = expanded_sessions.map(|sessions| { | 919 | let panel = expanded_sessions.map(|sessions| { |
| 947 | - let open_id = user.id.as_str(); | 920 | + let open_id = user.id; |
| 948 | - let password_open = self.chat.pending_builder_password.as_deref() == Some(open_id); | 921 | + let password_open = self.chat.pending_builder_password == Some(open_id); |
| 949 | - let rename_open = self.chat.pending_builder_rename.as_deref() == Some(open_id); | 922 | + let rename_open = self.chat.pending_builder_rename == Some(open_id); |
| 950 | - let timeout_open = self.chat.pending_builder_timeout.as_deref() == Some(open_id); | 923 | + let timeout_open = self.chat.pending_builder_timeout == Some(open_id); |
| 951 | - let ban_open = self.chat.pending_builder_ban.as_deref() == Some(open_id); | 924 | + let ban_open = self.chat.pending_builder_ban == Some(open_id); |
| 952 | 925 | ||
| 953 | let account_actions = [ | 926 | let account_actions = [ |
| 954 | manage.then(|| rename_button.into_any_element()), | 927 | manage.then(|| rename_button.into_any_element()), |
| @@ -969,7 +942,7 @@ impl Yumush { | |||
| 969 | let sessions: Vec<AnyElement> = sessions | 942 | let sessions: Vec<AnyElement> = sessions |
| 970 | .iter() | 943 | .iter() |
| 971 | .map(|session| { | 944 | .map(|session| { |
| 972 | - self.builder_session_row(&user.id, session, entity, palette) | 945 | + self.builder_session_row(user.id, session, entity, palette) |
| 973 | .into_any_element() | 946 | .into_any_element() |
| 974 | }) | 947 | }) |
| 975 | .collect(); | 948 | .collect(); |
| @@ -989,16 +962,16 @@ impl Yumush { | |||
| 989 | account_actions.into_iter().flatten().collect(), | 962 | account_actions.into_iter().flatten().collect(), |
| 990 | )) | 963 | )) |
| 991 | .children( | 964 | .children( |
| 992 | - password_open.then(|| self.builder_password_row(&user.id, entity, palette)), | 965 | + password_open.then(|| self.builder_password_row(user.id, entity, palette)), |
| 993 | ) | 966 | ) |
| 994 | - .children(rename_open.then(|| self.builder_rename_row(&user.id, entity, palette))) | 967 | + .children(rename_open.then(|| self.builder_rename_row(user.id, entity, palette))) |
| 995 | .children(action_group( | 968 | .children(action_group( |
| 996 | "Moderation", | 969 | "Moderation", |
| 997 | palette, | 970 | palette, |
| 998 | moderation_actions.into_iter().flatten().collect(), | 971 | moderation_actions.into_iter().flatten().collect(), |
| 999 | )) | 972 | )) |
| 1000 | - .children(timeout_open.then(|| self.builder_timeout_row(&user.id, entity, palette))) | 973 | + .children(timeout_open.then(|| self.builder_timeout_row(user.id, entity, palette))) |
| 1001 | - .children(ban_open.then(|| self.builder_ban_row(&user.id, entity, palette))) | 974 | + .children(ban_open.then(|| self.builder_ban_row(user.id, entity, palette))) |
| 1002 | .children(action_group( | 975 | .children(action_group( |
| 1003 | "Danger", | 976 | "Danger", |
| 1004 | palette, | 977 | palette, |
crates/client/src/gui/builder/voice.rsmodified+13 -14
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::future::Future; | 2 | use std::future::Future; |
| 2 | 3 | ||
| 3 | use common::{ | 4 | use common::{ |
| @@ -50,12 +51,11 @@ impl Yumush { | |||
| 50 | 51 | ||
| 51 | pub(super) fn set_server_mute( | 52 | pub(super) fn set_server_mute( |
| 52 | &mut self, | 53 | &mut self, |
| 53 | - user_id: &str, | 54 | + user_id: Id, |
| 54 | muted: bool, | 55 | muted: bool, |
| 55 | window: &mut Window, | 56 | window: &mut Window, |
| 56 | cx: &mut Context<Self>, | 57 | cx: &mut Context<Self>, |
| 57 | ) { | 58 | ) { |
| 58 | - let user_id = user_id.to_string(); | ||
| 59 | self.voice_action(window, cx, move |network| async move { | 59 | self.voice_action(window, cx, move |network| async move { |
| 60 | network.call(ServerMute { user_id, muted }).await | 60 | network.call(ServerMute { user_id, muted }).await |
| 61 | }); | 61 | }); |
| @@ -63,11 +63,10 @@ impl Yumush { | |||
| 63 | 63 | ||
| 64 | pub(super) fn kick_from_voice( | 64 | pub(super) fn kick_from_voice( |
| 65 | &mut self, | 65 | &mut self, |
| 66 | - user_id: &str, | 66 | + user_id: Id, |
| 67 | window: &mut Window, | 67 | window: &mut Window, |
| 68 | cx: &mut Context<Self>, | 68 | cx: &mut Context<Self>, |
| 69 | ) { | 69 | ) { |
| 70 | - let user_id = user_id.to_string(); | ||
| 71 | self.voice_action(window, cx, move |network| async move { | 70 | self.voice_action(window, cx, move |network| async move { |
| 72 | network.call(KickFromVoice { user_id }).await | 71 | network.call(KickFromVoice { user_id }).await |
| 73 | }); | 72 | }); |
| @@ -95,7 +94,7 @@ impl Yumush { | |||
| 95 | entity: &Entity<Self>, | 94 | entity: &Entity<Self>, |
| 96 | palette: Palette, | 95 | palette: Palette, |
| 97 | ) -> Div { | 96 | ) -> Div { |
| 98 | - let id = room.community_id.clone(); | 97 | + let id = room.community_id; |
| 99 | let voice = self | 98 | let voice = self |
| 100 | .chat | 99 | .chat |
| 101 | .builder_communities | 100 | .builder_communities |
| @@ -103,8 +102,8 @@ impl Yumush { | |||
| 103 | .find(|summary| summary.community.id == id) | 102 | .find(|summary| summary.community.id == id) |
| 104 | .map(|summary| summary.community.voice_enabled); | 103 | .map(|summary| summary.community.voice_enabled); |
| 105 | 104 | ||
| 106 | - let joined = self.chat.in_voice(&id); | 105 | + let joined = self.chat.in_voice(id); |
| 107 | - let join_id = id.clone(); | 106 | + let join_id = id; |
| 108 | let mut actions = | 107 | let mut actions = |
| 109 | vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()]; | 108 | vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()]; |
| 110 | if !joined { | 109 | if !joined { |
| @@ -116,7 +115,7 @@ impl Yumush { | |||
| 116 | palette.ok, | 115 | palette.ok, |
| 117 | palette, | 116 | palette, |
| 118 | entity_action(entity, move |yumush, window, cx| { | 117 | entity_action(entity, move |yumush, window, cx| { |
| 119 | - yumush.jump_to(join_id.clone(), true, window, cx) | 118 | + yumush.jump_to(join_id, true, window, cx) |
| 120 | }), | 119 | }), |
| 121 | ) | 120 | ) |
| 122 | .into_any_element(), | 121 | .into_any_element(), |
| @@ -135,7 +134,7 @@ impl Yumush { | |||
| 135 | palette.muted, | 134 | palette.muted, |
| 136 | palette, | 135 | palette, |
| 137 | entity_action(entity, move |yumush, window, cx| { | 136 | entity_action(entity, move |yumush, window, cx| { |
| 138 | - yumush.set_builder_community_voice(&id, !enabled, window, cx) | 137 | + yumush.set_builder_community_voice(id, !enabled, window, cx) |
| 139 | }), | 138 | }), |
| 140 | ) | 139 | ) |
| 141 | .into_any_element(), | 140 | .into_any_element(), |
| @@ -169,9 +168,9 @@ impl Yumush { | |||
| 169 | entity: &Entity<Self>, | 168 | entity: &Entity<Self>, |
| 170 | palette: Palette, | 169 | palette: Palette, |
| 171 | ) -> Div { | 170 | ) -> Div { |
| 172 | - let id = user.id.clone(); | 171 | + let id = user.id; |
| 173 | - let mute_id = id.clone(); | 172 | + let mute_id = id; |
| 174 | - let kick_id = id.clone(); | 173 | + let kick_id = id; |
| 175 | 174 | ||
| 176 | div() | 175 | div() |
| 177 | .min_h(px(44.)) | 176 | .min_h(px(44.)) |
| @@ -219,7 +218,7 @@ impl Yumush { | |||
| 219 | palette.muted, | 218 | palette.muted, |
| 220 | palette, | 219 | palette, |
| 221 | entity_action(entity, move |yumush, window, cx| { | 220 | entity_action(entity, move |yumush, window, cx| { |
| 222 | - yumush.set_server_mute(&mute_id, !muted, window, cx) | 221 | + yumush.set_server_mute(mute_id, !muted, window, cx) |
| 223 | }), | 222 | }), |
| 224 | )) | 223 | )) |
| 225 | .child(icon_button( | 224 | .child(icon_button( |
| @@ -229,7 +228,7 @@ impl Yumush { | |||
| 229 | palette.danger, | 228 | palette.danger, |
| 230 | palette, | 229 | palette, |
| 231 | entity_action(entity, move |yumush, window, cx| { | 230 | entity_action(entity, move |yumush, window, cx| { |
| 232 | - yumush.kick_from_voice(&kick_id, window, cx) | 231 | + yumush.kick_from_voice(kick_id, window, cx) |
| 233 | }), | 232 | }), |
| 234 | )) | 233 | )) |
| 235 | } | 234 | } |
crates/client/src/gui/camera_view.rsmodified+18 -20
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::sync::Arc; | 2 | use std::sync::Arc; |
| 2 | 3 | ||
| 3 | use common::share::{Fps, Kind, Quality, Resolution}; | 4 | use common::share::{Fps, Kind, Quality, Resolution}; |
| @@ -27,17 +28,17 @@ pub(super) struct CameraTile { | |||
| 27 | } | 28 | } |
| 28 | 29 | ||
| 29 | impl Yumush { | 30 | impl Yumush { |
| 30 | - fn camera_users(&self) -> Vec<String> { | 31 | + fn camera_users(&self) -> Vec<Id> { |
| 31 | let Some(community_id) = self.chat.voice_community() else { | 32 | let Some(community_id) = self.chat.voice_community() else { |
| 32 | return Vec::new(); | 33 | return Vec::new(); |
| 33 | }; | 34 | }; |
| 34 | self.chat | 35 | self.chat |
| 35 | .shares | 36 | .shares |
| 36 | - .get(community_id) | 37 | + .get(&community_id) |
| 37 | .into_iter() | 38 | .into_iter() |
| 38 | .flatten() | 39 | .flatten() |
| 39 | .filter(|share| share.kind == Kind::Camera) | 40 | .filter(|share| share.kind == Kind::Camera) |
| 40 | - .map(|share| share.user_id.clone()) | 41 | + .map(|share| share.user_id) |
| 41 | .collect() | 42 | .collect() |
| 42 | } | 43 | } |
| 43 | 44 | ||
| @@ -46,35 +47,34 @@ impl Yumush { | |||
| 46 | let viewing = self.viewing_camera(); | 47 | let viewing = self.viewing_camera(); |
| 47 | let mut changed = false; | 48 | let mut changed = false; |
| 48 | 49 | ||
| 49 | - for user_id in &wanted { | 50 | + for &user_id in &wanted { |
| 50 | - if self.chat.cameras.contains_key(user_id) { | 51 | + if self.chat.cameras.contains_key(&user_id) { |
| 51 | continue; | 52 | continue; |
| 52 | } | 53 | } |
| 53 | self.chat.cameras.insert( | 54 | self.chat.cameras.insert( |
| 54 | - user_id.clone(), | 55 | + user_id, |
| 55 | CameraTile { | 56 | CameraTile { |
| 56 | generation: None, | 57 | generation: None, |
| 57 | frame: None, | 58 | frame: None, |
| 58 | }, | 59 | }, |
| 59 | ); | 60 | ); |
| 60 | let network = self.network.clone(); | 61 | let network = self.network.clone(); |
| 61 | - let user_id = user_id.clone(); | ||
| 62 | let volume = self.settings.share.volume; | 62 | let volume = self.settings.share.volume; |
| 63 | let choice = self.settings.voice.choice.clone(); | 63 | let choice = self.settings.voice.choice.clone(); |
| 64 | spawn_warn(cx, "camera watch", async move { | 64 | spawn_warn(cx, "camera watch", async move { |
| 65 | network | 65 | network |
| 66 | - .watch_share(&user_id, Kind::Camera, CAMERA_TILE, volume, choice) | 66 | + .watch_share(user_id, Kind::Camera, CAMERA_TILE, volume, choice) |
| 67 | .await | 67 | .await |
| 68 | }); | 68 | }); |
| 69 | changed = true; | 69 | changed = true; |
| 70 | } | 70 | } |
| 71 | 71 | ||
| 72 | - let gone: Vec<String> = self | 72 | + let gone: Vec<Id> = self |
| 73 | .chat | 73 | .chat |
| 74 | .cameras | 74 | .cameras |
| 75 | .keys() | 75 | .keys() |
| 76 | - .filter(|user_id| !wanted.contains(*user_id)) | 76 | + .filter(|user_id| !wanted.contains(user_id)) |
| 77 | - .cloned() | 77 | + .copied() |
| 78 | .collect(); | 78 | .collect(); |
| 79 | for user_id in gone { | 79 | for user_id in gone { |
| 80 | if let Some(frame) = self | 80 | if let Some(frame) = self |
| @@ -85,10 +85,10 @@ impl Yumush { | |||
| 85 | { | 85 | { |
| 86 | cx.drop_image(frame, None); | 86 | cx.drop_image(frame, None); |
| 87 | } | 87 | } |
| 88 | - if viewing.as_deref() != Some(user_id.as_str()) { | 88 | + if viewing != Some(user_id) { |
| 89 | let network = self.network.clone(); | 89 | let network = self.network.clone(); |
| 90 | cx.spawn(async move |_, _| { | 90 | cx.spawn(async move |_, _| { |
| 91 | - let _ = network.unwatch_share(&user_id, Kind::Camera).await; | 91 | + let _ = network.unwatch_share(user_id, Kind::Camera).await; |
| 92 | }) | 92 | }) |
| 93 | .detach(); | 93 | .detach(); |
| 94 | } | 94 | } |
| @@ -96,7 +96,7 @@ impl Yumush { | |||
| 96 | } | 96 | } |
| 97 | 97 | ||
| 98 | for (user_id, tile) in self.chat.cameras.iter_mut() { | 98 | for (user_id, tile) in self.chat.cameras.iter_mut() { |
| 99 | - let Some(frame) = self.network.share_frame(user_id, Kind::Camera) else { | 99 | + let Some(frame) = self.network.share_frame(*user_id, Kind::Camera) else { |
| 100 | continue; | 100 | continue; |
| 101 | }; | 101 | }; |
| 102 | if tile.generation == Some(frame.generation) { | 102 | if tile.generation == Some(frame.generation) { |
| @@ -146,9 +146,9 @@ impl Yumush { | |||
| 146 | .map(|(user_id, tile)| { | 146 | .map(|(user_id, tile)| { |
| 147 | let name = self | 147 | let name = self |
| 148 | .chat | 148 | .chat |
| 149 | - .author(user_id) | 149 | + .author(*user_id) |
| 150 | .map_or("Someone", |user| user.username.as_str()); | 150 | .map_or("Someone", |user| user.username.as_str()); |
| 151 | - camera_tile(entity, user_id, name, tile, palette) | 151 | + camera_tile(entity, *user_id, name, tile, palette) |
| 152 | }) | 152 | }) |
| 153 | .collect(); | 153 | .collect(); |
| 154 | 154 | ||
| @@ -208,18 +208,16 @@ pub(super) fn camera_toggle( | |||
| 208 | 208 | ||
| 209 | fn camera_tile( | 209 | fn camera_tile( |
| 210 | entity: &Entity<Yumush>, | 210 | entity: &Entity<Yumush>, |
| 211 | - user_id: &str, | 211 | + user_id: Id, |
| 212 | name: &str, | 212 | name: &str, |
| 213 | tile: &CameraTile, | 213 | tile: &CameraTile, |
| 214 | palette: Palette, | 214 | palette: Palette, |
| 215 | ) -> impl IntoElement { | 215 | ) -> impl IntoElement { |
| 216 | let entity = entity.clone(); | 216 | let entity = entity.clone(); |
| 217 | - let id = user_id.to_string(); | ||
| 218 | 217 | ||
| 219 | clickable(format!("camera_{user_id}"), palette, move |window, cx| { | 218 | clickable(format!("camera_{user_id}"), palette, move |window, cx| { |
| 220 | - let id = id.clone(); | ||
| 221 | entity.update(cx, |yumush, cx| { | 219 | entity.update(cx, |yumush, cx| { |
| 222 | - yumush.toggle_viewer(id, Kind::Camera, window, cx) | 220 | + yumush.toggle_viewer(user_id, Kind::Camera, window, cx) |
| 223 | }); | 221 | }); |
| 224 | }) | 222 | }) |
| 225 | .tip("Watch") | 223 | .tip("Watch") |
crates/client/src/gui/chat.rsmodified+227 -274
| @@ -16,9 +16,9 @@ use crate::gui::{ | |||
| 16 | clickable, community_name, | 16 | clickable, community_name, |
| 17 | community_settings::{BanSort, LogSort}, | 17 | community_settings::{BanSort, LogSort}, |
| 18 | composer::{self, Composer}, | 18 | composer::{self, Composer}, |
| 19 | - entity_action, hoverable, id_time, | 19 | + entity_action, hoverable, |
| 20 | media_view::{self, Media}, | 20 | media_view::{self, Media}, |
| 21 | - message_actions, new_input, notify_error, palette, poll, pop_in, presence_avatar, | 21 | + message_actions, millis_time, new_input, notify_error, palette, poll, pop_in, presence_avatar, |
| 22 | primary_button, | 22 | primary_button, |
| 23 | profile::profile_popover, | 23 | profile::profile_popover, |
| 24 | rank_tag, | 24 | rank_tag, |
| @@ -42,9 +42,9 @@ use common::{ | |||
| 42 | event::Event, | 42 | event::Event, |
| 43 | model::{ | 43 | model::{ |
| 44 | Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community, | 44 | Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community, |
| 45 | - CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, | 45 | + CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Id, Invitation, |
| 46 | - LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, | 46 | + InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, |
| 47 | - ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, | 47 | + ReportStatus, ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, |
| 48 | }, | 48 | }, |
| 49 | permission, | 49 | permission, |
| 50 | share::{Kind, Share}, | 50 | share::{Kind, Share}, |
| @@ -87,7 +87,7 @@ pub enum DeleteStep { | |||
| 87 | pub enum VoiceState { | 87 | pub enum VoiceState { |
| 88 | Off, | 88 | Off, |
| 89 | In { | 89 | In { |
| 90 | - community_id: String, | 90 | + community_id: Id, |
| 91 | muted: bool, | 91 | muted: bool, |
| 92 | deafened: bool, | 92 | deafened: bool, |
| 93 | }, | 93 | }, |
| @@ -111,8 +111,8 @@ impl History { | |||
| 111 | 111 | ||
| 112 | #[derive(Debug, Clone, PartialEq, Eq)] | 112 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 113 | pub enum ReportTarget { | 113 | pub enum ReportTarget { |
| 114 | - Message(String), | 114 | + Message(Id), |
| 115 | - User(String), | 115 | + User(Id), |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 118 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -124,17 +124,17 @@ pub enum CardMenu { | |||
| 124 | 124 | ||
| 125 | pub struct Chat { | 125 | pub struct Chat { |
| 126 | pub(super) communities: Vec<Community>, | 126 | pub(super) communities: Vec<Community>, |
| 127 | - pub(super) selected_community_id: Option<String>, | 127 | + pub(super) selected_community_id: Option<Id>, |
| 128 | pub(super) opened: Option<Community>, | 128 | pub(super) opened: Option<Community>, |
| 129 | pub(super) ghost: bool, | 129 | pub(super) ghost: bool, |
| 130 | members: Vec<Member>, | 130 | members: Vec<Member>, |
| 131 | pub(super) messages: Vec<Message>, | 131 | pub(super) messages: Vec<Message>, |
| 132 | pub(super) pins: Vec<Message>, | 132 | pub(super) pins: Vec<Message>, |
| 133 | history: History, | 133 | history: History, |
| 134 | - pub(super) unread: HashMap<String, Unread>, | 134 | + pub(super) unread: HashMap<Id, Unread>, |
| 135 | - pub(super) unread_anchor: Option<(String, u32)>, | 135 | + pub(super) unread_anchor: Option<(Id, u32)>, |
| 136 | unseen: u32, | 136 | unseen: u32, |
| 137 | - pub(super) muted: HashSet<String>, | 137 | + pub(super) muted: HashSet<Id>, |
| 138 | pub(super) message_input: Entity<InputState>, | 138 | pub(super) message_input: Entity<InputState>, |
| 139 | pub(super) search_input: Entity<InputState>, | 139 | pub(super) search_input: Entity<InputState>, |
| 140 | pub(super) community_search: Entity<InputState>, | 140 | pub(super) community_search: Entity<InputState>, |
| @@ -144,23 +144,23 @@ pub struct Chat { | |||
| 144 | pub(super) tab: SidebarTab, | 144 | pub(super) tab: SidebarTab, |
| 145 | pub(super) sidebar_collapsed: bool, | 145 | pub(super) sidebar_collapsed: bool, |
| 146 | pub(super) composer: Composer, | 146 | pub(super) composer: Composer, |
| 147 | - pub(super) drafts: HashMap<String, String>, | 147 | + pub(super) drafts: HashMap<Id, String>, |
| 148 | pub(super) poll_question: Entity<InputState>, | 148 | pub(super) poll_question: Entity<InputState>, |
| 149 | pub(super) poll_options: Vec<Entity<InputState>>, | 149 | pub(super) poll_options: Vec<Entity<InputState>>, |
| 150 | pub(super) poll_multiple: bool, | 150 | pub(super) poll_multiple: bool, |
| 151 | pub(super) poll_expanded: bool, | 151 | pub(super) poll_expanded: bool, |
| 152 | scroll: ScrollHandle, | 152 | scroll: ScrollHandle, |
| 153 | - pub(super) jump: Option<String>, | 153 | + pub(super) jump: Option<Id>, |
| 154 | - highlight: Option<(String, Instant)>, | 154 | + highlight: Option<(Id, Instant)>, |
| 155 | pub(super) view: View, | 155 | pub(super) view: View, |
| 156 | pub(super) username_input: Entity<InputState>, | 156 | pub(super) username_input: Entity<InputState>, |
| 157 | pub(super) community_name_input: Entity<InputState>, | 157 | pub(super) community_name_input: Entity<InputState>, |
| 158 | pub(super) status_input: Entity<InputState>, | 158 | pub(super) status_input: Entity<InputState>, |
| 159 | - pub(super) avatars: HashMap<String, Arc<Image>>, | 159 | + pub(super) avatars: HashMap<Id, Arc<Image>>, |
| 160 | - pub(super) hues: HashMap<String, f32>, | 160 | + pub(super) hues: HashMap<Id, f32>, |
| 161 | - pub(super) avatar_requests: HashSet<String>, | 161 | + pub(super) avatar_requests: HashSet<Id>, |
| 162 | - pub(super) users: HashMap<String, User>, | 162 | + pub(super) users: HashMap<Id, User>, |
| 163 | - user_requests: HashSet<String>, | 163 | + user_requests: HashSet<Id>, |
| 164 | pub(super) delete_step: DeleteStep, | 164 | pub(super) delete_step: DeleteStep, |
| 165 | pub(super) bans: Vec<Ban>, | 165 | pub(super) bans: Vec<Ban>, |
| 166 | pub(super) ban_search: Entity<InputState>, | 166 | pub(super) ban_search: Entity<InputState>, |
| @@ -170,16 +170,16 @@ pub struct Chat { | |||
| 170 | pub(super) log_sort: LogSort, | 170 | pub(super) log_sort: LogSort, |
| 171 | pub(super) friends: Friends, | 171 | pub(super) friends: Friends, |
| 172 | pub(super) invitations: Vec<Invitation>, | 172 | pub(super) invitations: Vec<Invitation>, |
| 173 | - pub(super) pending_user_delete: Option<String>, | 173 | + pub(super) pending_user_delete: Option<Id>, |
| 174 | pub(super) card_menu: CardMenu, | 174 | pub(super) card_menu: CardMenu, |
| 175 | - pub(super) presences: HashMap<String, Presence>, | 175 | + pub(super) presences: HashMap<Id, Presence>, |
| 176 | pub(super) slowed_until: Option<u64>, | 176 | pub(super) slowed_until: Option<u64>, |
| 177 | - pub(super) pending_builder_delete: Option<String>, | 177 | + pub(super) pending_builder_delete: Option<Id>, |
| 178 | pub(super) builder_users: Vec<Account>, | 178 | pub(super) builder_users: Vec<Account>, |
| 179 | - pub(super) pending_builder_password: Option<String>, | 179 | + pub(super) pending_builder_password: Option<Id>, |
| 180 | pub(super) builder_password: Entity<InputState>, | 180 | pub(super) builder_password: Entity<InputState>, |
| 181 | - pub(super) builder_sessions: Option<(String, Vec<SessionInfo>)>, | 181 | + pub(super) builder_sessions: Option<(Id, Vec<SessionInfo>)>, |
| 182 | - pub(super) pending_builder_rename: Option<String>, | 182 | + pub(super) pending_builder_rename: Option<Id>, |
| 183 | pub(super) builder_rename: Entity<InputState>, | 183 | pub(super) builder_rename: Entity<InputState>, |
| 184 | pub(super) server_name: Entity<InputState>, | 184 | pub(super) server_name: Entity<InputState>, |
| 185 | pub(super) server_limit: Entity<InputState>, | 185 | pub(super) server_limit: Entity<InputState>, |
| @@ -195,9 +195,9 @@ pub struct Chat { | |||
| 195 | pub(super) server_logins_per_minute: Entity<InputState>, | 195 | pub(super) server_logins_per_minute: Entity<InputState>, |
| 196 | pub(super) server_registration_open: bool, | 196 | pub(super) server_registration_open: bool, |
| 197 | pub(super) server_maintenance: bool, | 197 | pub(super) server_maintenance: bool, |
| 198 | - pub(super) pending_builder_timeout: Option<String>, | 198 | + pub(super) pending_builder_timeout: Option<Id>, |
| 199 | pub(super) builder_timeout: Entity<InputState>, | 199 | pub(super) builder_timeout: Entity<InputState>, |
| 200 | - pub(super) pending_builder_ban: Option<String>, | 200 | + pub(super) pending_builder_ban: Option<Id>, |
| 201 | pub(super) builder_ban_reason: Entity<InputState>, | 201 | pub(super) builder_ban_reason: Entity<InputState>, |
| 202 | pub(super) builder_ban_scope: BanScope, | 202 | pub(super) builder_ban_scope: BanScope, |
| 203 | pub(super) builder_bans: Vec<ServerBan>, | 203 | pub(super) builder_bans: Vec<ServerBan>, |
| @@ -223,7 +223,7 @@ pub struct Chat { | |||
| 223 | pub(super) open_reports: usize, | 223 | pub(super) open_reports: usize, |
| 224 | pub(super) report: Option<ReportTarget>, | 224 | pub(super) report: Option<ReportTarget>, |
| 225 | pub(super) report_reason: Entity<InputState>, | 225 | pub(super) report_reason: Entity<InputState>, |
| 226 | - pub(super) pending_community_delete: Option<String>, | 226 | + pub(super) pending_community_delete: Option<Id>, |
| 227 | pub(super) builder_message_text: Entity<InputState>, | 227 | pub(super) builder_message_text: Entity<InputState>, |
| 228 | pub(super) builder_message_user: Entity<InputState>, | 228 | pub(super) builder_message_user: Entity<InputState>, |
| 229 | pub(super) builder_message_community: Entity<InputState>, | 229 | pub(super) builder_message_community: Entity<InputState>, |
| @@ -235,30 +235,30 @@ pub struct Chat { | |||
| 235 | pub(super) builder_usage_users: Vec<Usage>, | 235 | pub(super) builder_usage_users: Vec<Usage>, |
| 236 | pub(super) builder_usage_communities: Vec<CommunityUsage>, | 236 | pub(super) builder_usage_communities: Vec<CommunityUsage>, |
| 237 | pub(super) builder_attachments: Vec<AttachmentInfo>, | 237 | pub(super) builder_attachments: Vec<AttachmentInfo>, |
| 238 | - pub(super) pending_attachment_delete: Option<String>, | 238 | + pub(super) pending_attachment_delete: Option<Id>, |
| 239 | - pub(super) pending_message_delete: Option<String>, | 239 | + pub(super) pending_message_delete: Option<Id>, |
| 240 | - pub(super) pending_builder_purge: Option<String>, | 240 | + pub(super) pending_builder_purge: Option<Id>, |
| 241 | pub(super) transfer: Option<Transfer>, | 241 | pub(super) transfer: Option<Transfer>, |
| 242 | - pub(super) voice: HashMap<String, Vec<String>>, | 242 | + pub(super) voice: HashMap<Id, Vec<Id>>, |
| 243 | pub(super) voice_state: VoiceState, | 243 | pub(super) voice_state: VoiceState, |
| 244 | pub(super) waves: Waves, | 244 | pub(super) waves: Waves, |
| 245 | - pub(super) server_muted: HashSet<String>, | 245 | + pub(super) server_muted: HashSet<Id>, |
| 246 | pub(super) builder_voice_rooms: Vec<VoiceRoom>, | 246 | pub(super) builder_voice_rooms: Vec<VoiceRoom>, |
| 247 | pub(super) voice_task: Option<Task<()>>, | 247 | pub(super) voice_task: Option<Task<()>>, |
| 248 | pub(super) user_volume: Option<UserVolume>, | 248 | pub(super) user_volume: Option<UserVolume>, |
| 249 | pub(super) voice_samples: VecDeque<VoiceSample>, | 249 | pub(super) voice_samples: VecDeque<VoiceSample>, |
| 250 | pub(super) share_sample: ShareSample, | 250 | pub(super) share_sample: ShareSample, |
| 251 | - pub(super) share_loss: HashMap<String, VecDeque<f32>>, | 251 | + pub(super) share_loss: HashMap<Id, VecDeque<f32>>, |
| 252 | pub(super) stats_tab: StatsTab, | 252 | pub(super) stats_tab: StatsTab, |
| 253 | - pub(super) ringing: HashSet<String>, | 253 | + pub(super) ringing: HashSet<Id>, |
| 254 | pub(super) ring_task: Option<Task<()>>, | 254 | pub(super) ring_task: Option<Task<()>>, |
| 255 | pub(super) media: Media, | 255 | pub(super) media: Media, |
| 256 | - pub(super) shares: HashMap<String, Vec<Share>>, | 256 | + pub(super) shares: HashMap<Id, Vec<Share>>, |
| 257 | pub(super) viewer: Option<Viewer>, | 257 | pub(super) viewer: Option<Viewer>, |
| 258 | - pub(super) cameras: BTreeMap<String, CameraTile>, | 258 | + pub(super) cameras: BTreeMap<Id, CameraTile>, |
| 259 | pub(super) camera_task: Option<Task<()>>, | 259 | pub(super) camera_task: Option<Task<()>>, |
| 260 | - pub(super) typing: HashMap<String, HashMap<String, Instant>>, | 260 | + pub(super) typing: HashMap<Id, HashMap<Id, Instant>>, |
| 261 | - pub(super) typing_sent: HashMap<String, Instant>, | 261 | + pub(super) typing_sent: HashMap<Id, Instant>, |
| 262 | } | 262 | } |
| 263 | 263 | ||
| 264 | const RING_LIMIT: usize = 15; | 264 | const RING_LIMIT: usize = 15; |
| @@ -268,7 +268,7 @@ const WAVE_INTERVAL: Duration = Duration::from_millis(33); | |||
| 268 | const DEFAULT_USER_VOLUME: f32 = 100.0; | 268 | const DEFAULT_USER_VOLUME: f32 = 100.0; |
| 269 | 269 | ||
| 270 | pub struct UserVolume { | 270 | pub struct UserVolume { |
| 271 | - pub user_id: String, | 271 | + pub user_id: Id, |
| 272 | pub slider: Entity<SliderState>, | 272 | pub slider: Entity<SliderState>, |
| 273 | _subscription: Subscription, | 273 | _subscription: Subscription, |
| 274 | } | 274 | } |
| @@ -530,18 +530,18 @@ impl Chat { | |||
| 530 | (remaining > 0).then(|| remaining.div_ceil(1000)) | 530 | (remaining > 0).then(|| remaining.div_ceil(1000)) |
| 531 | } | 531 | } |
| 532 | 532 | ||
| 533 | - pub fn apply_event(&mut self, event: Event, me: Option<&str>) { | 533 | + pub fn apply_event(&mut self, event: Event, me: Option<Id>) { |
| 534 | match event { | 534 | match event { |
| 535 | Event::MessageCreated(message) => { | 535 | Event::MessageCreated(message) => { |
| 536 | if let Some(users) = self.typing.get_mut(&message.community_id) { | 536 | if let Some(users) = self.typing.get_mut(&message.community_id) { |
| 537 | users.remove(&message.user_id); | 537 | users.remove(&message.user_id); |
| 538 | } | 538 | } |
| 539 | - if self.is_selected(&message.community_id) { | 539 | + if self.is_selected(message.community_id) { |
| 540 | self.insert_messages([message], me); | 540 | self.insert_messages([message], me); |
| 541 | } | 541 | } |
| 542 | } | 542 | } |
| 543 | Event::MessageUpdated(message) => { | 543 | Event::MessageUpdated(message) => { |
| 544 | - if self.is_selected(&message.community_id) { | 544 | + if self.is_selected(message.community_id) { |
| 545 | self.update_pin(&message); | 545 | self.update_pin(&message); |
| 546 | if let Some(existing) = self | 546 | if let Some(existing) = self |
| 547 | .messages | 547 | .messages |
| @@ -553,8 +553,8 @@ impl Chat { | |||
| 553 | } | 553 | } |
| 554 | } | 554 | } |
| 555 | Event::MessagesDeleted { community_id, ids } => { | 555 | Event::MessagesDeleted { community_id, ids } => { |
| 556 | - if self.is_selected(&community_id) { | 556 | + if self.is_selected(community_id) { |
| 557 | - for id in &ids { | 557 | + for id in ids { |
| 558 | self.forget_message(id); | 558 | self.forget_message(id); |
| 559 | } | 559 | } |
| 560 | } | 560 | } |
| @@ -563,7 +563,7 @@ impl Chat { | |||
| 563 | community_id, | 563 | community_id, |
| 564 | member, | 564 | member, |
| 565 | } => { | 565 | } => { |
| 566 | - if self.is_selected(&community_id) { | 566 | + if self.is_selected(community_id) { |
| 567 | self.insert_member(member); | 567 | self.insert_member(member); |
| 568 | } | 568 | } |
| 569 | } | 569 | } |
| @@ -571,8 +571,8 @@ impl Chat { | |||
| 571 | community_id, | 571 | community_id, |
| 572 | user_id, | 572 | user_id, |
| 573 | } => { | 573 | } => { |
| 574 | - if self.is_selected(&community_id) { | 574 | + if self.is_selected(community_id) { |
| 575 | - self.remove_member(&user_id); | 575 | + self.remove_member(user_id); |
| 576 | } | 576 | } |
| 577 | } | 577 | } |
| 578 | Event::RankChanged { | 578 | Event::RankChanged { |
| @@ -580,8 +580,8 @@ impl Chat { | |||
| 580 | user_id, | 580 | user_id, |
| 581 | rank, | 581 | rank, |
| 582 | } => { | 582 | } => { |
| 583 | - if self.is_selected(&community_id) { | 583 | + if self.is_selected(community_id) { |
| 584 | - self.set_rank(&user_id, rank); | 584 | + self.set_rank(user_id, rank); |
| 585 | } | 585 | } |
| 586 | } | 586 | } |
| 587 | Event::CommunityUpdated(community) | Event::CommunityAdded(community) => { | 587 | Event::CommunityUpdated(community) | Event::CommunityAdded(community) => { |
| @@ -590,10 +590,10 @@ impl Chat { | |||
| 590 | Event::FriendsUpdated(friends) => self.friends = friends, | 590 | Event::FriendsUpdated(friends) => self.friends = friends, |
| 591 | Event::InvitationsUpdated(invitations) => self.invitations = invitations, | 591 | Event::InvitationsUpdated(invitations) => self.invitations = invitations, |
| 592 | Event::CommunityDeleted { community_id } | Event::Removed { community_id, .. } => { | 592 | Event::CommunityDeleted { community_id } | Event::Removed { community_id, .. } => { |
| 593 | - self.remove_community(&community_id) | 593 | + self.remove_community(community_id) |
| 594 | } | 594 | } |
| 595 | Event::UserDeleted { user_id } => { | 595 | Event::UserDeleted { user_id } => { |
| 596 | - self.remove_member(&user_id); | 596 | + self.remove_member(user_id); |
| 597 | self.messages.retain(|message| message.user_id != user_id); | 597 | self.messages.retain(|message| message.user_id != user_id); |
| 598 | } | 598 | } |
| 599 | Event::UserUpdated(user) => self.update_member(&user), | 599 | Event::UserUpdated(user) => self.update_member(&user), |
| @@ -659,8 +659,8 @@ impl Chat { | |||
| 659 | } | 659 | } |
| 660 | } | 660 | } |
| 661 | 661 | ||
| 662 | - pub(super) fn is_selected(&self, community_id: &str) -> bool { | 662 | + pub(super) fn is_selected(&self, community_id: Id) -> bool { |
| 663 | - self.selected_community_id.as_deref() == Some(community_id) | 663 | + self.selected_community_id == Some(community_id) |
| 664 | } | 664 | } |
| 665 | 665 | ||
| 666 | pub fn typing_label(&self) -> Option<String> { | 666 | pub fn typing_label(&self) -> Option<String> { |
| @@ -671,7 +671,7 @@ impl Chat { | |||
| 671 | .iter() | 671 | .iter() |
| 672 | .filter(|(_, at)| at.elapsed() < TYPING_TTL) | 672 | .filter(|(_, at)| at.elapsed() < TYPING_TTL) |
| 673 | .map(|(user_id, _)| { | 673 | .map(|(user_id, _)| { |
| 674 | - self.author(user_id) | 674 | + self.author(*user_id) |
| 675 | .map_or("Someone", |user| user.username.as_str()) | 675 | .map_or("Someone", |user| user.username.as_str()) |
| 676 | }) | 676 | }) |
| 677 | .collect(); | 677 | .collect(); |
| @@ -682,7 +682,7 @@ impl Chat { | |||
| 682 | } | 682 | } |
| 683 | } | 683 | } |
| 684 | 684 | ||
| 685 | - fn select(&mut self, community_id: Option<String>) { | 685 | + fn select(&mut self, community_id: Option<Id>) { |
| 686 | if community_id != self.selected_community_id { | 686 | if community_id != self.selected_community_id { |
| 687 | self.unread_anchor = community_id | 687 | self.unread_anchor = community_id |
| 688 | .as_ref() | 688 | .as_ref() |
| @@ -691,7 +691,6 @@ impl Chat { | |||
| 691 | .and_then(|unread| { | 691 | .and_then(|unread| { |
| 692 | unread | 692 | unread |
| 693 | .last_read | 693 | .last_read |
| 694 | - .clone() | ||
| 695 | .map(|last_read| (last_read, unread.messages)) | 694 | .map(|last_read| (last_read, unread.messages)) |
| 696 | }); | 695 | }); |
| 697 | self.unseen = 0; | 696 | self.unseen = 0; |
| @@ -718,21 +717,21 @@ impl Chat { | |||
| 718 | self.composer = Composer::Compose { reply: None }; | 717 | self.composer = Composer::Compose { reply: None }; |
| 719 | } | 718 | } |
| 720 | 719 | ||
| 721 | - pub fn joined(&self, community_id: &str) -> bool { | 720 | + pub fn joined(&self, community_id: Id) -> bool { |
| 722 | self.communities | 721 | self.communities |
| 723 | .iter() | 722 | .iter() |
| 724 | .any(|community| community.id == community_id) | 723 | .any(|community| community.id == community_id) |
| 725 | } | 724 | } |
| 726 | 725 | ||
| 727 | - fn forget_message(&mut self, message_id: &str) { | 726 | + fn forget_message(&mut self, message_id: Id) { |
| 728 | self.messages.retain(|existing| existing.id != message_id); | 727 | self.messages.retain(|existing| existing.id != message_id); |
| 729 | 728 | ||
| 730 | match &mut self.composer { | 729 | match &mut self.composer { |
| 731 | - Composer::Select { ids } => ids.retain(|id| id != message_id), | 730 | + Composer::Select { ids } => ids.retain(|id| *id != message_id), |
| 732 | - Composer::Compose { reply } if reply.as_deref() == Some(message_id) => { | 731 | + Composer::Compose { reply } if *reply == Some(message_id) => { |
| 733 | self.composer = Composer::Compose { reply: None }; | 732 | self.composer = Composer::Compose { reply: None }; |
| 734 | } | 733 | } |
| 735 | - Composer::Edit { message_id: edited } if edited.as_str() == message_id => { | 734 | + Composer::Edit { message_id: edited } if *edited == message_id => { |
| 736 | self.composer = Composer::Compose { reply: None }; | 735 | self.composer = Composer::Compose { reply: None }; |
| 737 | } | 736 | } |
| 738 | _ => {} | 737 | _ => {} |
| @@ -749,18 +748,18 @@ impl Chat { | |||
| 749 | .find(|community| matches!(community.kind, CommunityKind::Notes)) | 748 | .find(|community| matches!(community.kind, CommunityKind::Notes)) |
| 750 | } | 749 | } |
| 751 | 750 | ||
| 752 | - fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>, me: Option<&str>) { | 751 | + fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>, me: Option<Id>) { |
| 753 | - let newest = self.messages.last().map(|message| message.id.clone()); | 752 | + let newest = self.messages.last().map(|message| message.id); |
| 754 | for message in messages { | 753 | for message in messages { |
| 755 | self.messages.retain(|existing| existing.id != message.id); | 754 | self.messages.retain(|existing| existing.id != message.id); |
| 756 | self.messages.push(message); | 755 | self.messages.push(message); |
| 757 | } | 756 | } |
| 758 | - self.messages.sort_by(|left, right| left.id.cmp(&right.id)); | 757 | + self.messages.sort_by_key(|message| message.id); |
| 759 | - if self.messages.last().map(|message| &message.id) != newest.as_ref() { | 758 | + if self.messages.last().map(|message| message.id) != newest { |
| 760 | let mine = self | 759 | let mine = self |
| 761 | .messages | 760 | .messages |
| 762 | .last() | 761 | .last() |
| 763 | - .is_some_and(|message| Some(message.user_id.as_str()) == me); | 762 | + .is_some_and(|message| Some(message.user_id) == me); |
| 764 | if newest.is_none() { | 763 | if newest.is_none() { |
| 765 | match self.unread_divider(me) { | 764 | match self.unread_divider(me) { |
| 766 | Some(index) => self.scroll_to_index(index), | 765 | Some(index) => self.scroll_to_index(index), |
| @@ -821,53 +820,49 @@ impl Chat { | |||
| 821 | } | 820 | } |
| 822 | } | 821 | } |
| 823 | 822 | ||
| 824 | - fn unread_divider(&self, me: Option<&str>) -> Option<usize> { | 823 | + fn unread_divider(&self, me: Option<Id>) -> Option<usize> { |
| 825 | - let (anchor, _) = self.unread_anchor.as_ref()?; | 824 | + let (anchor, _) = self.unread_anchor?; |
| 826 | if !self.unread_covered() { | 825 | if !self.unread_covered() { |
| 827 | return None; | 826 | return None; |
| 828 | } | 827 | } |
| 829 | self.messages | 828 | self.messages |
| 830 | .iter() | 829 | .iter() |
| 831 | - .position(|message| message.id > *anchor && Some(message.user_id.as_str()) != me) | 830 | + .position(|message| message.id > anchor && Some(message.user_id) != me) |
| 832 | } | 831 | } |
| 833 | 832 | ||
| 834 | - pub(super) fn mark_read(&mut self, community_id: &str, message_id: &str) { | 833 | + pub(super) fn mark_read(&mut self, community_id: Id, message_id: Id) { |
| 835 | - let unread = self | 834 | + let unread = self.unread.entry(community_id).or_insert_with(|| Unread { |
| 836 | - .unread | 835 | + community_id, |
| 837 | - .entry(community_id.to_string()) | 836 | + ..Default::default() |
| 838 | - .or_insert_with(|| Unread { | 837 | + }); |
| 839 | - community_id: community_id.to_string(), | ||
| 840 | - ..Default::default() | ||
| 841 | - }); | ||
| 842 | unread.messages = 0; | 838 | unread.messages = 0; |
| 843 | unread.mentions = 0; | 839 | unread.mentions = 0; |
| 844 | - unread.last_read = Some(message_id.to_string()); | 840 | + unread.last_read = Some(message_id); |
| 845 | } | 841 | } |
| 846 | 842 | ||
| 847 | - fn add_page(&mut self, page: Vec<Message>, me: Option<&str>) { | 843 | + fn add_page(&mut self, page: Vec<Message>, me: Option<Id>) { |
| 848 | self.history = History::of_page(page.len()); | 844 | self.history = History::of_page(page.len()); |
| 849 | self.insert_messages(page, me); | 845 | self.insert_messages(page, me); |
| 850 | } | 846 | } |
| 851 | 847 | ||
| 852 | fn insert_member(&mut self, member: Member) { | 848 | fn insert_member(&mut self, member: Member) { |
| 853 | - self.remove_member(&member.user.id); | 849 | + self.remove_member(member.user.id); |
| 854 | self.members.push(member); | 850 | self.members.push(member); |
| 855 | - self.members | 851 | + self.members.sort_by_key(|member| member.user.id); |
| 856 | - .sort_by(|left, right| left.user.id.cmp(&right.user.id)); | ||
| 857 | } | 852 | } |
| 858 | 853 | ||
| 859 | - pub(super) fn remove_member(&mut self, user_id: &str) { | 854 | + pub(super) fn remove_member(&mut self, user_id: Id) { |
| 860 | if let Some(index) = self | 855 | if let Some(index) = self |
| 861 | .members | 856 | .members |
| 862 | .iter() | 857 | .iter() |
| 863 | .position(|member| member.user.id == user_id) | 858 | .position(|member| member.user.id == user_id) |
| 864 | { | 859 | { |
| 865 | let member = self.members.remove(index); | 860 | let member = self.members.remove(index); |
| 866 | - self.users.insert(member.user.id.clone(), member.user); | 861 | + self.users.insert(member.user.id, member.user); |
| 867 | } | 862 | } |
| 868 | } | 863 | } |
| 869 | 864 | ||
| 870 | - fn set_rank(&mut self, user_id: &str, rank: Rank) { | 865 | + fn set_rank(&mut self, user_id: Id, rank: Rank) { |
| 871 | if let Some(member) = self | 866 | if let Some(member) = self |
| 872 | .members | 867 | .members |
| 873 | .iter_mut() | 868 | .iter_mut() |
| @@ -877,7 +872,7 @@ impl Chat { | |||
| 877 | } | 872 | } |
| 878 | } | 873 | } |
| 879 | 874 | ||
| 880 | - fn community(&self, community_id: &str) -> Option<&Community> { | 875 | + fn community(&self, community_id: Id) -> Option<&Community> { |
| 881 | self.communities | 876 | self.communities |
| 882 | .iter() | 877 | .iter() |
| 883 | .chain(self.opened.as_ref()) | 878 | .chain(self.opened.as_ref()) |
| @@ -885,34 +880,33 @@ impl Chat { | |||
| 885 | } | 880 | } |
| 886 | 881 | ||
| 887 | pub fn selected_community(&self) -> Option<&Community> { | 882 | pub fn selected_community(&self) -> Option<&Community> { |
| 888 | - self.community(self.selected_community_id.as_deref()?) | 883 | + self.community(self.selected_community_id?) |
| 889 | } | 884 | } |
| 890 | 885 | ||
| 891 | - fn member_entry(&self, user_id: &str) -> Option<&Member> { | 886 | + fn member_entry(&self, user_id: Id) -> Option<&Member> { |
| 892 | self.members.iter().find(|member| member.user.id == user_id) | 887 | self.members.iter().find(|member| member.user.id == user_id) |
| 893 | } | 888 | } |
| 894 | 889 | ||
| 895 | - pub fn member(&self, user_id: &str) -> Option<&User> { | 890 | + pub fn member(&self, user_id: Id) -> Option<&User> { |
| 896 | self.member_entry(user_id).map(|member| &member.user) | 891 | self.member_entry(user_id).map(|member| &member.user) |
| 897 | } | 892 | } |
| 898 | 893 | ||
| 899 | - pub fn author(&self, user_id: &str) -> Option<&User> { | 894 | + pub fn author(&self, user_id: Id) -> Option<&User> { |
| 900 | - self.member(user_id).or_else(|| self.users.get(user_id)) | 895 | + self.member(user_id).or_else(|| self.users.get(&user_id)) |
| 901 | } | 896 | } |
| 902 | 897 | ||
| 903 | - fn missing_authors(&self) -> Vec<String> { | 898 | + fn missing_authors(&self) -> Vec<Id> { |
| 904 | if self.members.is_empty() { | 899 | if self.members.is_empty() { |
| 905 | return vec![]; | 900 | return vec![]; |
| 906 | } | 901 | } |
| 907 | - let mut missing: Vec<String> = self | 902 | + let mut missing: Vec<Id> = self |
| 908 | .messages | 903 | .messages |
| 909 | .iter() | 904 | .iter() |
| 910 | .flat_map(|message| { | 905 | .flat_map(|message| { |
| 911 | - std::iter::once(&message.user_id) | 906 | + std::iter::once(message.user_id) |
| 912 | - .chain(message.reply.as_ref().map(|quote| "e.user_id)) | 907 | + .chain(message.reply.as_ref().map(|quote| quote.user_id)) |
| 913 | }) | 908 | }) |
| 914 | - .filter(|id| self.author(id).is_none() && !self.user_requests.contains(*id)) | 909 | + .filter(|id| self.author(*id).is_none() && !self.user_requests.contains(id)) |
| 915 | - .cloned() | ||
| 916 | .collect(); | 910 | .collect(); |
| 917 | missing.sort(); | 911 | missing.sort(); |
| 918 | missing.dedup(); | 912 | missing.dedup(); |
| @@ -920,12 +914,12 @@ impl Chat { | |||
| 920 | } | 914 | } |
| 921 | 915 | ||
| 922 | pub fn rank_of(&self, user: &User) -> Option<Rank> { | 916 | pub fn rank_of(&self, user: &User) -> Option<Rank> { |
| 923 | - let rank = self.member_entry(&user.id).map(|member| member.rank); | 917 | + let rank = self.member_entry(user.id).map(|member| member.rank); |
| 924 | 918 | ||
| 925 | permission::effective_rank(user.role, rank) | 919 | permission::effective_rank(user.role, rank) |
| 926 | } | 920 | } |
| 927 | 921 | ||
| 928 | - pub fn rank_of_id(&self, user_id: &str) -> Option<Rank> { | 922 | + pub fn rank_of_id(&self, user_id: Id) -> Option<Rank> { |
| 929 | self.member(user_id).and_then(|user| self.rank_of(user)) | 923 | self.member(user_id).and_then(|user| self.rank_of(user)) |
| 930 | } | 924 | } |
| 931 | 925 | ||
| @@ -940,14 +934,14 @@ impl Chat { | |||
| 940 | self.pins.retain(|pin| pin.id != message.id); | 934 | self.pins.retain(|pin| pin.id != message.id); |
| 941 | if message.pinned { | 935 | if message.pinned { |
| 942 | self.pins.push(message.clone()); | 936 | self.pins.push(message.clone()); |
| 943 | - self.pins.sort_by(|left, right| right.id.cmp(&left.id)); | 937 | + self.pins.sort_by_key(|pin| std::cmp::Reverse(pin.id)); |
| 944 | } | 938 | } |
| 945 | } | 939 | } |
| 946 | 940 | ||
| 947 | pub fn can_delete(&self, message: &Message, me: &User) -> bool { | 941 | pub fn can_delete(&self, message: &Message, me: &User) -> bool { |
| 948 | permission::can_delete_message( | 942 | permission::can_delete_message( |
| 949 | self.rank_of(me), | 943 | self.rank_of(me), |
| 950 | - self.rank_of_id(&message.user_id), | 944 | + self.rank_of_id(message.user_id), |
| 951 | message.user_id == me.id, | 945 | message.user_id == me.id, |
| 952 | ) | 946 | ) |
| 953 | } | 947 | } |
| @@ -983,15 +977,14 @@ impl Chat { | |||
| 983 | self.communities | 977 | self.communities |
| 984 | .retain(|existing| existing.id != community.id); | 978 | .retain(|existing| existing.id != community.id); |
| 985 | self.communities.push(community); | 979 | self.communities.push(community); |
| 986 | - self.communities | 980 | + self.communities.sort_by_key(|community| community.id); |
| 987 | - .sort_by(|left, right| left.id.cmp(&right.id)); | ||
| 988 | } | 981 | } |
| 989 | 982 | ||
| 990 | - pub(super) fn remove_community(&mut self, community_id: &str) { | 983 | + pub(super) fn remove_community(&mut self, community_id: Id) { |
| 991 | self.communities | 984 | self.communities |
| 992 | .retain(|community| community.id != community_id); | 985 | .retain(|community| community.id != community_id); |
| 993 | - self.unread.remove(community_id); | 986 | + self.unread.remove(&community_id); |
| 994 | - self.voice.remove(community_id); | 987 | + self.voice.remove(&community_id); |
| 995 | if self.in_voice(community_id) { | 988 | if self.in_voice(community_id) { |
| 996 | self.set_voice_off(); | 989 | self.set_voice_off(); |
| 997 | } | 990 | } |
| @@ -1006,7 +999,7 @@ impl Chat { | |||
| 1006 | let selected_present = self | 999 | let selected_present = self |
| 1007 | .communities | 1000 | .communities |
| 1008 | .iter() | 1001 | .iter() |
| 1009 | - .any(|community| self.is_selected(&community.id)); | 1002 | + .any(|community| self.is_selected(community.id)); |
| 1010 | if !selected_present { | 1003 | if !selected_present { |
| 1011 | self.select(None); | 1004 | self.select(None); |
| 1012 | } | 1005 | } |
| @@ -1074,10 +1067,10 @@ impl Chat { | |||
| 1074 | self.set_voice_off(); | 1067 | self.set_voice_off(); |
| 1075 | } | 1068 | } |
| 1076 | 1069 | ||
| 1077 | - pub fn voice_community(&self) -> Option<&str> { | 1070 | + pub fn voice_community(&self) -> Option<Id> { |
| 1078 | match &self.voice_state { | 1071 | match &self.voice_state { |
| 1079 | VoiceState::Off => None, | 1072 | VoiceState::Off => None, |
| 1080 | - VoiceState::In { community_id, .. } => Some(community_id), | 1073 | + VoiceState::In { community_id, .. } => Some(*community_id), |
| 1081 | } | 1074 | } |
| 1082 | } | 1075 | } |
| 1083 | 1076 | ||
| @@ -1085,7 +1078,7 @@ impl Chat { | |||
| 1085 | self.community(self.voice_community()?) | 1078 | self.community(self.voice_community()?) |
| 1086 | } | 1079 | } |
| 1087 | 1080 | ||
| 1088 | - pub fn in_voice(&self, community_id: &str) -> bool { | 1081 | + pub fn in_voice(&self, community_id: Id) -> bool { |
| 1089 | self.voice_community() == Some(community_id) | 1082 | self.voice_community() == Some(community_id) |
| 1090 | } | 1083 | } |
| 1091 | 1084 | ||
| @@ -1098,25 +1091,25 @@ impl Chat { | |||
| 1098 | } | 1091 | } |
| 1099 | } | 1092 | } |
| 1100 | 1093 | ||
| 1101 | - pub fn voice_enabled(&self, community_id: &str) -> bool { | 1094 | + pub fn voice_enabled(&self, community_id: Id) -> bool { |
| 1102 | self.community(community_id) | 1095 | self.community(community_id) |
| 1103 | .is_some_and(|community| community.voice_enabled) | 1096 | .is_some_and(|community| community.voice_enabled) |
| 1104 | } | 1097 | } |
| 1105 | 1098 | ||
| 1106 | - pub fn share_of(&self, community_id: &str, user_id: &str, kind: Kind) -> Option<&Share> { | 1099 | + pub fn share_of(&self, community_id: Id, user_id: Id, kind: Kind) -> Option<&Share> { |
| 1107 | self.shares | 1100 | self.shares |
| 1108 | - .get(community_id)? | 1101 | + .get(&community_id)? |
| 1109 | .iter() | 1102 | .iter() |
| 1110 | .find(|share| share.user_id == user_id && share.kind == kind) | 1103 | .find(|share| share.user_id == user_id && share.kind == kind) |
| 1111 | } | 1104 | } |
| 1112 | 1105 | ||
| 1113 | - pub fn is_sharing(&self, community_id: &str, user_id: &str) -> bool { | 1106 | + pub fn is_sharing(&self, community_id: Id, user_id: Id) -> bool { |
| 1114 | self.share_of(community_id, user_id, Kind::Screen).is_some() | 1107 | self.share_of(community_id, user_id, Kind::Screen).is_some() |
| 1115 | } | 1108 | } |
| 1116 | 1109 | ||
| 1117 | - pub fn voice_ids(&self, community_id: &str) -> &[String] { | 1110 | + pub fn voice_ids(&self, community_id: Id) -> &[Id] { |
| 1118 | self.voice | 1111 | self.voice |
| 1119 | - .get(community_id) | 1112 | + .get(&community_id) |
| 1120 | .map(Vec::as_slice) | 1113 | .map(Vec::as_slice) |
| 1121 | .unwrap_or_default() | 1114 | .unwrap_or_default() |
| 1122 | } | 1115 | } |
| @@ -1134,7 +1127,7 @@ impl Chat { | |||
| 1134 | self.share_loss | 1127 | self.share_loss |
| 1135 | .retain(|user_id, _| sample.watching.iter().any(|(id, _)| id == user_id)); | 1128 | .retain(|user_id, _| sample.watching.iter().any(|(id, _)| id == user_id)); |
| 1136 | for (user_id, stats) in &sample.watching { | 1129 | for (user_id, stats) in &sample.watching { |
| 1137 | - let history = self.share_loss.entry(user_id.clone()).or_default(); | 1130 | + let history = self.share_loss.entry(*user_id).or_default(); |
| 1138 | history.push_back(stats.loss); | 1131 | history.push_back(stats.loss); |
| 1139 | while history.len() > SAMPLE_HISTORY { | 1132 | while history.len() > SAMPLE_HISTORY { |
| 1140 | history.pop_front(); | 1133 | history.pop_front(); |
| @@ -1190,7 +1183,7 @@ pub(super) fn create_community( | |||
| 1190 | struct MembersTrigger { | 1183 | struct MembersTrigger { |
| 1191 | palette: Palette, | 1184 | palette: Palette, |
| 1192 | members: Vec<User>, | 1185 | members: Vec<User>, |
| 1193 | - avatars: HashMap<String, Arc<Image>>, | 1186 | + avatars: HashMap<Id, Arc<Image>>, |
| 1194 | } | 1187 | } |
| 1195 | 1188 | ||
| 1196 | impl Selectable for MembersTrigger { | 1189 | impl Selectable for MembersTrigger { |
| @@ -1341,7 +1334,7 @@ impl Yumush { | |||
| 1341 | .children(self.voice_button(entity, palette)) | 1334 | .children(self.voice_button(entity, palette)) |
| 1342 | .children( | 1335 | .children( |
| 1343 | community | 1336 | community |
| 1344 | - .is_some_and(|community| self.chat.joined(&community.id)) | 1337 | + .is_some_and(|community| self.chat.joined(community.id)) |
| 1345 | .then(|| message_actions::search_popover(&self.chat, entity, palette)), | 1338 | .then(|| message_actions::search_popover(&self.chat, entity, palette)), |
| 1346 | ) | 1339 | ) |
| 1347 | .children( | 1340 | .children( |
| @@ -1363,7 +1356,7 @@ impl Yumush { | |||
| 1363 | } | 1356 | } |
| 1364 | 1357 | ||
| 1365 | fn unread_bar(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { | 1358 | fn unread_bar(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { |
| 1366 | - let (anchor, count) = self.chat.unread_anchor.clone()?; | 1359 | + let (anchor, count) = self.chat.unread_anchor?; |
| 1367 | if self.chat.unread_covered() { | 1360 | if self.chat.unread_covered() { |
| 1368 | return None; | 1361 | return None; |
| 1369 | } | 1362 | } |
| @@ -1379,7 +1372,7 @@ impl Yumush { | |||
| 1379 | "jump_unread", | 1372 | "jump_unread", |
| 1380 | palette, | 1373 | palette, |
| 1381 | entity_action(entity, move |yumush, window, cx| { | 1374 | entity_action(entity, move |yumush, window, cx| { |
| 1382 | - yumush.go_to_message(anchor.clone(), window, cx) | 1375 | + yumush.go_to_message(anchor, window, cx) |
| 1383 | }), | 1376 | }), |
| 1384 | ) | 1377 | ) |
| 1385 | .child("↑"), | 1378 | .child("↑"), |
| @@ -1445,7 +1438,7 @@ impl Yumush { | |||
| 1445 | fn message_list(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement { | 1438 | fn message_list(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement { |
| 1446 | let divider = self | 1439 | let divider = self |
| 1447 | .chat | 1440 | .chat |
| 1448 | - .unread_divider(self.user.as_ref().map(|user| user.id.as_str())); | 1441 | + .unread_divider(self.user.as_ref().map(|user| user.id)); |
| 1449 | let entity_scroll = entity.clone(); | 1442 | let entity_scroll = entity.clone(); |
| 1450 | div() | 1443 | div() |
| 1451 | .id("chat_messages") | 1444 | .id("chat_messages") |
| @@ -1593,18 +1586,18 @@ impl Yumush { | |||
| 1593 | 1586 | ||
| 1594 | pub(super) fn select_community( | 1587 | pub(super) fn select_community( |
| 1595 | &mut self, | 1588 | &mut self, |
| 1596 | - community_id: String, | 1589 | + community_id: Id, |
| 1597 | window: &mut Window, | 1590 | window: &mut Window, |
| 1598 | cx: &mut Context<Self>, | 1591 | cx: &mut Context<Self>, |
| 1599 | ) { | 1592 | ) { |
| 1600 | self.stop_playing(cx); | 1593 | self.stop_playing(cx); |
| 1601 | self.save_draft(cx); | 1594 | self.save_draft(cx); |
| 1602 | - self.chat.select(Some(community_id.clone())); | 1595 | + self.chat.select(Some(community_id)); |
| 1603 | - self.restore_draft(&community_id, window, cx); | 1596 | + self.restore_draft(community_id, window, cx); |
| 1604 | self.chat.focus(window, cx); | 1597 | self.chat.focus(window, cx); |
| 1605 | self.load_members(window, cx); | 1598 | self.load_members(window, cx); |
| 1606 | self.load_pins(window, cx); | 1599 | self.load_pins(window, cx); |
| 1607 | - self.load_voice(community_id.clone(), cx); | 1600 | + self.load_voice(community_id, cx); |
| 1608 | self.load_shares(community_id, cx); | 1601 | self.load_shares(community_id, cx); |
| 1609 | self.load_messages(None, window, cx); | 1602 | self.load_messages(None, window, cx); |
| 1610 | cx.notify(); | 1603 | cx.notify(); |
| @@ -1616,7 +1609,7 @@ impl Yumush { | |||
| 1616 | window: &mut Window, | 1609 | window: &mut Window, |
| 1617 | cx: &mut Context<Self>, | 1610 | cx: &mut Context<Self>, |
| 1618 | ) { | 1611 | ) { |
| 1619 | - let community_id = community.id.clone(); | 1612 | + let community_id = community.id; |
| 1620 | self.chat.insert_community(community); | 1613 | self.chat.insert_community(community); |
| 1621 | self.request_social_avatars(cx); | 1614 | self.request_social_avatars(cx); |
| 1622 | self.select_community(community_id, window, cx); | 1615 | self.select_community(community_id, window, cx); |
| @@ -1628,11 +1621,11 @@ impl Yumush { | |||
| 1628 | self.load_communities(window, cx); | 1621 | self.load_communities(window, cx); |
| 1629 | self.load_social(window, cx); | 1622 | self.load_social(window, cx); |
| 1630 | 1623 | ||
| 1631 | - if let Some(community_id) = self.chat.selected_community_id.clone() { | 1624 | + if let Some(community_id) = self.chat.selected_community_id { |
| 1632 | self.load_members(window, cx); | 1625 | self.load_members(window, cx); |
| 1633 | self.chat.messages.clear(); | 1626 | self.chat.messages.clear(); |
| 1634 | self.load_messages(None, window, cx); | 1627 | self.load_messages(None, window, cx); |
| 1635 | - self.load_voice(community_id.clone(), cx); | 1628 | + self.load_voice(community_id, cx); |
| 1636 | self.load_shares(community_id, cx); | 1629 | self.load_shares(community_id, cx); |
| 1637 | } | 1630 | } |
| 1638 | } | 1631 | } |
| @@ -1650,7 +1643,7 @@ impl Yumush { | |||
| 1650 | let _ = this.update_in(cx, |yumush, window, cx| { | 1643 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 1651 | yumush.chat.unread = unreads | 1644 | yumush.chat.unread = unreads |
| 1652 | .into_iter() | 1645 | .into_iter() |
| 1653 | - .map(|unread| (unread.community_id.clone(), unread)) | 1646 | + .map(|unread| (unread.community_id, unread)) |
| 1654 | .collect(); | 1647 | .collect(); |
| 1655 | yumush.chat.replace_communities(communities); | 1648 | yumush.chat.replace_communities(communities); |
| 1656 | yumush.request_social_avatars(cx); | 1649 | yumush.request_social_avatars(cx); |
| @@ -1660,7 +1653,7 @@ impl Yumush { | |||
| 1660 | .chat | 1653 | .chat |
| 1661 | .communities | 1654 | .communities |
| 1662 | .first() | 1655 | .first() |
| 1663 | - .map(|community| community.id.clone()); | 1656 | + .map(|community| community.id); |
| 1664 | if let Some(community_id) = first { | 1657 | if let Some(community_id) = first { |
| 1665 | yumush.select_community(community_id, window, cx); | 1658 | yumush.select_community(community_id, window, cx); |
| 1666 | } | 1659 | } |
| @@ -1672,7 +1665,7 @@ impl Yumush { | |||
| 1672 | } | 1665 | } |
| 1673 | 1666 | ||
| 1674 | fn search_community(&self, window: &mut Window, cx: &mut Context<Self>) { | 1667 | fn search_community(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 1675 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 1668 | + let Some(community_id) = self.chat.selected_community_id else { |
| 1676 | return; | 1669 | return; |
| 1677 | }; | 1670 | }; |
| 1678 | let text = search_text(&self.chat.community_search, cx); | 1671 | let text = search_text(&self.chat.community_search, cx); |
| @@ -1683,12 +1676,7 @@ impl Yumush { | |||
| 1683 | 1676 | ||
| 1684 | cx.spawn_in(window, async move |this, cx| { | 1677 | cx.spawn_in(window, async move |this, cx| { |
| 1685 | let Some(hits) = ok_or_notify( | 1678 | let Some(hits) = ok_or_notify( |
| 1686 | - network | 1679 | + network.call(SearchCommunity { community_id, text }).await, |
| 1687 | - .call(SearchCommunity { | ||
| 1688 | - community_id: community_id.clone(), | ||
| 1689 | - text, | ||
| 1690 | - }) | ||
| 1691 | - .await, | ||
| 1692 | &this, | 1680 | &this, |
| 1693 | cx, | 1681 | cx, |
| 1694 | ) else { | 1682 | ) else { |
| @@ -1696,7 +1684,7 @@ impl Yumush { | |||
| 1696 | }; | 1684 | }; |
| 1697 | 1685 | ||
| 1698 | let _ = this.update(cx, |yumush, cx| { | 1686 | let _ = this.update(cx, |yumush, cx| { |
| 1699 | - if yumush.chat.is_selected(&community_id) { | 1687 | + if yumush.chat.is_selected(community_id) { |
| 1700 | yumush.chat.community_hits = hits; | 1688 | yumush.chat.community_hits = hits; |
| 1701 | cx.notify(); | 1689 | cx.notify(); |
| 1702 | } | 1690 | } |
| @@ -1706,26 +1694,19 @@ impl Yumush { | |||
| 1706 | } | 1694 | } |
| 1707 | 1695 | ||
| 1708 | fn load_pins(&self, window: &mut Window, cx: &mut Context<Self>) { | 1696 | fn load_pins(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 1709 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 1697 | + let Some(community_id) = self.chat.selected_community_id else { |
| 1710 | return; | 1698 | return; |
| 1711 | }; | 1699 | }; |
| 1712 | let network = self.network.clone(); | 1700 | let network = self.network.clone(); |
| 1713 | 1701 | ||
| 1714 | cx.spawn_in(window, async move |this, cx| { | 1702 | cx.spawn_in(window, async move |this, cx| { |
| 1715 | - let Some(pins) = ok_or_notify( | 1703 | + let Some(pins) = ok_or_notify(network.call(ListPins { community_id }).await, &this, cx) |
| 1716 | - network | 1704 | + else { |
| 1717 | - .call(ListPins { | ||
| 1718 | - community_id: community_id.clone(), | ||
| 1719 | - }) | ||
| 1720 | - .await, | ||
| 1721 | - &this, | ||
| 1722 | - cx, | ||
| 1723 | - ) else { | ||
| 1724 | return; | 1705 | return; |
| 1725 | }; | 1706 | }; |
| 1726 | 1707 | ||
| 1727 | let _ = this.update(cx, |yumush, cx| { | 1708 | let _ = this.update(cx, |yumush, cx| { |
| 1728 | - if yumush.chat.is_selected(&community_id) { | 1709 | + if yumush.chat.is_selected(community_id) { |
| 1729 | yumush.chat.pins = pins; | 1710 | yumush.chat.pins = pins; |
| 1730 | cx.notify(); | 1711 | cx.notify(); |
| 1731 | } | 1712 | } |
| @@ -1735,32 +1716,26 @@ impl Yumush { | |||
| 1735 | } | 1716 | } |
| 1736 | 1717 | ||
| 1737 | fn load_members(&self, window: &mut Window, cx: &mut Context<Self>) { | 1718 | fn load_members(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 1738 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 1719 | + let Some(community_id) = self.chat.selected_community_id else { |
| 1739 | return; | 1720 | return; |
| 1740 | }; | 1721 | }; |
| 1741 | let network = self.network.clone(); | 1722 | let network = self.network.clone(); |
| 1742 | 1723 | ||
| 1743 | cx.spawn_in(window, async move |this, cx| { | 1724 | cx.spawn_in(window, async move |this, cx| { |
| 1744 | - let Some(members) = ok_or_notify( | 1725 | + let Some(members) = |
| 1745 | - network | 1726 | + ok_or_notify(network.call(ListMembers { community_id }).await, &this, cx) |
| 1746 | - .call(ListMembers { | 1727 | + else { |
| 1747 | - community_id: community_id.clone(), | ||
| 1748 | - }) | ||
| 1749 | - .await, | ||
| 1750 | - &this, | ||
| 1751 | - cx, | ||
| 1752 | - ) else { | ||
| 1753 | return; | 1728 | return; |
| 1754 | }; | 1729 | }; |
| 1755 | 1730 | ||
| 1756 | let _ = this.update_in(cx, |yumush, window, cx| { | 1731 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 1757 | - if yumush.chat.is_selected(&community_id) { | 1732 | + if yumush.chat.is_selected(community_id) { |
| 1758 | for member in &members { | 1733 | for member in &members { |
| 1759 | yumush.request_user_avatar(&member.user, cx); | 1734 | yumush.request_user_avatar(&member.user, cx); |
| 1760 | yumush | 1735 | yumush |
| 1761 | .chat | 1736 | .chat |
| 1762 | .users | 1737 | .users |
| 1763 | - .insert(member.user.id.clone(), member.user.clone()); | 1738 | + .insert(member.user.id, member.user.clone()); |
| 1764 | } | 1739 | } |
| 1765 | yumush.chat.members = members; | 1740 | yumush.chat.members = members; |
| 1766 | yumush.load_bans(window, cx); | 1741 | yumush.load_bans(window, cx); |
| @@ -1777,7 +1752,7 @@ impl Yumush { | |||
| 1777 | if missing.is_empty() { | 1752 | if missing.is_empty() { |
| 1778 | return; | 1753 | return; |
| 1779 | } | 1754 | } |
| 1780 | - self.chat.user_requests.extend(missing.iter().cloned()); | 1755 | + self.chat.user_requests.extend(missing.iter().copied()); |
| 1781 | let network = self.network.clone(); | 1756 | let network = self.network.clone(); |
| 1782 | 1757 | ||
| 1783 | cx.spawn(async move |this, cx| { | 1758 | cx.spawn(async move |this, cx| { |
| @@ -1787,7 +1762,7 @@ impl Yumush { | |||
| 1787 | }; | 1762 | }; |
| 1788 | let _ = this.update(cx, |yumush, cx| { | 1763 | let _ = this.update(cx, |yumush, cx| { |
| 1789 | yumush.request_user_avatar(&user, cx); | 1764 | yumush.request_user_avatar(&user, cx); |
| 1790 | - yumush.chat.users.insert(user.id.clone(), user); | 1765 | + yumush.chat.users.insert(user.id, user); |
| 1791 | cx.notify(); | 1766 | cx.notify(); |
| 1792 | }); | 1767 | }); |
| 1793 | } | 1768 | } |
| @@ -1799,26 +1774,19 @@ impl Yumush { | |||
| 1799 | if !permission::can_unban(self.actor_rank()) { | 1774 | if !permission::can_unban(self.actor_rank()) { |
| 1800 | return; | 1775 | return; |
| 1801 | } | 1776 | } |
| 1802 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 1777 | + let Some(community_id) = self.chat.selected_community_id else { |
| 1803 | return; | 1778 | return; |
| 1804 | }; | 1779 | }; |
| 1805 | let network = self.network.clone(); | 1780 | let network = self.network.clone(); |
| 1806 | 1781 | ||
| 1807 | cx.spawn_in(window, async move |this, cx| { | 1782 | cx.spawn_in(window, async move |this, cx| { |
| 1808 | - let Some(bans) = ok_or_notify( | 1783 | + let Some(bans) = ok_or_notify(network.call(ListBans { community_id }).await, &this, cx) |
| 1809 | - network | 1784 | + else { |
| 1810 | - .call(ListBans { | ||
| 1811 | - community_id: community_id.clone(), | ||
| 1812 | - }) | ||
| 1813 | - .await, | ||
| 1814 | - &this, | ||
| 1815 | - cx, | ||
| 1816 | - ) else { | ||
| 1817 | return; | 1785 | return; |
| 1818 | }; | 1786 | }; |
| 1819 | 1787 | ||
| 1820 | let _ = this.update(cx, |yumush, cx| { | 1788 | let _ = this.update(cx, |yumush, cx| { |
| 1821 | - if yumush.chat.is_selected(&community_id) { | 1789 | + if yumush.chat.is_selected(community_id) { |
| 1822 | for ban in &bans { | 1790 | for ban in &bans { |
| 1823 | yumush.request_user_avatar(&ban.user, cx); | 1791 | yumush.request_user_avatar(&ban.user, cx); |
| 1824 | } | 1792 | } |
| @@ -1832,7 +1800,7 @@ impl Yumush { | |||
| 1832 | 1800 | ||
| 1833 | pub(super) fn go_to_message( | 1801 | pub(super) fn go_to_message( |
| 1834 | &mut self, | 1802 | &mut self, |
| 1835 | - message_id: String, | 1803 | + message_id: Id, |
| 1836 | window: &mut Window, | 1804 | window: &mut Window, |
| 1837 | cx: &mut Context<Self>, | 1805 | cx: &mut Context<Self>, |
| 1838 | ) { | 1806 | ) { |
| @@ -1861,14 +1829,14 @@ impl Yumush { | |||
| 1861 | } | 1829 | } |
| 1862 | 1830 | ||
| 1863 | fn load_older_messages(&self, window: &mut Window, cx: &mut Context<Self>) { | 1831 | fn load_older_messages(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 1864 | - let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else { | 1832 | + let Some(oldest_id) = self.chat.messages.first().map(|message| message.id) else { |
| 1865 | return; | 1833 | return; |
| 1866 | }; | 1834 | }; |
| 1867 | self.load_messages(Some(oldest_id), window, cx); | 1835 | self.load_messages(Some(oldest_id), window, cx); |
| 1868 | } | 1836 | } |
| 1869 | 1837 | ||
| 1870 | - fn load_messages(&self, before: Option<String>, window: &mut Window, cx: &mut Context<Self>) { | 1838 | + fn load_messages(&self, before: Option<Id>, window: &mut Window, cx: &mut Context<Self>) { |
| 1871 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 1839 | + let Some(community_id) = self.chat.selected_community_id else { |
| 1872 | return; | 1840 | return; |
| 1873 | }; | 1841 | }; |
| 1874 | let network = self.network.clone(); | 1842 | let network = self.network.clone(); |
| @@ -1878,14 +1846,14 @@ impl Yumush { | |||
| 1878 | if before.is_none() { | 1846 | if before.is_none() { |
| 1879 | let _ = network | 1847 | let _ = network |
| 1880 | .call(WatchCommunity { | 1848 | .call(WatchCommunity { |
| 1881 | - community_id: Some(community_id.clone()), | 1849 | + community_id: Some(community_id), |
| 1882 | }) | 1850 | }) |
| 1883 | .await; | 1851 | .await; |
| 1884 | } | 1852 | } |
| 1885 | let Some(page) = ok_or_notify( | 1853 | let Some(page) = ok_or_notify( |
| 1886 | network | 1854 | network |
| 1887 | .call(ListMessages { | 1855 | .call(ListMessages { |
| 1888 | - community_id: community_id.clone(), | 1856 | + community_id, |
| 1889 | before, | 1857 | before, |
| 1890 | }) | 1858 | }) |
| 1891 | .await, | 1859 | .await, |
| @@ -1896,17 +1864,17 @@ impl Yumush { | |||
| 1896 | }; | 1864 | }; |
| 1897 | 1865 | ||
| 1898 | let _ = this.update_in(cx, |yumush, window, cx| { | 1866 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 1899 | - if yumush.chat.is_selected(&community_id) { | 1867 | + if yumush.chat.is_selected(community_id) { |
| 1900 | - let newest = page.last().map(|message| message.id.clone()); | 1868 | + let newest = page.last().map(|message| message.id); |
| 1901 | let seeking = yumush.chat.jump.is_some(); | 1869 | let seeking = yumush.chat.jump.is_some(); |
| 1902 | yumush | 1870 | yumush |
| 1903 | .chat | 1871 | .chat |
| 1904 | - .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str())); | 1872 | + .add_page(page, yumush.user.as_ref().map(|user| user.id)); |
| 1905 | if seeking { | 1873 | if seeking { |
| 1906 | yumush.continue_jump(window, cx); | 1874 | yumush.continue_jump(window, cx); |
| 1907 | } | 1875 | } |
| 1908 | if let Some(message_id) = newest.filter(|_| latest) { | 1876 | if let Some(message_id) = newest.filter(|_| latest) { |
| 1909 | - yumush.mark_read(&community_id, &message_id, cx); | 1877 | + yumush.mark_read(community_id, message_id, cx); |
| 1910 | } | 1878 | } |
| 1911 | yumush.request_media(cx); | 1879 | yumush.request_media(cx); |
| 1912 | yumush.request_authors(cx); | 1880 | yumush.request_authors(cx); |
| @@ -1919,15 +1887,15 @@ impl Yumush { | |||
| 1919 | 1887 | ||
| 1920 | pub(super) fn request_message_delete( | 1888 | pub(super) fn request_message_delete( |
| 1921 | &mut self, | 1889 | &mut self, |
| 1922 | - message_id: String, | 1890 | + message_id: Id, |
| 1923 | window: &mut Window, | 1891 | window: &mut Window, |
| 1924 | cx: &mut Context<Self>, | 1892 | cx: &mut Context<Self>, |
| 1925 | ) { | 1893 | ) { |
| 1926 | if self.chat.pending_message_delete.as_ref() == Some(&message_id) { | 1894 | if self.chat.pending_message_delete.as_ref() == Some(&message_id) { |
| 1927 | self.chat.pending_message_delete = None; | 1895 | self.chat.pending_message_delete = None; |
| 1928 | - self.delete_message(&message_id, window, cx); | 1896 | + self.delete_message(message_id, window, cx); |
| 1929 | } else { | 1897 | } else { |
| 1930 | - self.chat.pending_message_delete = Some(message_id.clone()); | 1898 | + self.chat.pending_message_delete = Some(message_id); |
| 1931 | cx.spawn(async move |this, cx| { | 1899 | cx.spawn(async move |this, cx| { |
| 1932 | cx.background_executor().timer(DELETE_CONFIRM).await; | 1900 | cx.background_executor().timer(DELETE_CONFIRM).await; |
| 1933 | let _ = this.update(cx, |yumush, cx| { | 1901 | let _ = this.update(cx, |yumush, cx| { |
| @@ -1944,13 +1912,11 @@ impl Yumush { | |||
| 1944 | 1912 | ||
| 1945 | pub(super) fn delete_message( | 1913 | pub(super) fn delete_message( |
| 1946 | &self, | 1914 | &self, |
| 1947 | - message_id: &str, | 1915 | + message_id: Id, |
| 1948 | window: &mut Window, | 1916 | window: &mut Window, |
| 1949 | cx: &mut Context<Self>, | 1917 | cx: &mut Context<Self>, |
| 1950 | ) { | 1918 | ) { |
| 1951 | let network = self.network.clone(); | 1919 | let network = self.network.clone(); |
| 1952 | - let message_id = message_id.to_string(); | ||
| 1953 | - | ||
| 1954 | spawn_done(window, cx, async move { | 1920 | spawn_done(window, cx, async move { |
| 1955 | network.call(DeleteMessage { message_id }).await | 1921 | network.call(DeleteMessage { message_id }).await |
| 1956 | }); | 1922 | }); |
| @@ -1958,41 +1924,32 @@ impl Yumush { | |||
| 1958 | 1924 | ||
| 1959 | pub(super) fn leave_community( | 1925 | pub(super) fn leave_community( |
| 1960 | &self, | 1926 | &self, |
| 1961 | - community_id: String, | 1927 | + community_id: Id, |
| 1962 | window: &mut Window, | 1928 | window: &mut Window, |
| 1963 | cx: &mut Context<Self>, | 1929 | cx: &mut Context<Self>, |
| 1964 | ) { | 1930 | ) { |
| 1965 | let network = self.network.clone(); | 1931 | let network = self.network.clone(); |
| 1966 | 1932 | ||
| 1967 | cx.spawn_in(window, async move |this, cx| { | 1933 | cx.spawn_in(window, async move |this, cx| { |
| 1968 | - if let Err(error) = network | 1934 | + if let Err(error) = network.call(LeaveCommunity { community_id }).await { |
| 1969 | - .call(LeaveCommunity { | ||
| 1970 | - community_id: community_id.clone(), | ||
| 1971 | - }) | ||
| 1972 | - .await | ||
| 1973 | - { | ||
| 1974 | notify_error(&this, cx, error); | 1935 | notify_error(&this, cx, error); |
| 1975 | return; | 1936 | return; |
| 1976 | } | 1937 | } |
| 1977 | 1938 | ||
| 1978 | let _ = this.update(cx, |yumush, cx| { | 1939 | let _ = this.update(cx, |yumush, cx| { |
| 1979 | - yumush.leave_voice_in(&community_id, cx); | 1940 | + yumush.leave_voice_in(community_id, cx); |
| 1980 | - yumush.chat.remove_community(&community_id); | 1941 | + yumush.chat.remove_community(community_id); |
| 1981 | cx.notify(); | 1942 | cx.notify(); |
| 1982 | }); | 1943 | }); |
| 1983 | }) | 1944 | }) |
| 1984 | .detach(); | 1945 | .detach(); |
| 1985 | } | 1946 | } |
| 1986 | 1947 | ||
| 1987 | - fn load_voice(&self, community_id: String, cx: &mut Context<Self>) { | 1948 | + fn load_voice(&self, community_id: Id, cx: &mut Context<Self>) { |
| 1988 | let network = self.network.clone(); | 1949 | let network = self.network.clone(); |
| 1989 | 1950 | ||
| 1990 | cx.spawn(async move |this, cx| { | 1951 | cx.spawn(async move |this, cx| { |
| 1991 | - let Ok(participants) = network | 1952 | + let Ok(participants) = network.call(ListVoiceParticipants { community_id }).await |
| 1992 | - .call(ListVoiceParticipants { | ||
| 1993 | - community_id: community_id.clone(), | ||
| 1994 | - }) | ||
| 1995 | - .await | ||
| 1996 | else { | 1953 | else { |
| 1997 | return; | 1954 | return; |
| 1998 | }; | 1955 | }; |
| @@ -2007,11 +1964,11 @@ impl Yumush { | |||
| 2007 | 1964 | ||
| 2008 | pub(super) fn toggle_voice( | 1965 | pub(super) fn toggle_voice( |
| 2009 | &mut self, | 1966 | &mut self, |
| 2010 | - community_id: String, | 1967 | + community_id: Id, |
| 2011 | window: &mut Window, | 1968 | window: &mut Window, |
| 2012 | cx: &mut Context<Self>, | 1969 | cx: &mut Context<Self>, |
| 2013 | ) { | 1970 | ) { |
| 2014 | - if self.chat.in_voice(&community_id) { | 1971 | + if self.chat.in_voice(community_id) { |
| 2015 | self.end_voice(cx); | 1972 | self.end_voice(cx); |
| 2016 | return; | 1973 | return; |
| 2017 | } | 1974 | } |
| @@ -2026,7 +1983,7 @@ impl Yumush { | |||
| 2026 | 1983 | ||
| 2027 | fn join_voice( | 1984 | fn join_voice( |
| 2028 | &mut self, | 1985 | &mut self, |
| 2029 | - community_id: String, | 1986 | + community_id: Id, |
| 2030 | (muted, deafened): (bool, bool), | 1987 | (muted, deafened): (bool, bool), |
| 2031 | was_in: bool, | 1988 | was_in: bool, |
| 2032 | window: &mut Window, | 1989 | window: &mut Window, |
| @@ -2040,15 +1997,15 @@ impl Yumush { | |||
| 2040 | let _ = network.leave_voice().await; | 1997 | let _ = network.leave_voice().await; |
| 2041 | } | 1998 | } |
| 2042 | 1999 | ||
| 2043 | - match network.join_voice(&community_id, &voice_settings).await { | 2000 | + match network.join_voice(community_id, &voice_settings).await { |
| 2044 | Ok(participants) => { | 2001 | Ok(participants) => { |
| 2045 | network.set_deafened(deafened); | 2002 | network.set_deafened(deafened); |
| 2046 | let _ = this.update_in(cx, |yumush, _, cx| { | 2003 | let _ = this.update_in(cx, |yumush, _, cx| { |
| 2047 | let muted = | 2004 | let muted = |
| 2048 | - muted || yumush.is_server_muted() || yumush.hidden_in(&community_id); | 2005 | + muted || yumush.is_server_muted() || yumush.hidden_in(community_id); |
| 2049 | yumush.network.set_muted(muted); | 2006 | yumush.network.set_muted(muted); |
| 2050 | - yumush.chat.voice.insert(community_id.clone(), participants); | 2007 | + yumush.chat.voice.insert(community_id, participants); |
| 2051 | - yumush.load_shares(community_id.clone(), cx); | 2008 | + yumush.load_shares(community_id, cx); |
| 2052 | yumush.chat.voice_state = VoiceState::In { | 2009 | yumush.chat.voice_state = VoiceState::In { |
| 2053 | community_id, | 2010 | community_id, |
| 2054 | muted, | 2011 | muted, |
| @@ -2084,14 +2041,14 @@ impl Yumush { | |||
| 2084 | } | 2041 | } |
| 2085 | 2042 | ||
| 2086 | pub(super) fn refresh_voice(&mut self, cx: &mut Context<Self>) { | 2043 | pub(super) fn refresh_voice(&mut self, cx: &mut Context<Self>) { |
| 2087 | - let Some(community_id) = self.chat.voice_community().map(str::to_string) else { | 2044 | + let Some(community_id) = self.chat.voice_community() else { |
| 2088 | return; | 2045 | return; |
| 2089 | }; | 2046 | }; |
| 2090 | - self.load_voice(community_id.clone(), cx); | 2047 | + self.load_voice(community_id, cx); |
| 2091 | self.load_shares(community_id, cx); | 2048 | self.load_shares(community_id, cx); |
| 2092 | } | 2049 | } |
| 2093 | 2050 | ||
| 2094 | - pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context<Self>) { | 2051 | + pub(super) fn leave_voice_in(&mut self, community_id: Id, cx: &mut Context<Self>) { |
| 2095 | if self.chat.in_voice(community_id) { | 2052 | if self.chat.in_voice(community_id) { |
| 2096 | self.end_voice(cx); | 2053 | self.end_voice(cx); |
| 2097 | } | 2054 | } |
| @@ -2103,7 +2060,7 @@ impl Yumush { | |||
| 2103 | .is_some_and(|me| self.chat.server_muted.contains(&me.id)) | 2060 | .is_some_and(|me| self.chat.server_muted.contains(&me.id)) |
| 2104 | } | 2061 | } |
| 2105 | 2062 | ||
| 2106 | - fn hidden_in(&self, community_id: &str) -> bool { | 2063 | + fn hidden_in(&self, community_id: Id) -> bool { |
| 2107 | self.chat.ghost || !self.chat.joined(community_id) | 2064 | self.chat.ghost || !self.chat.joined(community_id) |
| 2108 | } | 2065 | } |
| 2109 | 2066 | ||
| @@ -2238,13 +2195,11 @@ impl Yumush { | |||
| 2238 | })); | 2195 | })); |
| 2239 | } | 2196 | } |
| 2240 | 2197 | ||
| 2241 | - pub(super) fn open_user_volume(&mut self, user_id: &str, cx: &mut Context<Self>) { | 2198 | + pub(super) fn open_user_volume(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 2242 | - let in_call = self.chat.voice_community().is_some_and(|community_id| { | 2199 | + let in_call = self |
| 2243 | - self.chat | 2200 | + .chat |
| 2244 | - .voice_ids(community_id) | 2201 | + .voice_community() |
| 2245 | - .iter() | 2202 | + .is_some_and(|community_id| self.chat.voice_ids(community_id).contains(&user_id)); |
| 2246 | - .any(|id| id == user_id) | ||
| 2247 | - }); | ||
| 2248 | if !in_call || self.is_me(user_id) { | 2203 | if !in_call || self.is_me(user_id) { |
| 2249 | self.chat.user_volume = None; | 2204 | self.chat.user_volume = None; |
| 2250 | return; | 2205 | return; |
| @@ -2256,30 +2211,29 @@ impl Yumush { | |||
| 2256 | .max(*VOLUME.end()) | 2211 | .max(*VOLUME.end()) |
| 2257 | .default_value(volume) | 2212 | .default_value(volume) |
| 2258 | }); | 2213 | }); |
| 2259 | - let id = user_id.to_string(); | ||
| 2260 | let subscription = cx.subscribe(&slider, move |this, _, event: &SliderEvent, cx| { | 2214 | let subscription = cx.subscribe(&slider, move |this, _, event: &SliderEvent, cx| { |
| 2261 | let SliderEvent::Change(value) = event else { | 2215 | let SliderEvent::Change(value) = event else { |
| 2262 | return; | 2216 | return; |
| 2263 | }; | 2217 | }; |
| 2264 | let volumes = &mut this.settings.voice.user_volumes; | 2218 | let volumes = &mut this.settings.voice.user_volumes; |
| 2265 | match value.start() { | 2219 | match value.start() { |
| 2266 | - volume if volume == DEFAULT_USER_VOLUME => volumes.remove(&id), | 2220 | + volume if volume == DEFAULT_USER_VOLUME => volumes.remove(&user_id), |
| 2267 | - volume => volumes.insert(id.clone(), volume), | 2221 | + volume => volumes.insert(user_id, volume), |
| 2268 | }; | 2222 | }; |
| 2269 | this.commit_settings(cx); | 2223 | this.commit_settings(cx); |
| 2270 | }); | 2224 | }); |
| 2271 | self.chat.user_volume = Some(UserVolume { | 2225 | self.chat.user_volume = Some(UserVolume { |
| 2272 | - user_id: user_id.to_string(), | 2226 | + user_id, |
| 2273 | slider, | 2227 | slider, |
| 2274 | _subscription: subscription, | 2228 | _subscription: subscription, |
| 2275 | }); | 2229 | }); |
| 2276 | } | 2230 | } |
| 2277 | 2231 | ||
| 2278 | - pub(super) fn user_volume(&self, user_id: &str) -> f32 { | 2232 | + pub(super) fn user_volume(&self, user_id: Id) -> f32 { |
| 2279 | self.settings | 2233 | self.settings |
| 2280 | .voice | 2234 | .voice |
| 2281 | .user_volumes | 2235 | .user_volumes |
| 2282 | - .get(user_id) | 2236 | + .get(&user_id) |
| 2283 | .copied() | 2237 | .copied() |
| 2284 | .unwrap_or(DEFAULT_USER_VOLUME) | 2238 | .unwrap_or(DEFAULT_USER_VOLUME) |
| 2285 | } | 2239 | } |
| @@ -2289,19 +2243,19 @@ impl Yumush { | |||
| 2289 | .chat | 2243 | .chat |
| 2290 | .voice_flags() | 2244 | .voice_flags() |
| 2291 | .is_some_and(|(muted, deafened)| muted || deafened); | 2245 | .is_some_and(|(muted, deafened)| muted || deafened); |
| 2292 | - let me = self.user.as_ref().map(|user| user.id.as_str()); | 2246 | + let me = self.user.as_ref().map(|user| user.id); |
| 2293 | if self.chat.waves.update(levels, me, silent) { | 2247 | if self.chat.waves.update(levels, me, silent) { |
| 2294 | cx.notify(); | 2248 | cx.notify(); |
| 2295 | } | 2249 | } |
| 2296 | } | 2250 | } |
| 2297 | 2251 | ||
| 2298 | fn voice_button(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { | 2252 | fn voice_button(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { |
| 2299 | - let community_id = self.chat.selected_community_id.clone()?; | 2253 | + let community_id = self.chat.selected_community_id?; |
| 2300 | - let direct = self.is_direct(&community_id); | 2254 | + let direct = self.is_direct(community_id); |
| 2301 | - let in_voice = self.chat.in_voice(&community_id); | 2255 | + let in_voice = self.chat.in_voice(community_id); |
| 2302 | if !in_voice | 2256 | if !in_voice |
| 2303 | && (!permission::can_join_voice(self.actor_rank()) | 2257 | && (!permission::can_join_voice(self.actor_rank()) |
| 2304 | - || !(self.is_builder() || self.chat.voice_enabled(&community_id)) | 2258 | + || !(self.is_builder() || self.chat.voice_enabled(community_id)) |
| 2305 | || self | 2259 | || self |
| 2306 | .chat | 2260 | .chat |
| 2307 | .notes() | 2261 | .notes() |
| @@ -2313,7 +2267,7 @@ impl Yumush { | |||
| 2313 | let entity = entity.clone(); | 2267 | let entity = entity.clone(); |
| 2314 | let on_click = move |window: &mut Window, cx: &mut App| { | 2268 | let on_click = move |window: &mut Window, cx: &mut App| { |
| 2315 | entity.update(cx, |yumush, cx| { | 2269 | entity.update(cx, |yumush, cx| { |
| 2316 | - yumush.toggle_voice(community_id.clone(), window, cx) | 2270 | + yumush.toggle_voice(community_id, window, cx) |
| 2317 | }) | 2271 | }) |
| 2318 | }; | 2272 | }; |
| 2319 | let (icon, tip) = match (direct, in_voice) { | 2273 | let (icon, tip) = match (direct, in_voice) { |
| @@ -2343,13 +2297,13 @@ impl Yumush { | |||
| 2343 | 2297 | ||
| 2344 | fn calling_hint(&self, palette: Palette) -> Option<Div> { | 2298 | fn calling_hint(&self, palette: Palette) -> Option<Div> { |
| 2345 | let community = self.chat.selected_community()?; | 2299 | let community = self.chat.selected_community()?; |
| 2346 | - let direct = self.is_direct(&community.id); | 2300 | + let direct = self.is_direct(community.id); |
| 2347 | - let alone = self.chat.in_voice(&community.id) | 2301 | + let alone = self.chat.in_voice(community.id) |
| 2348 | && self | 2302 | && self |
| 2349 | .chat | 2303 | .chat |
| 2350 | - .voice_ids(&community.id) | 2304 | + .voice_ids(community.id) |
| 2351 | .iter() | 2305 | .iter() |
| 2352 | - .all(|id| self.is_me(id)); | 2306 | + .all(|id| self.is_me(*id)); |
| 2353 | 2307 | ||
| 2354 | (direct && alone).then(|| { | 2308 | (direct && alone).then(|| { |
| 2355 | div() | 2309 | div() |
| @@ -2361,7 +2315,7 @@ impl Yumush { | |||
| 2361 | 2315 | ||
| 2362 | fn call_banner(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> { | 2316 | fn call_banner(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> { |
| 2363 | let (community_id, caller) = self.incoming_call()?; | 2317 | let (community_id, caller) = self.incoming_call()?; |
| 2364 | - let accept_id = community_id.clone(); | 2318 | + let accept_id = community_id; |
| 2365 | 2319 | ||
| 2366 | Some( | 2320 | Some( |
| 2367 | accent_bar(palette) | 2321 | accent_bar(palette) |
| @@ -2382,7 +2336,7 @@ impl Yumush { | |||
| 2382 | "accept_call", | 2336 | "accept_call", |
| 2383 | palette, | 2337 | palette, |
| 2384 | entity_action(entity, move |yumush, window, cx| { | 2338 | entity_action(entity, move |yumush, window, cx| { |
| 2385 | - yumush.accept_call(accept_id.clone(), window, cx) | 2339 | + yumush.accept_call(accept_id, window, cx) |
| 2386 | }), | 2340 | }), |
| 2387 | ) | 2341 | ) |
| 2388 | .bg(palette.ok) | 2342 | .bg(palette.ok) |
| @@ -2395,7 +2349,7 @@ impl Yumush { | |||
| 2395 | "decline_call", | 2349 | "decline_call", |
| 2396 | palette, | 2350 | palette, |
| 2397 | entity_action(entity, move |yumush, window, cx| { | 2351 | entity_action(entity, move |yumush, window, cx| { |
| 2398 | - yumush.decline_call(community_id.clone(), window, cx) | 2352 | + yumush.decline_call(community_id, window, cx) |
| 2399 | }), | 2353 | }), |
| 2400 | ) | 2354 | ) |
| 2401 | .bg(palette.danger) | 2355 | .bg(palette.danger) |
| @@ -2408,7 +2362,7 @@ impl Yumush { | |||
| 2408 | ) | 2362 | ) |
| 2409 | } | 2363 | } |
| 2410 | 2364 | ||
| 2411 | - fn incoming_call(&self) -> Option<(String, User)> { | 2365 | + fn incoming_call(&self) -> Option<(Id, User)> { |
| 2412 | self.chat.communities().iter().find_map(|community| { | 2366 | self.chat.communities().iter().find_map(|community| { |
| 2413 | let CommunityKind::Direct { peer } = &community.kind else { | 2367 | let CommunityKind::Direct { peer } = &community.kind else { |
| 2414 | return None; | 2368 | return None; |
| @@ -2416,21 +2370,21 @@ impl Yumush { | |||
| 2416 | let calling = self.user.is_some() | 2370 | let calling = self.user.is_some() |
| 2417 | && self | 2371 | && self |
| 2418 | .chat | 2372 | .chat |
| 2419 | - .voice_ids(&community.id) | 2373 | + .voice_ids(community.id) |
| 2420 | .iter() | 2374 | .iter() |
| 2421 | - .any(|id| !self.is_me(id)); | 2375 | + .any(|id| !self.is_me(*id)); |
| 2422 | let ringing = calling | 2376 | let ringing = calling |
| 2423 | - && !self.chat.in_voice(&community.id) | 2377 | + && !self.chat.in_voice(community.id) |
| 2424 | && self.chat.ringing.contains(&community.id); | 2378 | && self.chat.ringing.contains(&community.id); |
| 2425 | - ringing.then(|| (community.id.clone(), peer.clone())) | 2379 | + ringing.then(|| (community.id, peer.clone())) |
| 2426 | }) | 2380 | }) |
| 2427 | } | 2381 | } |
| 2428 | 2382 | ||
| 2429 | - fn ring_allowed(&self, community_id: &str) -> bool { | 2383 | + fn ring_allowed(&self, community_id: Id) -> bool { |
| 2430 | self.user | 2384 | self.user |
| 2431 | .as_ref() | 2385 | .as_ref() |
| 2432 | - .is_some_and(|me| self.presence_of(&me.id) == Presence::Online) | 2386 | + .is_some_and(|me| self.presence_of(me.id) == Presence::Online) |
| 2433 | - && !self.chat.muted.contains(community_id) | 2387 | + && !self.chat.muted.contains(&community_id) |
| 2434 | } | 2388 | } |
| 2435 | 2389 | ||
| 2436 | pub(super) fn update_ringing(&mut self, cx: &mut Context<Self>) { | 2390 | pub(super) fn update_ringing(&mut self, cx: &mut Context<Self>) { |
| @@ -2446,7 +2400,7 @@ impl Yumush { | |||
| 2446 | for _ in 0..RING_LIMIT { | 2400 | for _ in 0..RING_LIMIT { |
| 2447 | let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { | 2401 | let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { |
| 2448 | Some((community_id, _)) => { | 2402 | Some((community_id, _)) => { |
| 2449 | - if yumush.ring_allowed(&community_id) { | 2403 | + if yumush.ring_allowed(community_id) { |
| 2450 | yumush.network.play_ring(&yumush.settings.voice); | 2404 | yumush.network.play_ring(&yumush.settings.voice); |
| 2451 | } | 2405 | } |
| 2452 | true | 2406 | true |
| @@ -2461,14 +2415,14 @@ impl Yumush { | |||
| 2461 | })); | 2415 | })); |
| 2462 | } | 2416 | } |
| 2463 | 2417 | ||
| 2464 | - fn accept_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context<Self>) { | 2418 | + fn accept_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 2465 | self.chat.ringing.remove(&community_id); | 2419 | self.chat.ringing.remove(&community_id); |
| 2466 | - self.select_community(community_id.clone(), window, cx); | 2420 | + self.select_community(community_id, window, cx); |
| 2467 | self.toggle_voice(community_id, window, cx); | 2421 | self.toggle_voice(community_id, window, cx); |
| 2468 | self.update_ringing(cx); | 2422 | self.update_ringing(cx); |
| 2469 | } | 2423 | } |
| 2470 | 2424 | ||
| 2471 | - fn decline_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context<Self>) { | 2425 | + fn decline_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 2472 | self.chat.ringing.remove(&community_id); | 2426 | self.chat.ringing.remove(&community_id); |
| 2473 | self.update_ringing(cx); | 2427 | self.update_ringing(cx); |
| 2474 | cx.notify(); | 2428 | cx.notify(); |
| @@ -2480,20 +2434,20 @@ impl Yumush { | |||
| 2480 | } | 2434 | } |
| 2481 | 2435 | ||
| 2482 | fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { | 2436 | fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { |
| 2483 | - let community_id = self.chat.selected_community_id.as_deref()?; | 2437 | + let community_id = self.chat.selected_community_id?; |
| 2484 | let users: Vec<&User> = self | 2438 | let users: Vec<&User> = self |
| 2485 | .chat | 2439 | .chat |
| 2486 | .voice_ids(community_id) | 2440 | .voice_ids(community_id) |
| 2487 | .iter() | 2441 | .iter() |
| 2488 | - .filter_map(|id| self.chat.member(id)) | 2442 | + .filter_map(|id| self.chat.member(*id)) |
| 2489 | .collect(); | 2443 | .collect(); |
| 2490 | if users.is_empty() { | 2444 | if users.is_empty() { |
| 2491 | return None; | 2445 | return None; |
| 2492 | } | 2446 | } |
| 2493 | - let sharers: Vec<String> = users | 2447 | + let sharers: Vec<Id> = users |
| 2494 | .iter() | 2448 | .iter() |
| 2495 | - .filter(|user| self.chat.is_sharing(community_id, &user.id)) | 2449 | + .filter(|user| self.chat.is_sharing(community_id, user.id)) |
| 2496 | - .map(|user| user.id.clone()) | 2450 | + .map(|user| user.id) |
| 2497 | .collect(); | 2451 | .collect(); |
| 2498 | 2452 | ||
| 2499 | Some( | 2453 | Some( |
| @@ -2523,8 +2477,8 @@ impl Yumush { | |||
| 2523 | .children(sharers.iter().map(|user_id| { | 2477 | .children(sharers.iter().map(|user_id| { |
| 2524 | share_view::share_badge( | 2478 | share_view::share_badge( |
| 2525 | entity, | 2479 | entity, |
| 2526 | - user_id, | 2480 | + *user_id, |
| 2527 | - self.chat.waves.share(user_id), | 2481 | + self.chat.waves.share(*user_id), |
| 2528 | palette, | 2482 | palette, |
| 2529 | ) | 2483 | ) |
| 2530 | })), | 2484 | })), |
| @@ -2614,7 +2568,6 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) - | |||
| 2614 | let entity = entity.clone(); | 2568 | let entity = entity.clone(); |
| 2615 | let voice = chat | 2569 | let voice = chat |
| 2616 | .selected_community_id | 2570 | .selected_community_id |
| 2617 | - .as_deref() | ||
| 2618 | .map(|community_id| chat.voice_ids(community_id)) | 2571 | .map(|community_id| chat.voice_ids(community_id)) |
| 2619 | .unwrap_or_default(); | 2572 | .unwrap_or_default(); |
| 2620 | let members: Vec<MemberRow> = chat | 2573 | let members: Vec<MemberRow> = chat |
| @@ -2625,7 +2578,7 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) - | |||
| 2625 | rank: chat.rank_of(&member.user), | 2578 | rank: chat.rank_of(&member.user), |
| 2626 | in_voice: voice.contains(&member.user.id), | 2579 | in_voice: voice.contains(&member.user.id), |
| 2627 | muted: chat.server_muted.contains(&member.user.id), | 2580 | muted: chat.server_muted.contains(&member.user.id), |
| 2628 | - presence: yumush.presence_of(&member.user.id), | 2581 | + presence: yumush.presence_of(member.user.id), |
| 2629 | }) | 2582 | }) |
| 2630 | .collect(); | 2583 | .collect(); |
| 2631 | let avatars = chat.avatars.clone(); | 2584 | let avatars = chat.avatars.clone(); |
| @@ -2787,7 +2740,7 @@ fn render_call( | |||
| 2787 | ) -> AnyElement { | 2740 | ) -> AnyElement { |
| 2788 | let mine = me.is_some_and(|me| me.id == message.user_id); | 2741 | let mine = me.is_some_and(|me| me.id == message.user_id); |
| 2789 | let author = chat | 2742 | let author = chat |
| 2790 | - .author(&message.user_id) | 2743 | + .author(message.user_id) |
| 2791 | .map_or("unknown", |user| user.username.as_str()); | 2744 | .map_or("unknown", |user| user.username.as_str()); |
| 2792 | let who = if mine { "You" } else { author }; | 2745 | let who = if mine { "You" } else { author }; |
| 2793 | let (icon, color) = match call { | 2746 | let (icon, color) = match call { |
| @@ -2828,7 +2781,7 @@ fn render_message( | |||
| 2828 | if let Some(call) = message.call { | 2781 | if let Some(call) = message.call { |
| 2829 | return render_call(message, call, chat, me, palette); | 2782 | return render_call(message, call, chat, me, palette); |
| 2830 | } | 2783 | } |
| 2831 | - let author = chat.author(&message.user_id); | 2784 | + let author = chat.author(message.user_id); |
| 2832 | let username = author.map_or("unknown", |user| user.username.as_str()); | 2785 | let username = author.map_or("unknown", |user| user.username.as_str()); |
| 2833 | let name = div() | 2786 | let name = div() |
| 2834 | .flex() | 2787 | .flex() |
| @@ -2836,13 +2789,13 @@ fn render_message( | |||
| 2836 | .gap(px(8.)) | 2789 | .gap(px(8.)) |
| 2837 | .child(match author { | 2790 | .child(match author { |
| 2838 | Some(user) => avatar(palette, user, px(20.), text(10.), &chat.avatars), | 2791 | Some(user) => avatar(palette, user, px(20.), text(10.), &chat.avatars), |
| 2839 | - None => badge(palette, &message.user_id, username, px(20.), text(10.)).rounded_full(), | 2792 | + None => badge(palette, message.user_id, username, px(20.), text(10.)).rounded_full(), |
| 2840 | }) | 2793 | }) |
| 2841 | .child( | 2794 | .child( |
| 2842 | div() | 2795 | div() |
| 2843 | .id(format!("author_name_{}", message.id)) | 2796 | .id(format!("author_name_{}", message.id)) |
| 2844 | .font_weight(FontWeight::SEMIBOLD) | 2797 | .font_weight(FontWeight::SEMIBOLD) |
| 2845 | - .text_color(palette.tinted(&message.user_id)) | 2798 | + .text_color(palette.tinted(message.user_id)) |
| 2846 | .when(author.is_some(), |this| { | 2799 | .when(author.is_some(), |this| { |
| 2847 | this.hover(|style| style.underline()) | 2800 | this.hover(|style| style.underline()) |
| 2848 | }) | 2801 | }) |
| @@ -2894,7 +2847,7 @@ fn render_message( | |||
| 2894 | div() | 2847 | div() |
| 2895 | .text_size(text(12.)) | 2848 | .text_size(text(12.)) |
| 2896 | .text_color(palette.muted) | 2849 | .text_color(palette.muted) |
| 2897 | - .child(id_time(&message.id, CLOCK)), | 2850 | + .child(millis_time(message.created_at, CLOCK)), |
| 2898 | ), | 2851 | ), |
| 2899 | ) | 2852 | ) |
| 2900 | }) | 2853 | }) |
| @@ -2978,7 +2931,7 @@ fn render_message( | |||
| 2978 | })), | 2931 | })), |
| 2979 | ) | 2932 | ) |
| 2980 | .children( | 2933 | .children( |
| 2981 | - (chat.report == Some(ReportTarget::Message(message.id.clone()))) | 2934 | + (chat.report == Some(ReportTarget::Message(message.id))) |
| 2982 | .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)), | 2935 | .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)), |
| 2983 | ); | 2936 | ); |
| 2984 | 2937 | ||
| @@ -2986,7 +2939,7 @@ fn render_message( | |||
| 2986 | return row.into_any_element(); | 2939 | return row.into_any_element(); |
| 2987 | } | 2940 | } |
| 2988 | 2941 | ||
| 2989 | - let message_id = message.id.clone(); | 2942 | + let message_id = message.id; |
| 2990 | let select_entity = entity.clone(); | 2943 | let select_entity = entity.clone(); |
| 2991 | let mark_line = if first { | 2944 | let mark_line = if first { |
| 2992 | div().h(px(20.)) | 2945 | div().h(px(20.)) |
| @@ -3006,7 +2959,7 @@ fn render_message( | |||
| 3006 | .hover(|style| style.bg(palette.hover.opacity(0.5))) | 2959 | .hover(|style| style.bg(palette.hover.opacity(0.5))) |
| 3007 | .when(selected, |this| this.bg(palette.hover)) | 2960 | .when(selected, |this| this.bg(palette.hover)) |
| 3008 | .on_click(move |_, _, cx| { | 2961 | .on_click(move |_, _, cx| { |
| 3009 | - select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx)); | 2962 | + select_entity.update(cx, |yumush, cx| yumush.toggle_select(message_id, cx)); |
| 3010 | }) | 2963 | }) |
| 3011 | .child( | 2964 | .child( |
| 3012 | mark_line | 2965 | mark_line |
crates/client/src/gui/community_settings.rsmodified+26 -37
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::{collections::HashMap, sync::Arc}; | 2 | use std::{collections::HashMap, sync::Arc}; |
| 2 | 3 | ||
| 3 | use crate::net::Fail; | 4 | use crate::net::Fail; |
| @@ -25,7 +26,7 @@ use gpui_kit::{ | |||
| 25 | use super::{ | 26 | use super::{ |
| 26 | Palette, STAMP, Yumush, avatar, | 27 | Palette, STAMP, Yumush, avatar, |
| 27 | chat::View, | 28 | chat::View, |
| 28 | - clickable, community_icon, entity_action, id_time, notify_error, | 29 | + clickable, community_icon, entity_action, millis_time, notify_error, |
| 29 | profile::user_link, | 30 | profile::user_link, |
| 30 | settings_page::{ | 31 | settings_page::{ |
| 31 | Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, | 32 | Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, |
| @@ -140,12 +141,7 @@ impl Yumush { | |||
| 140 | palette, | 141 | palette, |
| 141 | vec![row( | 142 | vec![row( |
| 142 | "Voice", | 143 | "Voice", |
| 143 | - voice_control( | 144 | + voice_control(entity, community.id, community.voice_enabled, palette), |
| 144 | - entity, | ||
| 145 | - community.id.clone(), | ||
| 146 | - community.voice_enabled, | ||
| 147 | - palette, | ||
| 148 | - ), | ||
| 149 | )], | 145 | )], |
| 150 | ) | 146 | ) |
| 151 | .into_any_element(), | 147 | .into_any_element(), |
| @@ -186,7 +182,7 @@ impl Yumush { | |||
| 186 | if let Some(community) = community.filter(|_| permission::can_leave(actor)) { | 182 | if let Some(community) = community.filter(|_| permission::can_leave(actor)) { |
| 187 | danger.push(row( | 183 | danger.push(row( |
| 188 | "Leave community", | 184 | "Leave community", |
| 189 | - leave_control(entity, community.id.clone(), palette), | 185 | + leave_control(entity, community.id, palette), |
| 190 | )); | 186 | )); |
| 191 | } | 187 | } |
| 192 | if permission::can_delete_community(actor) { | 188 | if permission::can_delete_community(actor) { |
| @@ -210,7 +206,7 @@ impl Yumush { | |||
| 210 | 206 | ||
| 211 | fn set_community_voice( | 207 | fn set_community_voice( |
| 212 | &mut self, | 208 | &mut self, |
| 213 | - community_id: String, | 209 | + community_id: Id, |
| 214 | enabled: bool, | 210 | enabled: bool, |
| 215 | window: &mut Window, | 211 | window: &mut Window, |
| 216 | cx: &mut Context<Self>, | 212 | cx: &mut Context<Self>, |
| @@ -230,7 +226,7 @@ impl Yumush { | |||
| 230 | } | 226 | } |
| 231 | 227 | ||
| 232 | pub(super) fn save_community_name(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 228 | pub(super) fn save_community_name(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 233 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 229 | + let Some(community_id) = self.chat.selected_community_id else { |
| 234 | return; | 230 | return; |
| 235 | }; | 231 | }; |
| 236 | let name = self | 232 | let name = self |
| @@ -257,7 +253,7 @@ impl Yumush { | |||
| 257 | } | 253 | } |
| 258 | 254 | ||
| 259 | fn upload_community_picture(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 255 | fn upload_community_picture(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 260 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 256 | + let Some(community_id) = self.chat.selected_community_id else { |
| 261 | return; | 257 | return; |
| 262 | }; | 258 | }; |
| 263 | let picked = picked_avatar(cx, self.max_avatar_bytes()); | 259 | let picked = picked_avatar(cx, self.max_avatar_bytes()); |
| @@ -284,7 +280,7 @@ impl Yumush { | |||
| 284 | } | 280 | } |
| 285 | 281 | ||
| 286 | fn remove_community_picture(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 282 | fn remove_community_picture(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 287 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 283 | + let Some(community_id) = self.chat.selected_community_id else { |
| 288 | return; | 284 | return; |
| 289 | }; | 285 | }; |
| 290 | let network = self.network.clone(); | 286 | let network = self.network.clone(); |
| @@ -305,19 +301,17 @@ impl Yumush { | |||
| 305 | if !self.confirm_delete(cx) { | 301 | if !self.confirm_delete(cx) { |
| 306 | return; | 302 | return; |
| 307 | } | 303 | } |
| 308 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 304 | + let Some(community_id) = self.chat.selected_community_id else { |
| 309 | return; | 305 | return; |
| 310 | }; | 306 | }; |
| 311 | let network = self.network.clone(); | 307 | let network = self.network.clone(); |
| 312 | 308 | ||
| 313 | cx.spawn_in(window, async move |this, cx| { | 309 | cx.spawn_in(window, async move |this, cx| { |
| 314 | - let call = DeleteCommunity { | 310 | + let call = DeleteCommunity { community_id }; |
| 315 | - community_id: community_id.clone(), | ||
| 316 | - }; | ||
| 317 | match network.call(call).await { | 311 | match network.call(call).await { |
| 318 | Ok(()) => { | 312 | Ok(()) => { |
| 319 | let _ = this.update_in(cx, |yumush, window, cx| { | 313 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 320 | - yumush.chat.remove_community(&community_id); | 314 | + yumush.chat.remove_community(community_id); |
| 321 | yumush.show_view(View::Chat, window, cx); | 315 | yumush.show_view(View::Chat, window, cx); |
| 322 | }); | 316 | }); |
| 323 | } | 317 | } |
| @@ -327,17 +321,16 @@ impl Yumush { | |||
| 327 | .detach(); | 321 | .detach(); |
| 328 | } | 322 | } |
| 329 | 323 | ||
| 330 | - pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context<Self>) { | 324 | + pub(super) fn unban(&self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 331 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 325 | + let Some(community_id) = self.chat.selected_community_id else { |
| 332 | return; | 326 | return; |
| 333 | }; | 327 | }; |
| 334 | let network = self.network.clone(); | 328 | let network = self.network.clone(); |
| 335 | - let user_id = user_id.to_string(); | ||
| 336 | 329 | ||
| 337 | cx.spawn_in(window, async move |this, cx| { | 330 | cx.spawn_in(window, async move |this, cx| { |
| 338 | let call = Unban { | 331 | let call = Unban { |
| 339 | community_id, | 332 | community_id, |
| 340 | - user_id: user_id.clone(), | 333 | + user_id, |
| 341 | }; | 334 | }; |
| 342 | match network.call(call).await { | 335 | match network.call(call).await { |
| 343 | Ok(()) => { | 336 | Ok(()) => { |
| @@ -382,7 +375,7 @@ impl Yumush { | |||
| 382 | } | 375 | } |
| 383 | 376 | ||
| 384 | fn open_logs(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 377 | fn open_logs(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 385 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 378 | + let Some(community_id) = self.chat.selected_community_id else { |
| 386 | return; | 379 | return; |
| 387 | }; | 380 | }; |
| 388 | self.show_logs(community_id, window, cx); | 381 | self.show_logs(community_id, window, cx); |
| @@ -390,7 +383,7 @@ impl Yumush { | |||
| 390 | 383 | ||
| 391 | pub(super) fn show_logs( | 384 | pub(super) fn show_logs( |
| 392 | &mut self, | 385 | &mut self, |
| 393 | - community_id: String, | 386 | + community_id: Id, |
| 394 | window: &mut Window, | 387 | window: &mut Window, |
| 395 | cx: &mut Context<Self>, | 388 | cx: &mut Context<Self>, |
| 396 | ) { | 389 | ) { |
| @@ -434,7 +427,7 @@ impl Yumush { | |||
| 434 | cx.notify(); | 427 | cx.notify(); |
| 435 | } | 428 | } |
| 436 | 429 | ||
| 437 | - fn load_logs(&self, community_id: String, window: &mut Window, cx: &mut Context<Self>) { | 430 | + fn load_logs(&self, community_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 438 | let network = self.network.clone(); | 431 | let network = self.network.clone(); |
| 439 | 432 | ||
| 440 | cx.spawn_in(window, async move |this, cx| { | 433 | cx.spawn_in(window, async move |this, cx| { |
| @@ -466,7 +459,7 @@ impl Yumush { | |||
| 466 | 459 | ||
| 467 | fn voice_control( | 460 | fn voice_control( |
| 468 | entity: &Entity<Yumush>, | 461 | entity: &Entity<Yumush>, |
| 469 | - community_id: String, | 462 | + community_id: Id, |
| 470 | enabled: bool, | 463 | enabled: bool, |
| 471 | palette: Palette, | 464 | palette: Palette, |
| 472 | ) -> impl IntoElement { | 465 | ) -> impl IntoElement { |
| @@ -478,7 +471,7 @@ fn voice_control( | |||
| 478 | palette.text, | 471 | palette.text, |
| 479 | move |window, cx| { | 472 | move |window, cx| { |
| 480 | entity.update(cx, |yumush, cx| { | 473 | entity.update(cx, |yumush, cx| { |
| 481 | - yumush.set_community_voice(community_id.clone(), !enabled, window, cx) | 474 | + yumush.set_community_voice(community_id, !enabled, window, cx) |
| 482 | }); | 475 | }); |
| 483 | }, | 476 | }, |
| 484 | ) | 477 | ) |
| @@ -622,7 +615,7 @@ fn log_text(entry: &LogEntry) -> String { | |||
| 622 | } | 615 | } |
| 623 | } | 616 | } |
| 624 | 617 | ||
| 625 | -fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap<String, Arc<Image>>) -> Div { | 618 | +fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap<Id, Arc<Image>>) -> Div { |
| 626 | div() | 619 | div() |
| 627 | .min_h(px(40.)) | 620 | .min_h(px(40.)) |
| 628 | .px(px(12.)) | 621 | .px(px(12.)) |
| @@ -641,15 +634,11 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap<String, Arc<Ima | |||
| 641 | .flex_shrink_0() | 634 | .flex_shrink_0() |
| 642 | .text_size(text(11.)) | 635 | .text_size(text(11.)) |
| 643 | .text_color(palette.muted) | 636 | .text_color(palette.muted) |
| 644 | - .child(id_time(&entry.id, STAMP)), | 637 | + .child(millis_time(entry.created_at, STAMP)), |
| 645 | ) | 638 | ) |
| 646 | } | 639 | } |
| 647 | 640 | ||
| 648 | -fn leave_control( | 641 | +fn leave_control(entity: &Entity<Yumush>, community_id: Id, palette: Palette) -> impl IntoElement { |
| 649 | - entity: &Entity<Yumush>, | ||
| 650 | - community_id: String, | ||
| 651 | - palette: Palette, | ||
| 652 | -) -> impl IntoElement { | ||
| 653 | let entity = entity.clone(); | 642 | let entity = entity.clone(); |
| 654 | 643 | ||
| 655 | small_button( | 644 | small_button( |
| @@ -658,7 +647,7 @@ fn leave_control( | |||
| 658 | palette.danger, | 647 | palette.danger, |
| 659 | move |window, cx| { | 648 | move |window, cx| { |
| 660 | entity.update(cx, |yumush, cx| { | 649 | entity.update(cx, |yumush, cx| { |
| 661 | - yumush.leave_community(community_id.clone(), window, cx) | 650 | + yumush.leave_community(community_id, window, cx) |
| 662 | }); | 651 | }); |
| 663 | }, | 652 | }, |
| 664 | ) | 653 | ) |
| @@ -671,11 +660,11 @@ fn ban_row( | |||
| 671 | ban: &Ban, | 660 | ban: &Ban, |
| 672 | entity: &Entity<Yumush>, | 661 | entity: &Entity<Yumush>, |
| 673 | palette: Palette, | 662 | palette: Palette, |
| 674 | - avatars: &HashMap<String, Arc<Image>>, | 663 | + avatars: &HashMap<Id, Arc<Image>>, |
| 675 | ) -> Div { | 664 | ) -> Div { |
| 676 | let entity = entity.clone(); | 665 | let entity = entity.clone(); |
| 677 | let user = &ban.user; | 666 | let user = &ban.user; |
| 678 | - let user_id = user.id.clone(); | 667 | + let user_id = user.id; |
| 679 | 668 | ||
| 680 | div() | 669 | div() |
| 681 | .h(px(48.)) | 670 | .h(px(48.)) |
| @@ -711,7 +700,7 @@ fn ban_row( | |||
| 711 | ) | 700 | ) |
| 712 | .child( | 701 | .child( |
| 713 | clickable(format!("unban_{}", user.id), palette, move |window, cx| { | 702 | clickable(format!("unban_{}", user.id), palette, move |window, cx| { |
| 714 | - entity.update(cx, |yumush, cx| yumush.unban(&user_id, window, cx)); | 703 | + entity.update(cx, |yumush, cx| yumush.unban(user_id, window, cx)); |
| 715 | }) | 704 | }) |
| 716 | .h(px(28.)) | 705 | .h(px(28.)) |
| 717 | .px(px(8.)) | 706 | .px(px(8.)) |
crates/client/src/gui/composer.rsmodified+35 -43
| @@ -1,5 +1,6 @@ | |||
| 1 | use super::text; | 1 | use super::text; |
| 2 | use super::widget::{compact_field, icon_button, panel, spawn_done}; | 2 | use super::widget::{compact_field, icon_button, panel, spawn_done}; |
| 3 | +use common::model::Id; | ||
| 3 | use std::time::{Duration, Instant}; | 4 | use std::time::{Duration, Instant}; |
| 4 | 5 | ||
| 5 | use crate::net::Fail; | 6 | use crate::net::Fail; |
| @@ -57,9 +58,9 @@ fn shortcut_label(keys: &str) -> String { | |||
| 57 | 58 | ||
| 58 | #[derive(Debug, Clone, PartialEq, Eq)] | 59 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 59 | pub enum Composer { | 60 | pub enum Composer { |
| 60 | - Compose { reply: Option<String> }, | 61 | + Compose { reply: Option<Id> }, |
| 61 | - Edit { message_id: String }, | 62 | + Edit { message_id: Id }, |
| 62 | - Select { ids: Vec<String> }, | 63 | + Select { ids: Vec<Id> }, |
| 63 | } | 64 | } |
| 64 | 65 | ||
| 65 | const SLOW_TICK: Duration = Duration::from_secs(1); | 66 | const SLOW_TICK: Duration = Duration::from_secs(1); |
| @@ -72,17 +73,13 @@ pub fn mode_bar(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> Optio | |||
| 72 | match &chat.composer { | 73 | match &chat.composer { |
| 73 | Composer::Compose { | 74 | Composer::Compose { |
| 74 | reply: Some(message_id), | 75 | reply: Some(message_id), |
| 75 | - } => Some(reply_bar(chat, message_id, entity, palette).into_any_element()), | 76 | + } => Some(reply_bar(chat, *message_id, entity, palette).into_any_element()), |
| 76 | Composer::Edit { .. } => Some(edit_bar(entity, palette).into_any_element()), | 77 | Composer::Edit { .. } => Some(edit_bar(entity, palette).into_any_element()), |
| 77 | Composer::Compose { reply: None } | Composer::Select { .. } => None, | 78 | Composer::Compose { reply: None } | Composer::Select { .. } => None, |
| 78 | } | 79 | } |
| 79 | } | 80 | } |
| 80 | 81 | ||
| 81 | -pub fn selection_bar( | 82 | +pub fn selection_bar(ids: &[Id], entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { |
| 82 | - ids: &[String], | ||
| 83 | - entity: &Entity<Yumush>, | ||
| 84 | - palette: Palette, | ||
| 85 | -) -> impl IntoElement { | ||
| 86 | let count = ids.len(); | 83 | let count = ids.len(); |
| 87 | let selected = ids.to_vec(); | 84 | let selected = ids.to_vec(); |
| 88 | let forward_entity = entity.clone(); | 85 | let forward_entity = entity.clone(); |
| @@ -131,7 +128,7 @@ fn bar(palette: Palette) -> Div { | |||
| 131 | 128 | ||
| 132 | fn reply_bar( | 129 | fn reply_bar( |
| 133 | chat: &Chat, | 130 | chat: &Chat, |
| 134 | - message_id: &str, | 131 | + message_id: Id, |
| 135 | entity: &Entity<Yumush>, | 132 | entity: &Entity<Yumush>, |
| 136 | palette: Palette, | 133 | palette: Palette, |
| 137 | ) -> impl IntoElement { | 134 | ) -> impl IntoElement { |
| @@ -140,11 +137,13 @@ fn reply_bar( | |||
| 140 | .iter() | 137 | .iter() |
| 141 | .find(|message| message.id == message_id); | 138 | .find(|message| message.id == message_id); |
| 142 | let author = message | 139 | let author = message |
| 143 | - .and_then(|message| chat.author(&message.user_id)) | 140 | + .and_then(|message| chat.author(message.user_id)) |
| 144 | .map_or("unknown", |user| user.username.as_str()) | 141 | .map_or("unknown", |user| user.username.as_str()) |
| 145 | .to_string(); | 142 | .to_string(); |
| 146 | let quote = message | 143 | let quote = message |
| 147 | - .map(|message| super::message_actions::quote_text(&message.body, message.attachments.len())) | 144 | + .map(|message| { |
| 145 | + super::message_actions::quote_text(&message.body, message.attachments.len() as u32) | ||
| 146 | + }) | ||
| 148 | .unwrap_or_default(); | 147 | .unwrap_or_default(); |
| 149 | 148 | ||
| 150 | bar(palette) | 149 | bar(palette) |
| @@ -210,7 +209,7 @@ impl Yumush { | |||
| 210 | } | 209 | } |
| 211 | 210 | ||
| 212 | pub(super) fn send_typing(&mut self, cx: &mut Context<Self>) { | 211 | pub(super) fn send_typing(&mut self, cx: &mut Context<Self>) { |
| 213 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 212 | + let Some(community_id) = self.chat.selected_community_id else { |
| 214 | return; | 213 | return; |
| 215 | }; | 214 | }; |
| 216 | if self | 215 | if self |
| @@ -228,9 +227,7 @@ impl Yumush { | |||
| 228 | { | 227 | { |
| 229 | return; | 228 | return; |
| 230 | } | 229 | } |
| 231 | - self.chat | 230 | + self.chat.typing_sent.insert(community_id, Instant::now()); |
| 232 | - .typing_sent | ||
| 233 | - .insert(community_id.clone(), Instant::now()); | ||
| 234 | let network = self.network.clone(); | 231 | let network = self.network.clone(); |
| 235 | cx.spawn(async move |_, _| { | 232 | cx.spawn(async move |_, _| { |
| 236 | let _ = network.call(Typing { community_id }).await; | 233 | let _ = network.call(Typing { community_id }).await; |
| @@ -240,18 +237,18 @@ impl Yumush { | |||
| 240 | 237 | ||
| 241 | fn create_message( | 238 | fn create_message( |
| 242 | &mut self, | 239 | &mut self, |
| 243 | - reply: Option<String>, | 240 | + reply: Option<Id>, |
| 244 | body: String, | 241 | body: String, |
| 245 | input: &Entity<InputState>, | 242 | input: &Entity<InputState>, |
| 246 | window: &mut Window, | 243 | window: &mut Window, |
| 247 | cx: &mut Context<Self>, | 244 | cx: &mut Context<Self>, |
| 248 | ) { | 245 | ) { |
| 249 | - let attachments: Vec<String> = self | 246 | + let attachments: Vec<Id> = self |
| 250 | .chat | 247 | .chat |
| 251 | .media | 248 | .media |
| 252 | .pending | 249 | .pending |
| 253 | .iter() | 250 | .iter() |
| 254 | - .map(|attachment| attachment.id.clone()) | 251 | + .map(|attachment| attachment.id) |
| 255 | .collect(); | 252 | .collect(); |
| 256 | 253 | ||
| 257 | if self.chat.slow_seconds().is_some() { | 254 | if self.chat.slow_seconds().is_some() { |
| @@ -262,7 +259,7 @@ impl Yumush { | |||
| 262 | window.push_notification(Notification::error(error.to_string()), cx); | 259 | window.push_notification(Notification::error(error.to_string()), cx); |
| 263 | return; | 260 | return; |
| 264 | } | 261 | } |
| 265 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 262 | + let Some(community_id) = self.chat.selected_community_id else { |
| 266 | window.push_notification(Notification::error("No Community Selected"), cx); | 263 | window.push_notification(Notification::error("No Community Selected"), cx); |
| 267 | return; | 264 | return; |
| 268 | }; | 265 | }; |
| @@ -274,7 +271,7 @@ impl Yumush { | |||
| 274 | cx.spawn_in(window, async move |this, cx| { | 271 | cx.spawn_in(window, async move |this, cx| { |
| 275 | match network | 272 | match network |
| 276 | .call(CreateMessage { | 273 | .call(CreateMessage { |
| 277 | - community_id: community_id.clone(), | 274 | + community_id, |
| 278 | body: body.clone(), | 275 | body: body.clone(), |
| 279 | attachments, | 276 | attachments, |
| 280 | reply_to: reply, | 277 | reply_to: reply, |
| @@ -286,13 +283,13 @@ impl Yumush { | |||
| 286 | retry_after_seconds, | 283 | retry_after_seconds, |
| 287 | })) => { | 284 | })) => { |
| 288 | let _ = this.update_in(cx, |yumush, window, cx| { | 285 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 289 | - yumush.restore_message(&restore, &community_id, body, pending, window, cx); | 286 | + yumush.restore_message(&restore, community_id, body, pending, window, cx); |
| 290 | yumush.slow_down(retry_after_seconds, window, cx) | 287 | yumush.slow_down(retry_after_seconds, window, cx) |
| 291 | }); | 288 | }); |
| 292 | } | 289 | } |
| 293 | Err(error) => { | 290 | Err(error) => { |
| 294 | let _ = this.update_in(cx, |yumush, window, cx| { | 291 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 295 | - yumush.restore_message(&restore, &community_id, body, pending, window, cx) | 292 | + yumush.restore_message(&restore, community_id, body, pending, window, cx) |
| 296 | }); | 293 | }); |
| 297 | notify_error(&this, cx, error); | 294 | notify_error(&this, cx, error); |
| 298 | } | 295 | } |
| @@ -308,14 +305,14 @@ impl Yumush { | |||
| 308 | fn restore_message( | 305 | fn restore_message( |
| 309 | &mut self, | 306 | &mut self, |
| 310 | input: &Entity<InputState>, | 307 | input: &Entity<InputState>, |
| 311 | - community_id: &str, | 308 | + community_id: Id, |
| 312 | body: String, | 309 | body: String, |
| 313 | pending: Vec<Attachment>, | 310 | pending: Vec<Attachment>, |
| 314 | window: &mut Window, | 311 | window: &mut Window, |
| 315 | cx: &mut Context<Self>, | 312 | cx: &mut Context<Self>, |
| 316 | ) { | 313 | ) { |
| 317 | - if self.chat.selected_community_id.as_deref() != Some(community_id) { | 314 | + if self.chat.selected_community_id != Some(community_id) { |
| 318 | - self.chat.drafts.insert(community_id.to_string(), body); | 315 | + self.chat.drafts.insert(community_id, body); |
| 319 | return; | 316 | return; |
| 320 | } | 317 | } |
| 321 | if input.read(cx).text().len() == 0 { | 318 | if input.read(cx).text().len() == 0 { |
| @@ -347,7 +344,7 @@ impl Yumush { | |||
| 347 | 344 | ||
| 348 | fn update_message( | 345 | fn update_message( |
| 349 | &mut self, | 346 | &mut self, |
| 350 | - message_id: String, | 347 | + message_id: Id, |
| 351 | body: String, | 348 | body: String, |
| 352 | input: &Entity<InputState>, | 349 | input: &Entity<InputState>, |
| 353 | window: &mut Window, | 350 | window: &mut Window, |
| @@ -363,7 +360,7 @@ impl Yumush { | |||
| 363 | cx.spawn_in(window, async move |this, cx| { | 360 | cx.spawn_in(window, async move |this, cx| { |
| 364 | if let Err(error) = network | 361 | if let Err(error) = network |
| 365 | .call(UpdateMessage { | 362 | .call(UpdateMessage { |
| 366 | - message_id: message_id.clone(), | 363 | + message_id, |
| 367 | body: body.clone(), | 364 | body: body.clone(), |
| 368 | }) | 365 | }) |
| 369 | .await | 366 | .await |
| @@ -386,7 +383,7 @@ impl Yumush { | |||
| 386 | } | 383 | } |
| 387 | 384 | ||
| 388 | pub(super) fn save_draft(&mut self, cx: &mut Context<Self>) { | 385 | pub(super) fn save_draft(&mut self, cx: &mut Context<Self>) { |
| 389 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 386 | + let Some(community_id) = self.chat.selected_community_id else { |
| 390 | return; | 387 | return; |
| 391 | }; | 388 | }; |
| 392 | let text = self.chat.message_input.read(cx).text().to_string(); | 389 | let text = self.chat.message_input.read(cx).text().to_string(); |
| @@ -399,14 +396,14 @@ impl Yumush { | |||
| 399 | 396 | ||
| 400 | pub(super) fn restore_draft( | 397 | pub(super) fn restore_draft( |
| 401 | &mut self, | 398 | &mut self, |
| 402 | - community_id: &str, | 399 | + community_id: Id, |
| 403 | window: &mut Window, | 400 | window: &mut Window, |
| 404 | cx: &mut Context<Self>, | 401 | cx: &mut Context<Self>, |
| 405 | ) { | 402 | ) { |
| 406 | let text = self | 403 | let text = self |
| 407 | .chat | 404 | .chat |
| 408 | .drafts | 405 | .drafts |
| 409 | - .get(community_id) | 406 | + .get(&community_id) |
| 410 | .cloned() | 407 | .cloned() |
| 411 | .unwrap_or_default(); | 408 | .unwrap_or_default(); |
| 412 | self.chat | 409 | self.chat |
| @@ -414,12 +411,7 @@ impl Yumush { | |||
| 414 | .update(cx, |input, cx| input.set_value(text, window, cx)); | 411 | .update(cx, |input, cx| input.set_value(text, window, cx)); |
| 415 | } | 412 | } |
| 416 | 413 | ||
| 417 | - pub(super) fn reply( | 414 | + pub(super) fn reply(&mut self, message_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 418 | - &mut self, | ||
| 419 | - message_id: String, | ||
| 420 | - window: &mut Window, | ||
| 421 | - cx: &mut Context<Self>, | ||
| 422 | - ) { | ||
| 423 | self.chat.composer = Composer::Compose { | 415 | self.chat.composer = Composer::Compose { |
| 424 | reply: Some(message_id), | 416 | reply: Some(message_id), |
| 425 | }; | 417 | }; |
| @@ -427,7 +419,7 @@ impl Yumush { | |||
| 427 | cx.notify(); | 419 | cx.notify(); |
| 428 | } | 420 | } |
| 429 | 421 | ||
| 430 | - pub(super) fn edit(&mut self, message_id: String, window: &mut Window, cx: &mut Context<Self>) { | 422 | + pub(super) fn edit(&mut self, message_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 431 | let Some(body) = self | 423 | let Some(body) = self |
| 432 | .chat | 424 | .chat |
| 433 | .messages | 425 | .messages |
| @@ -448,7 +440,7 @@ impl Yumush { | |||
| 448 | 440 | ||
| 449 | pub(super) fn start_select( | 441 | pub(super) fn start_select( |
| 450 | &mut self, | 442 | &mut self, |
| 451 | - message_id: String, | 443 | + message_id: Id, |
| 452 | window: &mut Window, | 444 | window: &mut Window, |
| 453 | cx: &mut Context<Self>, | 445 | cx: &mut Context<Self>, |
| 454 | ) { | 446 | ) { |
| @@ -459,14 +451,14 @@ impl Yumush { | |||
| 459 | cx.notify(); | 451 | cx.notify(); |
| 460 | } | 452 | } |
| 461 | 453 | ||
| 462 | - pub(super) fn toggle_select(&mut self, message_id: &str, cx: &mut Context<Self>) { | 454 | + pub(super) fn toggle_select(&mut self, message_id: Id, cx: &mut Context<Self>) { |
| 463 | let Composer::Select { ids } = &mut self.chat.composer else { | 455 | let Composer::Select { ids } = &mut self.chat.composer else { |
| 464 | return; | 456 | return; |
| 465 | }; | 457 | }; |
| 466 | - if let Some(index) = ids.iter().position(|id| id == message_id) { | 458 | + if let Some(index) = ids.iter().position(|id| *id == message_id) { |
| 467 | ids.remove(index); | 459 | ids.remove(index); |
| 468 | } else if ids.len() < MAXIMUM_FORWARD_MESSAGES { | 460 | } else if ids.len() < MAXIMUM_FORWARD_MESSAGES { |
| 469 | - ids.push(message_id.to_string()); | 461 | + ids.push(message_id); |
| 470 | } | 462 | } |
| 471 | cx.notify(); | 463 | cx.notify(); |
| 472 | } | 464 | } |
| @@ -690,7 +682,7 @@ impl Yumush { | |||
| 690 | } | 682 | } |
| 691 | 683 | ||
| 692 | pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool { | 684 | pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool { |
| 693 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 685 | + let Some(community_id) = self.chat.selected_community_id else { |
| 694 | return false; | 686 | return false; |
| 695 | }; | 687 | }; |
| 696 | let question = self.chat.poll_question.read(cx).text().to_string(); | 688 | let question = self.chat.poll_question.read(cx).text().to_string(); |
crates/client/src/gui/forward.rsmodified+9 -9
| @@ -1,5 +1,6 @@ | |||
| 1 | use super::text; | 1 | use super::text; |
| 2 | use common::call::ForwardMessages; | 2 | use common::call::ForwardMessages; |
| 3 | +use common::model::Id; | ||
| 3 | use gpui_kit::{ | 4 | use gpui_kit::{ |
| 4 | AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, | 5 | AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, |
| 5 | StatefulInteractiveElement, Styled, Window, | 6 | StatefulInteractiveElement, Styled, Window, |
| @@ -20,7 +21,7 @@ use super::{ | |||
| 20 | 21 | ||
| 21 | pub struct Forward { | 22 | pub struct Forward { |
| 22 | yumush: Entity<Yumush>, | 23 | yumush: Entity<Yumush>, |
| 23 | - selected: Vec<String>, | 24 | + selected: Vec<Id>, |
| 24 | filter: Entity<InputState>, | 25 | filter: Entity<InputState>, |
| 25 | keep_authors: bool, | 26 | keep_authors: bool, |
| 26 | } | 27 | } |
| @@ -28,7 +29,7 @@ pub struct Forward { | |||
| 28 | impl Forward { | 29 | impl Forward { |
| 29 | fn new( | 30 | fn new( |
| 30 | yumush: Entity<Yumush>, | 31 | yumush: Entity<Yumush>, |
| 31 | - selected: Vec<String>, | 32 | + selected: Vec<Id>, |
| 32 | window: &mut Window, | 33 | window: &mut Window, |
| 33 | cx: &mut Context<Self>, | 34 | cx: &mut Context<Self>, |
| 34 | ) -> Self { | 35 | ) -> Self { |
| @@ -69,12 +70,11 @@ impl Render for Forward { | |||
| 69 | .filter(|community| community_name(community).to_lowercase().contains(&query)) | 70 | .filter(|community| community_name(community).to_lowercase().contains(&query)) |
| 70 | .enumerate() | 71 | .enumerate() |
| 71 | .map(|(index, community)| { | 72 | .map(|(index, community)| { |
| 72 | - let community_id = community.id.clone(); | 73 | + let community_id = community.id; |
| 73 | let selected = self.selected.clone(); | 74 | let selected = self.selected.clone(); |
| 74 | let forward_entity = self.yumush.clone(); | 75 | let forward_entity = self.yumush.clone(); |
| 75 | 76 | ||
| 76 | clickable(("forward_to", index), palette, move |window, cx| { | 77 | clickable(("forward_to", index), palette, move |window, cx| { |
| 77 | - let community_id = community_id.clone(); | ||
| 78 | let selected = selected.clone(); | 78 | let selected = selected.clone(); |
| 79 | forward_entity.update(cx, |yumush, cx| { | 79 | forward_entity.update(cx, |yumush, cx| { |
| 80 | yumush.forward_to(selected, community_id, keep_authors, window, cx) | 80 | yumush.forward_to(selected, community_id, keep_authors, window, cx) |
| @@ -130,7 +130,7 @@ impl Render for Forward { | |||
| 130 | impl Yumush { | 130 | impl Yumush { |
| 131 | pub(super) fn open_forward( | 131 | pub(super) fn open_forward( |
| 132 | &mut self, | 132 | &mut self, |
| 133 | - selected: Vec<String>, | 133 | + selected: Vec<Id>, |
| 134 | window: &mut Window, | 134 | window: &mut Window, |
| 135 | cx: &mut Context<Self>, | 135 | cx: &mut Context<Self>, |
| 136 | ) { | 136 | ) { |
| @@ -147,8 +147,8 @@ impl Yumush { | |||
| 147 | 147 | ||
| 148 | pub(super) fn forward_to( | 148 | pub(super) fn forward_to( |
| 149 | &mut self, | 149 | &mut self, |
| 150 | - selected: Vec<String>, | 150 | + selected: Vec<Id>, |
| 151 | - community_id: String, | 151 | + community_id: Id, |
| 152 | keep_authors: bool, | 152 | keep_authors: bool, |
| 153 | window: &mut Window, | 153 | window: &mut Window, |
| 154 | cx: &mut Context<Self>, | 154 | cx: &mut Context<Self>, |
| @@ -158,12 +158,12 @@ impl Yumush { | |||
| 158 | self.chat.composer = Composer::Compose { reply: None }; | 158 | self.chat.composer = Composer::Compose { reply: None }; |
| 159 | } | 159 | } |
| 160 | 160 | ||
| 161 | - let ids: Vec<String> = self | 161 | + let ids: Vec<Id> = self |
| 162 | .chat | 162 | .chat |
| 163 | .messages | 163 | .messages |
| 164 | .iter() | 164 | .iter() |
| 165 | .filter(|message| selected.contains(&message.id)) | 165 | .filter(|message| selected.contains(&message.id)) |
| 166 | - .map(|message| message.id.clone()) | 166 | + .map(|message| message.id) |
| 167 | .collect(); | 167 | .collect(); |
| 168 | let network = self.network.clone(); | 168 | let network = self.network.clone(); |
| 169 | 169 | ||
crates/client/src/gui/media_view.rsmodified+25 -23
| @@ -1,4 +1,5 @@ | |||
| 1 | use super::text; | 1 | use super::text; |
| 2 | +use common::model::Id; | ||
| 2 | use std::{ | 3 | use std::{ |
| 3 | collections::{HashMap, HashSet}, | 4 | collections::{HashMap, HashSet}, |
| 4 | path::PathBuf, | 5 | path::PathBuf, |
| @@ -55,7 +56,7 @@ pub enum PlayState { | |||
| 55 | } | 56 | } |
| 56 | 57 | ||
| 57 | pub struct Playing { | 58 | pub struct Playing { |
| 58 | - attachment_id: String, | 59 | + attachment_id: Id, |
| 59 | state: PlayState, | 60 | state: PlayState, |
| 60 | } | 61 | } |
| 61 | 62 | ||
| @@ -64,10 +65,11 @@ pub struct Media { | |||
| 64 | pub pending: Vec<Attachment>, | 65 | pub pending: Vec<Attachment>, |
| 65 | pub(super) uploading: usize, | 66 | pub(super) uploading: usize, |
| 66 | pub(super) voice_note: VoiceNote, | 67 | pub(super) voice_note: VoiceNote, |
| 67 | - thumbnails: HashMap<String, Arc<Image>>, | 68 | + thumbnails: HashMap<Id, Arc<Image>>, |
| 68 | - waveforms: HashMap<String, note::Waveform>, | 69 | + waveforms: HashMap<Id, note::Waveform>, |
| 69 | embeds: HashMap<String, LoadedEmbed>, | 70 | embeds: HashMap<String, LoadedEmbed>, |
| 70 | - requested: HashSet<String>, | 71 | + requested: HashSet<Id>, |
| 72 | + requested_links: HashSet<String>, | ||
| 71 | playing: Option<Playing>, | 73 | playing: Option<Playing>, |
| 72 | } | 74 | } |
| 73 | 75 | ||
| @@ -148,7 +150,7 @@ fn duration_secs(player: &Player) -> f32 { | |||
| 148 | pub(super) async fn upload_file( | 150 | pub(super) async fn upload_file( |
| 149 | this: &WeakEntity<Yumush>, | 151 | this: &WeakEntity<Yumush>, |
| 150 | network: &NetworkHandle, | 152 | network: &NetworkHandle, |
| 151 | - community_id: &str, | 153 | + community_id: Id, |
| 152 | path: PathBuf, | 154 | path: PathBuf, |
| 153 | maximum: Option<u64>, | 155 | maximum: Option<u64>, |
| 154 | cx: &mut AsyncWindowContext, | 156 | cx: &mut AsyncWindowContext, |
| @@ -179,8 +181,8 @@ impl Yumush { | |||
| 179 | for message in &self.chat.messages { | 181 | for message in &self.chat.messages { |
| 180 | let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages); | 182 | let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages); |
| 181 | for item in forwarded.clone() { | 183 | for item in forwarded.clone() { |
| 182 | - if let Some(avatar_id) = &item.avatar_id { | 184 | + if let Some(avatar_id) = item.avatar_id { |
| 183 | - avatars.push(avatar_id.clone()); | 185 | + avatars.push(avatar_id); |
| 184 | } | 186 | } |
| 185 | } | 187 | } |
| 186 | for attachment in message | 188 | for attachment in message |
| @@ -189,31 +191,31 @@ impl Yumush { | |||
| 189 | .chain(forwarded.flat_map(|item| &item.attachments)) | 191 | .chain(forwarded.flat_map(|item| &item.attachments)) |
| 190 | { | 192 | { |
| 191 | if attachment.kind == AttachmentKind::Image | 193 | if attachment.kind == AttachmentKind::Image |
| 192 | - && self.chat.media.requested.insert(attachment.id.clone()) | 194 | + && self.chat.media.requested.insert(attachment.id) |
| 193 | { | 195 | { |
| 194 | - thumbnails.push(attachment.id.clone()); | 196 | + thumbnails.push(attachment.id); |
| 195 | } | 197 | } |
| 196 | if note::is_voice_note(attachment) | 198 | if note::is_voice_note(attachment) |
| 197 | - && self.chat.media.requested.insert(attachment.id.clone()) | 199 | + && self.chat.media.requested.insert(attachment.id) |
| 198 | { | 200 | { |
| 199 | voices.push(attachment.clone()); | 201 | voices.push(attachment.clone()); |
| 200 | } | 202 | } |
| 201 | } | 203 | } |
| 202 | for url in embed::urls(&message.body) { | 204 | for url in embed::urls(&message.body) { |
| 203 | - if self.chat.media.requested.insert(url.clone()) { | 205 | + if self.chat.media.requested_links.insert(url.clone()) { |
| 204 | links.push(url); | 206 | links.push(url); |
| 205 | } | 207 | } |
| 206 | } | 208 | } |
| 207 | } | 209 | } |
| 208 | 210 | ||
| 209 | for avatar_id in avatars { | 211 | for avatar_id in avatars { |
| 210 | - self.request_avatar(&avatar_id, cx); | 212 | + self.request_avatar(avatar_id, cx); |
| 211 | } | 213 | } |
| 212 | 214 | ||
| 213 | for attachment_id in thumbnails { | 215 | for attachment_id in thumbnails { |
| 214 | let network = self.network.clone(); | 216 | let network = self.network.clone(); |
| 215 | cx.spawn(async move |this, cx| { | 217 | cx.spawn(async move |this, cx| { |
| 216 | - let Ok(bytes) = network.download_attachment(&attachment_id, true).await else { | 218 | + let Ok(bytes) = network.download_attachment(attachment_id, true).await else { |
| 217 | return; | 219 | return; |
| 218 | }; | 220 | }; |
| 219 | let _ = this.update(cx, |yumush, cx| { | 221 | let _ = this.update(cx, |yumush, cx| { |
| @@ -228,7 +230,7 @@ impl Yumush { | |||
| 228 | 230 | ||
| 229 | for attachment in voices { | 231 | for attachment in voices { |
| 230 | let fetched = self.fetch_file(&attachment, cx); | 232 | let fetched = self.fetch_file(&attachment, cx); |
| 231 | - let attachment_id = attachment.id.clone(); | 233 | + let attachment_id = attachment.id; |
| 232 | cx.spawn(async move |this, cx| { | 234 | cx.spawn(async move |this, cx| { |
| 233 | let Ok(path) = fetched.await else { | 235 | let Ok(path) = fetched.await else { |
| 234 | return; | 236 | return; |
| @@ -275,7 +277,7 @@ impl Yumush { | |||
| 275 | } | 277 | } |
| 276 | 278 | ||
| 277 | pub(super) fn attach_files(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 279 | pub(super) fn attach_files(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 278 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 280 | + let Some(community_id) = self.chat.selected_community_id else { |
| 279 | return; | 281 | return; |
| 280 | }; | 282 | }; |
| 281 | let picked = cx.prompt_for_paths(PathPromptOptions { | 283 | let picked = cx.prompt_for_paths(PathPromptOptions { |
| @@ -295,7 +297,7 @@ impl Yumush { | |||
| 295 | return; | 297 | return; |
| 296 | }; | 298 | }; |
| 297 | for path in paths { | 299 | for path in paths { |
| 298 | - let result = upload_file(&this, &network, &community_id, path, maximum, cx).await; | 300 | + let result = upload_file(&this, &network, community_id, path, maximum, cx).await; |
| 299 | let _ = this.update(cx, |yumush, cx| { | 301 | let _ = this.update(cx, |yumush, cx| { |
| 300 | if let Ok(attachment) = &result { | 302 | if let Ok(attachment) = &result { |
| 301 | yumush.chat.media.pending.push(attachment.clone()); | 303 | yumush.chat.media.pending.push(attachment.clone()); |
| @@ -310,7 +312,7 @@ impl Yumush { | |||
| 310 | .detach(); | 312 | .detach(); |
| 311 | } | 313 | } |
| 312 | 314 | ||
| 313 | - fn remove_pending(&mut self, attachment_id: &str, cx: &mut Context<Self>) { | 315 | + fn remove_pending(&mut self, attachment_id: Id, cx: &mut Context<Self>) { |
| 314 | self.chat | 316 | self.chat |
| 315 | .media | 317 | .media |
| 316 | .pending | 318 | .pending |
| @@ -330,7 +332,7 @@ impl Yumush { | |||
| 330 | if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) { | 332 | if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) { |
| 331 | return Ok(path); | 333 | return Ok(path); |
| 332 | } | 334 | } |
| 333 | - let bytes = network.download_attachment(&attachment.id, false).await?; | 335 | + let bytes = network.download_attachment(attachment.id, false).await?; |
| 334 | cx.background_executor() | 336 | cx.background_executor() |
| 335 | .spawn({ | 337 | .spawn({ |
| 336 | let path = path.clone(); | 338 | let path = path.clone(); |
| @@ -393,14 +395,14 @@ impl Yumush { | |||
| 393 | } | 395 | } |
| 394 | self.stop_playing(cx); | 396 | self.stop_playing(cx); |
| 395 | self.chat.media.playing = Some(Playing { | 397 | self.chat.media.playing = Some(Playing { |
| 396 | - attachment_id: attachment.id.clone(), | 398 | + attachment_id: attachment.id, |
| 397 | state: PlayState::Loading, | 399 | state: PlayState::Loading, |
| 398 | }); | 400 | }); |
| 399 | cx.notify(); | 401 | cx.notify(); |
| 400 | 402 | ||
| 401 | let fetched = self.fetch_file(attachment, cx); | 403 | let fetched = self.fetch_file(attachment, cx); |
| 402 | let choice = self.settings.voice.choice.clone(); | 404 | let choice = self.settings.voice.choice.clone(); |
| 403 | - let attachment_id = attachment.id.clone(); | 405 | + let attachment_id = attachment.id; |
| 404 | cx.spawn_in(window, async move |this, cx| { | 406 | cx.spawn_in(window, async move |this, cx| { |
| 405 | let opened = match fetched.await { | 407 | let opened = match fetched.await { |
| 406 | Ok(path) => cx | 408 | Ok(path) => cx |
| @@ -435,7 +437,7 @@ impl Yumush { | |||
| 435 | 437 | ||
| 436 | fn start_player( | 438 | fn start_player( |
| 437 | &mut self, | 439 | &mut self, |
| 438 | - attachment_id: String, | 440 | + attachment_id: Id, |
| 439 | player: Player, | 441 | player: Player, |
| 440 | window: &mut Window, | 442 | window: &mut Window, |
| 441 | cx: &mut Context<Self>, | 443 | cx: &mut Context<Self>, |
| @@ -878,7 +880,7 @@ pub fn pending_row( | |||
| 878 | .pb(px(8.)) | 880 | .pb(px(8.)) |
| 879 | .children(media.pending.iter().map(|attachment| { | 881 | .children(media.pending.iter().map(|attachment| { |
| 880 | let entity = entity.clone(); | 882 | let entity = entity.clone(); |
| 881 | - let attachment_id = attachment.id.clone(); | 883 | + let attachment_id = attachment.id; |
| 882 | div() | 884 | div() |
| 883 | .flex() | 885 | .flex() |
| 884 | .items_center() | 886 | .items_center() |
| @@ -901,7 +903,7 @@ pub fn pending_row( | |||
| 901 | palette, | 903 | palette, |
| 902 | move |_, cx| { | 904 | move |_, cx| { |
| 903 | entity.update(cx, |yumush, cx| { | 905 | entity.update(cx, |yumush, cx| { |
| 904 | - yumush.remove_pending(&attachment_id, cx) | 906 | + yumush.remove_pending(attachment_id, cx) |
| 905 | }) | 907 | }) |
| 906 | }, | 908 | }, |
| 907 | ) | 909 | ) |
crates/client/src/gui/message_actions.rsmodified+23 -27
| @@ -1,4 +1,5 @@ | |||
| 1 | use super::text; | 1 | use super::text; |
| 2 | +use common::model::Id; | ||
| 2 | use common::{ | 3 | use common::{ |
| 3 | call::{Pin, React, ReportMessage, ReportUser}, | 4 | call::{Pin, React, ReportMessage, ReportUser}, |
| 4 | constant::REACTIONS, | 5 | constant::REACTIONS, |
| @@ -23,7 +24,7 @@ use super::{ | |||
| 23 | chat::{Chat, ReportTarget}, | 24 | chat::{Chat, ReportTarget}, |
| 24 | clickable, | 25 | clickable, |
| 25 | composer::trigger_icon, | 26 | composer::trigger_icon, |
| 26 | - entity_action, id_time, notify_error, pop_in, primary_button, sidebar, | 27 | + entity_action, millis_time, notify_error, pop_in, primary_button, sidebar, |
| 27 | widget::{field, icon_button, panel, spawn_done}, | 28 | widget::{field, icon_button, panel, spawn_done}, |
| 28 | }; | 29 | }; |
| 29 | 30 | ||
| @@ -33,7 +34,7 @@ pub fn reactions( | |||
| 33 | entity: &Entity<Yumush>, | 34 | entity: &Entity<Yumush>, |
| 34 | palette: Palette, | 35 | palette: Palette, |
| 35 | ) -> impl IntoElement { | 36 | ) -> impl IntoElement { |
| 36 | - let me_id = me.map(|me| me.id.clone()); | 37 | + let me_id = me.map(|me| me.id); |
| 37 | 38 | ||
| 38 | div() | 39 | div() |
| 39 | .flex() | 40 | .flex() |
| @@ -44,7 +45,7 @@ pub fn reactions( | |||
| 44 | .as_ref() | 45 | .as_ref() |
| 45 | .is_some_and(|id| reaction.user_ids.contains(id)); | 46 | .is_some_and(|id| reaction.user_ids.contains(id)); |
| 46 | let entity = entity.clone(); | 47 | let entity = entity.clone(); |
| 47 | - let message_id = message.id.clone(); | 48 | + let message_id = message.id; |
| 48 | let emoji = reaction.emoji.clone(); | 49 | let emoji = reaction.emoji.clone(); |
| 49 | let chip_emoji = reaction.emoji.clone(); | 50 | let chip_emoji = reaction.emoji.clone(); |
| 50 | let count = reaction.user_ids.len(); | 51 | let count = reaction.user_ids.len(); |
| @@ -53,7 +54,6 @@ pub fn reactions( | |||
| 53 | format!("reaction_{}_{}", message.id, reaction.emoji), | 54 | format!("reaction_{}_{}", message.id, reaction.emoji), |
| 54 | palette, | 55 | palette, |
| 55 | move |window, cx| { | 56 | move |window, cx| { |
| 56 | - let message_id = message_id.clone(); | ||
| 57 | let emoji = emoji.clone(); | 57 | let emoji = emoji.clone(); |
| 58 | entity.update(cx, |yumush, cx| { | 58 | entity.update(cx, |yumush, cx| { |
| 59 | yumush.toggle_reaction(message_id, emoji, window, cx) | 59 | yumush.toggle_reaction(message_id, emoji, window, cx) |
| @@ -84,7 +84,7 @@ pub fn react_popover( | |||
| 84 | entity: &Entity<Yumush>, | 84 | entity: &Entity<Yumush>, |
| 85 | palette: Palette, | 85 | palette: Palette, |
| 86 | ) -> impl IntoElement { | 86 | ) -> impl IntoElement { |
| 87 | - let message_id = message.id.clone(); | 87 | + let message_id = message.id; |
| 88 | let entity = entity.clone(); | 88 | let entity = entity.clone(); |
| 89 | 89 | ||
| 90 | Popover::new(format!("react_{}", message.id)) | 90 | Popover::new(format!("react_{}", message.id)) |
| @@ -106,14 +106,12 @@ pub fn react_popover( | |||
| 106 | .p(px(4.)) | 106 | .p(px(4.)) |
| 107 | .children(REACTIONS.map(|emoji| { | 107 | .children(REACTIONS.map(|emoji| { |
| 108 | let entity = entity.clone(); | 108 | let entity = entity.clone(); |
| 109 | - let message_id = message_id.clone(); | ||
| 110 | let popover = popover.clone(); | 109 | let popover = popover.clone(); |
| 111 | clickable( | 110 | clickable( |
| 112 | format!("react_{emoji}_{message_id}"), | 111 | format!("react_{emoji}_{message_id}"), |
| 113 | palette, | 112 | palette, |
| 114 | move |window, cx| { | 113 | move |window, cx| { |
| 115 | popover.update(cx, |state, cx| state.dismiss(window, cx)); | 114 | popover.update(cx, |state, cx| state.dismiss(window, cx)); |
| 116 | - let message_id = message_id.clone(); | ||
| 117 | entity.update(cx, |yumush, cx| { | 115 | entity.update(cx, |yumush, cx| { |
| 118 | yumush.toggle_reaction( | 116 | yumush.toggle_reaction( |
| 119 | message_id, | 117 | message_id, |
| @@ -137,7 +135,7 @@ pub fn react_popover( | |||
| 137 | }) | 135 | }) |
| 138 | } | 136 | } |
| 139 | 137 | ||
| 140 | -pub fn quote_text(body: &str, attachments: usize) -> String { | 138 | +pub fn quote_text(body: &str, attachments: u32) -> String { |
| 141 | if body.is_empty() { | 139 | if body.is_empty() { |
| 142 | format!("{attachments} attachments") | 140 | format!("{attachments} attachments") |
| 143 | } else { | 141 | } else { |
| @@ -147,7 +145,7 @@ pub fn quote_text(body: &str, attachments: usize) -> String { | |||
| 147 | 145 | ||
| 148 | pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<impl IntoElement> { | 146 | pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<impl IntoElement> { |
| 149 | let quote = message.reply.as_ref()?; | 147 | let quote = message.reply.as_ref()?; |
| 150 | - let author = chat.author("e.user_id); | 148 | + let author = chat.author(quote.user_id); |
| 151 | 149 | ||
| 152 | Some( | 150 | Some( |
| 153 | div() | 151 | div() |
| @@ -164,7 +162,7 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<im | |||
| 164 | div() | 162 | div() |
| 165 | .flex_shrink_0() | 163 | .flex_shrink_0() |
| 166 | .font_weight(FontWeight::SEMIBOLD) | 164 | .font_weight(FontWeight::SEMIBOLD) |
| 167 | - .text_color(palette.tinted(&user.id)) | 165 | + .text_color(palette.tinted(user.id)) |
| 168 | .child(user.username.clone()) | 166 | .child(user.username.clone()) |
| 169 | })) | 167 | })) |
| 170 | .child( | 168 | .child( |
| @@ -212,7 +210,7 @@ pub fn pin_mark(palette: Palette) -> impl IntoElement { | |||
| 212 | } | 210 | } |
| 213 | 211 | ||
| 214 | struct Hit { | 212 | struct Hit { |
| 215 | - message_id: String, | 213 | + message_id: Id, |
| 216 | name: String, | 214 | name: String, |
| 217 | time: Option<String>, | 215 | time: Option<String>, |
| 218 | body: String, | 216 | body: String, |
| @@ -227,7 +225,7 @@ fn jump_row( | |||
| 227 | ) -> Stateful<Div> { | 225 | ) -> Stateful<Div> { |
| 228 | let entity = entity.clone(); | 226 | let entity = entity.clone(); |
| 229 | let popover = popover.clone(); | 227 | let popover = popover.clone(); |
| 230 | - let message_id = hit.message_id.clone(); | 228 | + let message_id = hit.message_id; |
| 231 | 229 | ||
| 232 | clickable( | 230 | clickable( |
| 233 | format!("{prefix}_{message_id}"), | 231 | format!("{prefix}_{message_id}"), |
| @@ -235,7 +233,7 @@ fn jump_row( | |||
| 235 | move |window, cx| { | 233 | move |window, cx| { |
| 236 | popover.update(cx, |state, cx| state.dismiss(window, cx)); | 234 | popover.update(cx, |state, cx| state.dismiss(window, cx)); |
| 237 | entity.update(cx, |yumush, cx| { | 235 | entity.update(cx, |yumush, cx| { |
| 238 | - yumush.go_to_message(message_id.clone(), window, cx) | 236 | + yumush.go_to_message(message_id, window, cx) |
| 239 | }); | 237 | }); |
| 240 | }, | 238 | }, |
| 241 | ) | 239 | ) |
| @@ -260,14 +258,14 @@ pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> | |||
| 260 | .community_hits | 258 | .community_hits |
| 261 | .iter() | 259 | .iter() |
| 262 | .map(|hit| Hit { | 260 | .map(|hit| Hit { |
| 263 | - message_id: hit.message.id.clone(), | 261 | + message_id: hit.message.id, |
| 264 | name: hit | 262 | name: hit |
| 265 | .author | 263 | .author |
| 266 | .as_ref() | 264 | .as_ref() |
| 267 | .map(|user| user.username.clone()) | 265 | .map(|user| user.username.clone()) |
| 268 | .unwrap_or_default(), | 266 | .unwrap_or_default(), |
| 269 | - time: Some(id_time(&hit.message.id, CLOCK)), | 267 | + time: Some(millis_time(hit.message.created_at, CLOCK)), |
| 270 | - body: quote_text(&hit.message.body, hit.message.attachments.len()), | 268 | + body: quote_text(&hit.message.body, hit.message.attachments.len() as u32), |
| 271 | }) | 269 | }) |
| 272 | .collect(); | 270 | .collect(); |
| 273 | 271 | ||
| @@ -312,13 +310,13 @@ pub fn pins_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i | |||
| 312 | .pins | 310 | .pins |
| 313 | .iter() | 311 | .iter() |
| 314 | .map(|pin| Hit { | 312 | .map(|pin| Hit { |
| 315 | - message_id: pin.id.clone(), | 313 | + message_id: pin.id, |
| 316 | name: chat | 314 | name: chat |
| 317 | - .author(&pin.user_id) | 315 | + .author(pin.user_id) |
| 318 | .map(|user| user.username.clone()) | 316 | .map(|user| user.username.clone()) |
| 319 | .unwrap_or_default(), | 317 | .unwrap_or_default(), |
| 320 | time: None, | 318 | time: None, |
| 321 | - body: quote_text(&pin.body, pin.attachments.len()), | 319 | + body: quote_text(&pin.body, pin.attachments.len() as u32), |
| 322 | }) | 320 | }) |
| 323 | .collect(); | 321 | .collect(); |
| 324 | 322 | ||
| @@ -364,8 +362,8 @@ pub fn actions( | |||
| 364 | let deletable = me.is_some_and(|me| chat.can_delete(message, me)); | 362 | let deletable = me.is_some_and(|me| chat.can_delete(message, me)); |
| 365 | let pinnable = me.is_some_and(|me| chat.can_pin(me)); | 363 | let pinnable = me.is_some_and(|me| chat.can_pin(me)); |
| 366 | let reportable = me.is_some_and(|me| me.id != message.user_id); | 364 | let reportable = me.is_some_and(|me| me.id != message.user_id); |
| 367 | - let id = message.id.as_str(); | 365 | + let id = message.id; |
| 368 | - let armed = chat.pending_message_delete.as_deref() == Some(id); | 366 | + let armed = chat.pending_message_delete == Some(id); |
| 369 | 367 | ||
| 370 | panel(palette) | 368 | panel(palette) |
| 371 | .flex() | 369 | .flex() |
| @@ -477,7 +475,7 @@ pub fn report_bar( | |||
| 477 | impl Yumush { | 475 | impl Yumush { |
| 478 | pub(super) fn toggle_pin( | 476 | pub(super) fn toggle_pin( |
| 479 | &mut self, | 477 | &mut self, |
| 480 | - message_id: String, | 478 | + message_id: Id, |
| 481 | window: &mut Window, | 479 | window: &mut Window, |
| 482 | cx: &mut Context<Self>, | 480 | cx: &mut Context<Self>, |
| 483 | ) { | 481 | ) { |
| @@ -500,7 +498,7 @@ impl Yumush { | |||
| 500 | 498 | ||
| 501 | pub(super) fn toggle_reaction( | 499 | pub(super) fn toggle_reaction( |
| 502 | &mut self, | 500 | &mut self, |
| 503 | - message_id: String, | 501 | + message_id: Id, |
| 504 | emoji: String, | 502 | emoji: String, |
| 505 | window: &mut Window, | 503 | window: &mut Window, |
| 506 | cx: &mut Context<Self>, | 504 | cx: &mut Context<Self>, |
| @@ -565,13 +563,12 @@ impl Yumush { | |||
| 565 | fn action( | 563 | fn action( |
| 566 | entity: &Entity<Yumush>, | 564 | entity: &Entity<Yumush>, |
| 567 | palette: Palette, | 565 | palette: Palette, |
| 568 | - message_id: &str, | 566 | + message_id: Id, |
| 569 | tip: &'static str, | 567 | tip: &'static str, |
| 570 | icon: IconName, | 568 | icon: IconName, |
| 571 | - run: fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>), | 569 | + run: fn(&mut Yumush, Id, &mut Window, &mut Context<Yumush>), |
| 572 | ) -> Stateful<Div> { | 570 | ) -> Stateful<Div> { |
| 573 | let entity = entity.clone(); | 571 | let entity = entity.clone(); |
| 574 | - let message_id = message_id.to_string(); | ||
| 575 | 572 | ||
| 576 | icon_button( | 573 | icon_button( |
| 577 | format!("{tip}_{message_id}"), | 574 | format!("{tip}_{message_id}"), |
| @@ -579,7 +576,6 @@ fn action( | |||
| 579 | icon, | 576 | icon, |
| 580 | tip, | 577 | tip, |
| 581 | move |window, cx| { | 578 | move |window, cx| { |
| 582 | - let message_id = message_id.clone(); | ||
| 583 | entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); | 579 | entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); |
| 584 | }, | 580 | }, |
| 585 | ) | 581 | ) |
crates/client/src/gui/poll.rsmodified+12 -14
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::collections::HashSet; | 2 | use std::collections::HashSet; |
| 2 | 3 | ||
| 3 | use common::call::{ClosePoll, Vote}; | 4 | use common::call::{ClosePoll, Vote}; |
| @@ -22,11 +23,11 @@ pub fn voter_count(poll: &Poll) -> usize { | |||
| 22 | .len() | 23 | .len() |
| 23 | } | 24 | } |
| 24 | 25 | ||
| 25 | -fn my_positions(poll: &Poll, user_id: &str) -> Vec<u32> { | 26 | +fn my_positions(poll: &Poll, user_id: Id) -> Vec<u32> { |
| 26 | poll.options | 27 | poll.options |
| 27 | .iter() | 28 | .iter() |
| 28 | .enumerate() | 29 | .enumerate() |
| 29 | - .filter(|(_, option)| option.voter_ids.iter().any(|id| id == user_id)) | 30 | + .filter(|(_, option)| option.voter_ids.contains(&user_id)) |
| 30 | .map(|(position, _)| position as u32) | 31 | .map(|(position, _)| position as u32) |
| 31 | .collect() | 32 | .collect() |
| 32 | } | 33 | } |
| @@ -50,7 +51,7 @@ fn percent(count: usize, voters: usize) -> usize { | |||
| 50 | 51 | ||
| 51 | pub enum PollMode<'a> { | 52 | pub enum PollMode<'a> { |
| 52 | Live(&'a Message), | 53 | Live(&'a Message), |
| 53 | - Snapshot(&'a str), | 54 | + Snapshot(Id), |
| 54 | } | 55 | } |
| 55 | 56 | ||
| 56 | pub fn poll_card( | 57 | pub fn poll_card( |
| @@ -62,15 +63,15 @@ pub fn poll_card( | |||
| 62 | palette: Palette, | 63 | palette: Palette, |
| 63 | ) -> impl IntoElement { | 64 | ) -> impl IntoElement { |
| 64 | let voters = voter_count(poll); | 65 | let voters = voter_count(poll); |
| 65 | - let me_id = me.map(|me| me.id.as_str()); | 66 | + let me_id = me.map(|me| me.id); |
| 66 | let mine = me_id.map(|id| my_positions(poll, id)).unwrap_or_default(); | 67 | let mine = me_id.map(|id| my_positions(poll, id)).unwrap_or_default(); |
| 67 | let (key, live) = match mode { | 68 | let (key, live) = match mode { |
| 68 | - PollMode::Live(message) => (message.id.clone(), Some(message)), | 69 | + PollMode::Live(message) => (message.id.to_string(), Some(message)), |
| 69 | PollMode::Snapshot(id) => (format!("snapshot_{id}"), None), | 70 | PollMode::Snapshot(id) => (format!("snapshot_{id}"), None), |
| 70 | }; | 71 | }; |
| 71 | let vote_id = live | 72 | let vote_id = live |
| 72 | .filter(|_| !poll.closed && me_id.is_some()) | 73 | .filter(|_| !poll.closed && me_id.is_some()) |
| 73 | - .map(|message| message.id.clone()); | 74 | + .map(|message| message.id); |
| 74 | let close_id = live | 75 | let close_id = live |
| 75 | .filter(|message| { | 76 | .filter(|message| { |
| 76 | !poll.closed | 77 | !poll.closed |
| @@ -78,7 +79,7 @@ pub fn poll_card( | |||
| 78 | me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator) | 79 | me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator) |
| 79 | }) | 80 | }) |
| 80 | }) | 81 | }) |
| 81 | - .map(|message| message.id.clone()); | 82 | + .map(|message| message.id); |
| 82 | 83 | ||
| 83 | let rows = poll.options.iter().enumerate().map(|(position, option)| { | 84 | let rows = poll.options.iter().enumerate().map(|(position, option)| { |
| 84 | let count = option.voter_ids.len(); | 85 | let count = option.voter_ids.len(); |
| @@ -89,10 +90,9 @@ pub fn poll_card( | |||
| 89 | .unwrap_or_default(); | 90 | .unwrap_or_default(); |
| 90 | let entity = entity.clone(); | 91 | let entity = entity.clone(); |
| 91 | let id = format!("poll_option_{key}_{position}"); | 92 | let id = format!("poll_option_{key}_{position}"); |
| 92 | - match vote_id.clone() { | 93 | + match vote_id { |
| 93 | Some(message_id) => clickable(id, palette, move |window, cx| { | 94 | Some(message_id) => clickable(id, palette, move |window, cx| { |
| 94 | let next = next.clone(); | 95 | let next = next.clone(); |
| 95 | - let message_id = message_id.clone(); | ||
| 96 | entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx)); | 96 | entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx)); |
| 97 | }), | 97 | }), |
| 98 | None => div().id(id), | 98 | None => div().id(id), |
| @@ -172,7 +172,6 @@ pub fn poll_card( | |||
| 172 | IconName::CircleStop, | 172 | IconName::CircleStop, |
| 173 | "End poll", | 173 | "End poll", |
| 174 | move |window, cx| { | 174 | move |window, cx| { |
| 175 | - let close_id = close_id.clone(); | ||
| 176 | close_entity.update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); | 175 | close_entity.update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); |
| 177 | }, | 176 | }, |
| 178 | ) | 177 | ) |
| @@ -222,7 +221,7 @@ impl Yumush { | |||
| 222 | let expanded = self.chat.poll_expanded; | 221 | let expanded = self.chat.poll_expanded; |
| 223 | let toggle = entity.clone(); | 222 | let toggle = entity.clone(); |
| 224 | let jump = entity.clone(); | 223 | let jump = entity.clone(); |
| 225 | - let message_id = message.id.clone(); | 224 | + let message_id = message.id; |
| 226 | 225 | ||
| 227 | Some( | 226 | Some( |
| 228 | div() | 227 | div() |
| @@ -289,7 +288,6 @@ impl Yumush { | |||
| 289 | IconName::ArrowUpRight, | 288 | IconName::ArrowUpRight, |
| 290 | "Jump to message", | 289 | "Jump to message", |
| 291 | move |window, cx| { | 290 | move |window, cx| { |
| 292 | - let message_id = message_id.clone(); | ||
| 293 | jump.update(cx, |yumush, cx| { | 291 | jump.update(cx, |yumush, cx| { |
| 294 | yumush.go_to_message(message_id, window, cx) | 292 | yumush.go_to_message(message_id, window, cx) |
| 295 | }); | 293 | }); |
| @@ -311,7 +309,7 @@ impl Yumush { | |||
| 311 | 309 | ||
| 312 | pub(super) fn vote( | 310 | pub(super) fn vote( |
| 313 | &mut self, | 311 | &mut self, |
| 314 | - message_id: String, | 312 | + message_id: Id, |
| 315 | positions: Vec<u32>, | 313 | positions: Vec<u32>, |
| 316 | window: &mut Window, | 314 | window: &mut Window, |
| 317 | cx: &mut Context<Self>, | 315 | cx: &mut Context<Self>, |
| @@ -330,7 +328,7 @@ impl Yumush { | |||
| 330 | 328 | ||
| 331 | pub(super) fn close_poll( | 329 | pub(super) fn close_poll( |
| 332 | &mut self, | 330 | &mut self, |
| 333 | - message_id: String, | 331 | + message_id: Id, |
| 334 | window: &mut Window, | 332 | window: &mut Window, |
| 335 | cx: &mut Context<Self>, | 333 | cx: &mut Context<Self>, |
| 336 | ) { | 334 | ) { |
crates/client/src/gui/profile.rsmodified+50 -58
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::{collections::HashMap, sync::Arc}; | 2 | use std::{collections::HashMap, sync::Arc}; |
| 2 | 3 | ||
| 3 | use common::{ | 4 | use common::{ |
| @@ -24,8 +25,8 @@ use super::message_actions::report_bar; | |||
| 24 | use super::social::Relation; | 25 | use super::social::Relation; |
| 25 | use super::widget::{panel, spawn_done}; | 26 | use super::widget::{panel, spawn_done}; |
| 26 | use super::{ | 27 | use super::{ |
| 27 | - DAY_YEAR, Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, | 28 | + DAY_YEAR, Palette, Trigger, Yumush, avatar, clickable, entity_action, input_dialog, |
| 28 | - notify_error, palette, pop_in, presence_color, rank_tag, swap_in, text, | 29 | + millis_time, notify_error, palette, pop_in, presence_color, rank_tag, swap_in, text, |
| 29 | }; | 30 | }; |
| 30 | 31 | ||
| 31 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 32 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -73,7 +74,7 @@ pub(super) fn profile_popover( | |||
| 73 | let user = user.clone(); | 74 | let user = user.clone(); |
| 74 | let entity = entity.clone(); | 75 | let entity = entity.clone(); |
| 75 | let notify_entity = entity.clone(); | 76 | let notify_entity = entity.clone(); |
| 76 | - let volume_user_id = user.id.clone(); | 77 | + let volume_user_id = user.id; |
| 77 | 78 | ||
| 78 | Popover::new(id) | 79 | Popover::new(id) |
| 79 | .anchor(anchor) | 80 | .anchor(anchor) |
| @@ -82,7 +83,7 @@ pub(super) fn profile_popover( | |||
| 82 | notify_entity.update(cx, |yumush, cx| { | 83 | notify_entity.update(cx, |yumush, cx| { |
| 83 | yumush.chat.card_menu = CardMenu::Main; | 84 | yumush.chat.card_menu = CardMenu::Main; |
| 84 | yumush.chat.pending_user_delete = None; | 85 | yumush.chat.pending_user_delete = None; |
| 85 | - yumush.open_user_volume(&volume_user_id, cx); | 86 | + yumush.open_user_volume(volume_user_id, cx); |
| 86 | cx.notify() | 87 | cx.notify() |
| 87 | }) | 88 | }) |
| 88 | }) | 89 | }) |
| @@ -93,23 +94,23 @@ pub(super) fn profile_popover( | |||
| 93 | viewer: yumush.user.clone(), | 94 | viewer: yumush.user.clone(), |
| 94 | actor: yumush.actor_rank(), | 95 | actor: yumush.actor_rank(), |
| 95 | target: yumush.chat.rank_of(&user), | 96 | target: yumush.chat.rank_of(&user), |
| 96 | - relation: yumush.relation(&user.id), | 97 | + relation: yumush.relation(user.id), |
| 97 | card_menu: yumush.chat.card_menu, | 98 | card_menu: yumush.chat.card_menu, |
| 98 | - presence: yumush.presence_of(&user.id), | 99 | + presence: yumush.presence_of(user.id), |
| 99 | - confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()), | 100 | + confirming: yumush.chat.pending_user_delete == Some(user.id), |
| 100 | - reporting: yumush.chat.report == Some(ReportTarget::User(user.id.clone())), | 101 | + reporting: yumush.chat.report == Some(ReportTarget::User(user.id)), |
| 101 | reason: yumush.chat.report_reason.clone(), | 102 | reason: yumush.chat.report_reason.clone(), |
| 102 | others: yumush | 103 | others: yumush |
| 103 | .accounts | 104 | .accounts |
| 104 | .others() | 105 | .others() |
| 105 | - .map(|account| (account.user_id.clone(), account.username.clone())) | 106 | + .map(|account| (account.user_id, account.username.clone())) |
| 106 | .collect(), | 107 | .collect(), |
| 107 | volume: yumush | 108 | volume: yumush |
| 108 | .chat | 109 | .chat |
| 109 | .user_volume | 110 | .user_volume |
| 110 | .as_ref() | 111 | .as_ref() |
| 111 | .filter(|volume| volume.user_id == user.id) | 112 | .filter(|volume| volume.user_id == user.id) |
| 112 | - .map(|volume| (volume.slider.clone(), yumush.user_volume(&user.id))), | 113 | + .map(|volume| (volume.slider.clone(), yumush.user_volume(user.id))), |
| 113 | user: user.clone(), | 114 | user: user.clone(), |
| 114 | }; | 115 | }; |
| 115 | 116 | ||
| @@ -132,7 +133,7 @@ struct Card { | |||
| 132 | confirming: bool, | 133 | confirming: bool, |
| 133 | reporting: bool, | 134 | reporting: bool, |
| 134 | reason: Entity<InputState>, | 135 | reason: Entity<InputState>, |
| 135 | - others: Vec<(String, String)>, | 136 | + others: Vec<(Id, String)>, |
| 136 | volume: Option<(Entity<SliderState>, f32)>, | 137 | volume: Option<(Entity<SliderState>, f32)>, |
| 137 | } | 138 | } |
| 138 | 139 | ||
| @@ -143,8 +144,8 @@ impl Card { | |||
| 143 | popover: &Entity<PopoverState>, | 144 | popover: &Entity<PopoverState>, |
| 144 | palette: Palette, | 145 | palette: Palette, |
| 145 | ) -> Vec<AnyElement> { | 146 | ) -> Vec<AnyElement> { |
| 146 | - let user_id = self.user.id.clone(); | 147 | + let user_id = self.user.id; |
| 147 | - let message_id = user_id.clone(); | 148 | + let message_id = user_id; |
| 148 | let mut rows = vec![ | 149 | let mut rows = vec![ |
| 149 | menu_row( | 150 | menu_row( |
| 150 | "profile_message", | 151 | "profile_message", |
| @@ -153,13 +154,13 @@ impl Card { | |||
| 153 | palette.text, | 154 | palette.text, |
| 154 | palette, | 155 | palette, |
| 155 | yumush_action(entity, popover, move |yumush, window, cx| { | 156 | yumush_action(entity, popover, move |yumush, window, cx| { |
| 156 | - yumush.open_direct(message_id.clone(), window, cx) | 157 | + yumush.open_direct(message_id, window, cx) |
| 157 | }), | 158 | }), |
| 158 | ) | 159 | ) |
| 159 | .into_any_element(), | 160 | .into_any_element(), |
| 160 | ]; | 161 | ]; |
| 161 | 162 | ||
| 162 | - let report_user_id = self.user.id.clone(); | 163 | + let report_user_id = self.user.id; |
| 163 | rows.push( | 164 | rows.push( |
| 164 | menu_row( | 165 | menu_row( |
| 165 | "profile_report", | 166 | "profile_report", |
| @@ -168,7 +169,7 @@ impl Card { | |||
| 168 | palette.danger, | 169 | palette.danger, |
| 169 | palette, | 170 | palette, |
| 170 | entity_action(entity, move |yumush, window, cx| { | 171 | entity_action(entity, move |yumush, window, cx| { |
| 171 | - yumush.start_report(ReportTarget::User(report_user_id.clone()), window, cx) | 172 | + yumush.start_report(ReportTarget::User(report_user_id), window, cx) |
| 172 | }), | 173 | }), |
| 173 | ) | 174 | ) |
| 174 | .into_any_element(), | 175 | .into_any_element(), |
| @@ -184,7 +185,7 @@ impl Card { | |||
| 184 | palette.text, | 185 | palette.text, |
| 185 | palette, | 186 | palette, |
| 186 | yumush_action(entity, popover, move |yumush, window, cx| { | 187 | yumush_action(entity, popover, move |yumush, window, cx| { |
| 187 | - yumush.friend_action(relation, user_id.clone(), window, cx) | 188 | + yumush.friend_action(relation, user_id, window, cx) |
| 188 | }), | 189 | }), |
| 189 | ) | 190 | ) |
| 190 | .into_any_element(), | 191 | .into_any_element(), |
| @@ -199,7 +200,7 @@ impl Card { | |||
| 199 | entity: &Entity<Yumush>, | 200 | entity: &Entity<Yumush>, |
| 200 | popover: Entity<PopoverState>, | 201 | popover: Entity<PopoverState>, |
| 201 | palette: Palette, | 202 | palette: Palette, |
| 202 | - avatars: &HashMap<String, Arc<Image>>, | 203 | + avatars: &HashMap<Id, Arc<Image>>, |
| 203 | ) -> Div { | 204 | ) -> Div { |
| 204 | let is_self = self | 205 | let is_self = self |
| 205 | .viewer | 206 | .viewer |
| @@ -261,7 +262,10 @@ impl Card { | |||
| 261 | div() | 262 | div() |
| 262 | .text_size(text(12.)) | 263 | .text_size(text(12.)) |
| 263 | .text_color(palette.muted) | 264 | .text_color(palette.muted) |
| 264 | - .child(format!("Joined {}", id_time(&self.user.id, DAY_YEAR))), | 265 | + .child(format!( |
| 266 | + "Joined {}", | ||
| 267 | + millis_time(self.user.created_at, DAY_YEAR) | ||
| 268 | + )), | ||
| 265 | ) | 269 | ) |
| 266 | .children(self.volume.map(|(slider, volume)| { | 270 | .children(self.volume.map(|(slider, volume)| { |
| 267 | div() | 271 | div() |
| @@ -294,12 +298,11 @@ impl Card { | |||
| 294 | ) -> Vec<AnyElement> { | 298 | ) -> Vec<AnyElement> { |
| 295 | let actor = self.actor; | 299 | let actor = self.actor; |
| 296 | let target = self.target; | 300 | let target = self.target; |
| 297 | - let user_id = self.user.id.clone(); | 301 | + let user_id = self.user.id; |
| 298 | let mut rows = Vec::new(); | 302 | let mut rows = Vec::new(); |
| 299 | 303 | ||
| 300 | for rank in [Rank::Member, Rank::Moderator, Rank::Admin] { | 304 | for rank in [Rank::Member, Rank::Moderator, Rank::Admin] { |
| 301 | if target != Some(rank) && permission::can_set_rank(actor, target, rank) { | 305 | if target != Some(rank) && permission::can_set_rank(actor, target, rank) { |
| 302 | - let user_id = user_id.clone(); | ||
| 303 | let label = format!("Make {}", rank.label().to_lowercase()); | 306 | let label = format!("Make {}", rank.label().to_lowercase()); |
| 304 | rows.push( | 307 | rows.push( |
| 305 | menu_row( | 308 | menu_row( |
| @@ -309,7 +312,7 @@ impl Card { | |||
| 309 | palette.text, | 312 | palette.text, |
| 310 | palette, | 313 | palette, |
| 311 | yumush_action(entity, popover, move |yumush, window, cx| { | 314 | yumush_action(entity, popover, move |yumush, window, cx| { |
| 312 | - yumush.set_member_rank(&user_id, rank, window, cx) | 315 | + yumush.set_member_rank(user_id, rank, window, cx) |
| 313 | }), | 316 | }), |
| 314 | ) | 317 | ) |
| 315 | .into_any_element(), | 318 | .into_any_element(), |
| @@ -318,8 +321,8 @@ impl Card { | |||
| 318 | } | 321 | } |
| 319 | 322 | ||
| 320 | if permission::can_moderate(actor, target) { | 323 | if permission::can_moderate(actor, target) { |
| 321 | - let kick_id = user_id.clone(); | 324 | + let kick_id = user_id; |
| 322 | - let ban_id = user_id.clone(); | 325 | + let ban_id = user_id; |
| 323 | rows.push( | 326 | rows.push( |
| 324 | menu_row( | 327 | menu_row( |
| 325 | "kick", | 328 | "kick", |
| @@ -328,7 +331,7 @@ impl Card { | |||
| 328 | palette.danger, | 331 | palette.danger, |
| 329 | palette, | 332 | palette, |
| 330 | yumush_action(entity, popover, move |yumush, window, cx| { | 333 | yumush_action(entity, popover, move |yumush, window, cx| { |
| 331 | - yumush.open_removal(kick_id.clone(), Removal::Kick, window, cx) | 334 | + yumush.open_removal(kick_id, Removal::Kick, window, cx) |
| 332 | }), | 335 | }), |
| 333 | ) | 336 | ) |
| 334 | .into_any_element(), | 337 | .into_any_element(), |
| @@ -341,7 +344,7 @@ impl Card { | |||
| 341 | palette.danger, | 344 | palette.danger, |
| 342 | palette, | 345 | palette, |
| 343 | yumush_action(entity, popover, move |yumush, window, cx| { | 346 | yumush_action(entity, popover, move |yumush, window, cx| { |
| 344 | - yumush.open_removal(ban_id.clone(), Removal::Ban, window, cx) | 347 | + yumush.open_removal(ban_id, Removal::Ban, window, cx) |
| 345 | }), | 348 | }), |
| 346 | ) | 349 | ) |
| 347 | .into_any_element(), | 350 | .into_any_element(), |
| @@ -366,7 +369,7 @@ impl Card { | |||
| 366 | menu_icon(IconName::Trash), | 369 | menu_icon(IconName::Trash), |
| 367 | palette.danger, | 370 | palette.danger, |
| 368 | palette, | 371 | palette, |
| 369 | - delete_user_action(&user_id, self.confirming, entity, popover), | 372 | + delete_user_action(user_id, self.confirming, entity, popover), |
| 370 | ) | 373 | ) |
| 371 | .into_any_element(), | 374 | .into_any_element(), |
| 372 | ); | 375 | ); |
| @@ -377,7 +380,7 @@ impl Card { | |||
| 377 | } | 380 | } |
| 378 | 381 | ||
| 379 | fn self_rows( | 382 | fn self_rows( |
| 380 | - others: &[(String, String)], | 383 | + others: &[(Id, String)], |
| 381 | card_menu: CardMenu, | 384 | card_menu: CardMenu, |
| 382 | presence: Presence, | 385 | presence: Presence, |
| 383 | entity: &Entity<Yumush>, | 386 | entity: &Entity<Yumush>, |
| @@ -440,13 +443,12 @@ fn main_self_rows( | |||
| 440 | } | 443 | } |
| 441 | 444 | ||
| 442 | fn accounts_rows( | 445 | fn accounts_rows( |
| 443 | - others: &[(String, String)], | 446 | + others: &[(Id, String)], |
| 444 | entity: &Entity<Yumush>, | 447 | entity: &Entity<Yumush>, |
| 445 | popover: &Entity<PopoverState>, | 448 | popover: &Entity<PopoverState>, |
| 446 | palette: Palette, | 449 | palette: Palette, |
| 447 | ) -> Vec<AnyElement> { | 450 | ) -> Vec<AnyElement> { |
| 448 | - let accounts = others.iter().map(|(user_id, username)| { | 451 | + let accounts = others.iter().map(|&(user_id, ref username)| { |
| 449 | - let user_id = user_id.clone(); | ||
| 450 | menu_row( | 452 | menu_row( |
| 451 | format!("switch_{user_id}"), | 453 | format!("switch_{user_id}"), |
| 452 | username.clone(), | 454 | username.clone(), |
| @@ -454,7 +456,7 @@ fn accounts_rows( | |||
| 454 | palette.text, | 456 | palette.text, |
| 455 | palette, | 457 | palette, |
| 456 | yumush_action(entity, popover, move |yumush, window, cx| { | 458 | yumush_action(entity, popover, move |yumush, window, cx| { |
| 457 | - yumush.switch_account(user_id.clone(), window, cx) | 459 | + yumush.switch_account(user_id, window, cx) |
| 458 | }), | 460 | }), |
| 459 | ) | 461 | ) |
| 460 | }); | 462 | }); |
| @@ -553,12 +555,11 @@ fn yumush_action( | |||
| 553 | } | 555 | } |
| 554 | 556 | ||
| 555 | fn delete_user_action( | 557 | fn delete_user_action( |
| 556 | - user_id: &str, | 558 | + user_id: Id, |
| 557 | confirming: bool, | 559 | confirming: bool, |
| 558 | entity: &Entity<Yumush>, | 560 | entity: &Entity<Yumush>, |
| 559 | popover: &Entity<PopoverState>, | 561 | popover: &Entity<PopoverState>, |
| 560 | ) -> impl Fn(&mut Window, &mut App) + 'static { | 562 | ) -> impl Fn(&mut Window, &mut App) + 'static { |
| 561 | - let user_id = user_id.to_string(); | ||
| 562 | let entity = entity.clone(); | 563 | let entity = entity.clone(); |
| 563 | let popover = popover.clone(); | 564 | let popover = popover.clone(); |
| 564 | 565 | ||
| @@ -566,10 +567,10 @@ fn delete_user_action( | |||
| 566 | if confirming { | 567 | if confirming { |
| 567 | popover.update(cx, |state, cx| state.dismiss(window, cx)); | 568 | popover.update(cx, |state, cx| state.dismiss(window, cx)); |
| 568 | entity.update(cx, |yumush, cx| { | 569 | entity.update(cx, |yumush, cx| { |
| 569 | - yumush.delete_member_account(&user_id, window, cx) | 570 | + yumush.delete_member_account(user_id, window, cx) |
| 570 | }); | 571 | }); |
| 571 | } else { | 572 | } else { |
| 572 | - entity.update(cx, |yumush, cx| yumush.request_member_delete(&user_id, cx)); | 573 | + entity.update(cx, |yumush, cx| yumush.request_member_delete(user_id, cx)); |
| 573 | } | 574 | } |
| 574 | } | 575 | } |
| 575 | } | 576 | } |
| @@ -607,12 +608,12 @@ fn drill_row(row: Stateful<Div>) -> AnyElement { | |||
| 607 | impl Yumush { | 608 | impl Yumush { |
| 608 | fn open_removal( | 609 | fn open_removal( |
| 609 | &self, | 610 | &self, |
| 610 | - user_id: String, | 611 | + user_id: Id, |
| 611 | removal: Removal, | 612 | removal: Removal, |
| 612 | window: &mut Window, | 613 | window: &mut Window, |
| 613 | cx: &mut Context<Self>, | 614 | cx: &mut Context<Self>, |
| 614 | ) { | 615 | ) { |
| 615 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 616 | + let Some(community_id) = self.chat.selected_community_id else { |
| 616 | return; | 617 | return; |
| 617 | }; | 618 | }; |
| 618 | input_dialog( | 619 | input_dialog( |
| @@ -624,23 +625,21 @@ impl Yumush { | |||
| 624 | move |this, text, window, cx| { | 625 | move |this, text, window, cx| { |
| 625 | let reason = text.trim().to_string(); | 626 | let reason = text.trim().to_string(); |
| 626 | let reason = (!reason.is_empty()).then_some(reason); | 627 | let reason = (!reason.is_empty()).then_some(reason); |
| 627 | - this.remove_member(&community_id, &user_id, removal, reason, window, cx); | 628 | + this.remove_member(community_id, user_id, removal, reason, window, cx); |
| 628 | }, | 629 | }, |
| 629 | ); | 630 | ); |
| 630 | } | 631 | } |
| 631 | 632 | ||
| 632 | fn remove_member( | 633 | fn remove_member( |
| 633 | &self, | 634 | &self, |
| 634 | - community_id: &str, | 635 | + community_id: Id, |
| 635 | - user_id: &str, | 636 | + user_id: Id, |
| 636 | removal: Removal, | 637 | removal: Removal, |
| 637 | reason: Option<String>, | 638 | reason: Option<String>, |
| 638 | window: &mut Window, | 639 | window: &mut Window, |
| 639 | cx: &mut Context<Self>, | 640 | cx: &mut Context<Self>, |
| 640 | ) { | 641 | ) { |
| 641 | let network = self.network.clone(); | 642 | let network = self.network.clone(); |
| 642 | - let community_id = community_id.to_string(); | ||
| 643 | - let user_id = user_id.to_string(); | ||
| 644 | 643 | ||
| 645 | cx.spawn_in(window, async move |this, cx| { | 644 | cx.spawn_in(window, async move |this, cx| { |
| 646 | let result = match removal { | 645 | let result = match removal { |
| @@ -680,16 +679,15 @@ impl Yumush { | |||
| 680 | 679 | ||
| 681 | pub(super) fn set_member_rank( | 680 | pub(super) fn set_member_rank( |
| 682 | &self, | 681 | &self, |
| 683 | - user_id: &str, | 682 | + user_id: Id, |
| 684 | rank: Rank, | 683 | rank: Rank, |
| 685 | window: &mut Window, | 684 | window: &mut Window, |
| 686 | cx: &mut Context<Self>, | 685 | cx: &mut Context<Self>, |
| 687 | ) { | 686 | ) { |
| 688 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 687 | + let Some(community_id) = self.chat.selected_community_id else { |
| 689 | return; | 688 | return; |
| 690 | }; | 689 | }; |
| 691 | let network = self.network.clone(); | 690 | let network = self.network.clone(); |
| 692 | - let user_id = user_id.to_string(); | ||
| 693 | 691 | ||
| 694 | spawn_done(window, cx, async move { | 692 | spawn_done(window, cx, async move { |
| 695 | network | 693 | network |
| @@ -709,7 +707,7 @@ impl Yumush { | |||
| 709 | cx: &mut Context<Self>, | 707 | cx: &mut Context<Self>, |
| 710 | ) { | 708 | ) { |
| 711 | if let Some(me) = &self.user { | 709 | if let Some(me) = &self.user { |
| 712 | - self.chat.presences.insert(me.id.clone(), presence); | 710 | + self.chat.presences.insert(me.id, presence); |
| 713 | } | 711 | } |
| 714 | self.chat.card_menu = CardMenu::Main; | 712 | self.chat.card_menu = CardMenu::Main; |
| 715 | cx.notify(); | 713 | cx.notify(); |
| @@ -721,31 +719,25 @@ impl Yumush { | |||
| 721 | }); | 719 | }); |
| 722 | } | 720 | } |
| 723 | 721 | ||
| 724 | - pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context<Self>) { | 722 | + pub(super) fn request_member_delete(&mut self, user_id: Id, cx: &mut Context<Self>) { |
| 725 | - self.chat.pending_user_delete = Some(user_id.to_string()); | 723 | + self.chat.pending_user_delete = Some(user_id); |
| 726 | cx.notify(); | 724 | cx.notify(); |
| 727 | } | 725 | } |
| 728 | 726 | ||
| 729 | pub(super) fn delete_member_account( | 727 | pub(super) fn delete_member_account( |
| 730 | &mut self, | 728 | &mut self, |
| 731 | - user_id: &str, | 729 | + user_id: Id, |
| 732 | window: &mut Window, | 730 | window: &mut Window, |
| 733 | cx: &mut Context<Self>, | 731 | cx: &mut Context<Self>, |
| 734 | ) { | 732 | ) { |
| 735 | self.chat.pending_user_delete = None; | 733 | self.chat.pending_user_delete = None; |
| 736 | let network = self.network.clone(); | 734 | let network = self.network.clone(); |
| 737 | - let user_id = user_id.to_string(); | ||
| 738 | 735 | ||
| 739 | cx.spawn_in(window, async move |this, cx| { | 736 | cx.spawn_in(window, async move |this, cx| { |
| 740 | - match network | 737 | + match network.call(DeleteUser { user_id }).await { |
| 741 | - .call(DeleteUser { | ||
| 742 | - user_id: user_id.clone(), | ||
| 743 | - }) | ||
| 744 | - .await | ||
| 745 | - { | ||
| 746 | Ok(()) => { | 738 | Ok(()) => { |
| 747 | let _ = this.update(cx, |yumush, cx| { | 739 | let _ = this.update(cx, |yumush, cx| { |
| 748 | - yumush.chat.remove_member(&user_id); | 740 | + yumush.chat.remove_member(user_id); |
| 749 | cx.notify(); | 741 | cx.notify(); |
| 750 | }); | 742 | }); |
| 751 | } | 743 | } |
crates/client/src/gui/settings_page.rsmodified+1 -1
| @@ -222,7 +222,7 @@ impl Yumush { | |||
| 222 | if !self.confirm_delete(cx) { | 222 | if !self.confirm_delete(cx) { |
| 223 | return; | 223 | return; |
| 224 | } | 224 | } |
| 225 | - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { | 225 | + let Some(user_id) = self.user.as_ref().map(|user| user.id) else { |
| 226 | return; | 226 | return; |
| 227 | }; | 227 | }; |
| 228 | let network = self.network.clone(); | 228 | let network = self.network.clone(); |
crates/client/src/gui/share_view.rsmodified+21 -22
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::{collections::VecDeque, sync::Arc, time::Duration}; | 2 | use std::{collections::VecDeque, sync::Arc, time::Duration}; |
| 2 | 3 | ||
| 3 | use common::share::{Codec, Fps, Kind, Quality, Resolution, Source, options}; | 4 | use common::share::{Codec, Fps, Kind, Quality, Resolution, Source, options}; |
| @@ -77,7 +78,7 @@ impl AudioMode { | |||
| 77 | } | 78 | } |
| 78 | 79 | ||
| 79 | pub(super) struct Viewer { | 80 | pub(super) struct Viewer { |
| 80 | - user_id: String, | 81 | + user_id: Id, |
| 81 | kind: Kind, | 82 | kind: Kind, |
| 82 | generation: Option<u64>, | 83 | generation: Option<u64>, |
| 83 | frame: Option<Arc<RenderImage>>, | 84 | frame: Option<Arc<RenderImage>>, |
| @@ -88,11 +89,11 @@ pub(super) struct Viewer { | |||
| 88 | } | 89 | } |
| 89 | 90 | ||
| 90 | impl Yumush { | 91 | impl Yumush { |
| 91 | - pub(super) fn load_shares(&self, community_id: String, cx: &mut Context<Self>) { | 92 | + pub(super) fn load_shares(&self, community_id: Id, cx: &mut Context<Self>) { |
| 92 | let network = self.network.clone(); | 93 | let network = self.network.clone(); |
| 93 | 94 | ||
| 94 | cx.spawn(async move |this, cx| { | 95 | cx.spawn(async move |this, cx| { |
| 95 | - let Ok(shares) = network.shares(&community_id).await else { | 96 | + let Ok(shares) = network.shares(community_id).await else { |
| 96 | return; | 97 | return; |
| 97 | }; | 98 | }; |
| 98 | let _ = this.update(cx, |yumush, cx| { | 99 | let _ = this.update(cx, |yumush, cx| { |
| @@ -195,29 +196,29 @@ impl Yumush { | |||
| 195 | self.update_share(cx, |settings| settings.watch = watch); | 196 | self.update_share(cx, |settings| settings.watch = watch); |
| 196 | } | 197 | } |
| 197 | 198 | ||
| 198 | - pub(super) fn is_watching(&self, user_id: &str, kind: Kind) -> bool { | 199 | + pub(super) fn is_watching(&self, user_id: Id, kind: Kind) -> bool { |
| 199 | self.chat | 200 | self.chat |
| 200 | .viewer | 201 | .viewer |
| 201 | .as_ref() | 202 | .as_ref() |
| 202 | .is_some_and(|viewer| viewer.user_id == user_id && viewer.kind == kind) | 203 | .is_some_and(|viewer| viewer.user_id == user_id && viewer.kind == kind) |
| 203 | } | 204 | } |
| 204 | 205 | ||
| 205 | - pub(super) fn viewing_camera(&self) -> Option<String> { | 206 | + pub(super) fn viewing_camera(&self) -> Option<Id> { |
| 206 | self.chat | 207 | self.chat |
| 207 | .viewer | 208 | .viewer |
| 208 | .as_ref() | 209 | .as_ref() |
| 209 | .filter(|viewer| viewer.kind == Kind::Camera) | 210 | .filter(|viewer| viewer.kind == Kind::Camera) |
| 210 | - .map(|viewer| viewer.user_id.clone()) | 211 | + .map(|viewer| viewer.user_id) |
| 211 | } | 212 | } |
| 212 | 213 | ||
| 213 | pub(super) fn toggle_viewer( | 214 | pub(super) fn toggle_viewer( |
| 214 | &mut self, | 215 | &mut self, |
| 215 | - user_id: String, | 216 | + user_id: Id, |
| 216 | kind: Kind, | 217 | kind: Kind, |
| 217 | window: &mut Window, | 218 | window: &mut Window, |
| 218 | cx: &mut Context<Self>, | 219 | cx: &mut Context<Self>, |
| 219 | ) { | 220 | ) { |
| 220 | - let watching = self.is_watching(&user_id, kind); | 221 | + let watching = self.is_watching(user_id, kind); |
| 221 | self.close_viewer(cx); | 222 | self.close_viewer(cx); |
| 222 | if watching { | 223 | if watching { |
| 223 | return; | 224 | return; |
| @@ -249,7 +250,7 @@ impl Yumush { | |||
| 249 | }); | 250 | }); |
| 250 | 251 | ||
| 251 | self.chat.viewer = Some(Viewer { | 252 | self.chat.viewer = Some(Viewer { |
| 252 | - user_id: user_id.clone(), | 253 | + user_id, |
| 253 | kind, | 254 | kind, |
| 254 | generation: None, | 255 | generation: None, |
| 255 | frame: None, | 256 | frame: None, |
| @@ -264,15 +265,15 @@ impl Yumush { | |||
| 264 | let volume = self.settings.share.volume; | 265 | let volume = self.settings.share.volume; |
| 265 | let choice = self.settings.voice.choice.clone(); | 266 | let choice = self.settings.voice.choice.clone(); |
| 266 | if kind == Kind::Camera && self.chat.cameras.contains_key(&user_id) { | 267 | if kind == Kind::Camera && self.chat.cameras.contains_key(&user_id) { |
| 267 | - network.set_watch_quality(&user_id, kind, watch); | 268 | + network.set_watch_quality(user_id, kind, watch); |
| 268 | } else { | 269 | } else { |
| 269 | cx.spawn_in(window, async move |this, cx| { | 270 | cx.spawn_in(window, async move |this, cx| { |
| 270 | if let Err(error) = network | 271 | if let Err(error) = network |
| 271 | - .watch_share(&user_id, kind, watch, volume, choice) | 272 | + .watch_share(user_id, kind, watch, volume, choice) |
| 272 | .await | 273 | .await |
| 273 | { | 274 | { |
| 274 | let _ = this.update(cx, |yumush, cx| { | 275 | let _ = this.update(cx, |yumush, cx| { |
| 275 | - if yumush.is_watching(&user_id, kind) { | 276 | + if yumush.is_watching(user_id, kind) { |
| 276 | yumush.close_viewer(cx); | 277 | yumush.close_viewer(cx); |
| 277 | } | 278 | } |
| 278 | }); | 279 | }); |
| @@ -293,12 +294,12 @@ impl Yumush { | |||
| 293 | } | 294 | } |
| 294 | let network = self.network.clone(); | 295 | let network = self.network.clone(); |
| 295 | if viewer.kind == Kind::Camera && self.chat.cameras.contains_key(&viewer.user_id) { | 296 | if viewer.kind == Kind::Camera && self.chat.cameras.contains_key(&viewer.user_id) { |
| 296 | - network.set_watch_quality(&viewer.user_id, viewer.kind, camera_view::CAMERA_TILE); | 297 | + network.set_watch_quality(viewer.user_id, viewer.kind, camera_view::CAMERA_TILE); |
| 297 | } else { | 298 | } else { |
| 298 | - let user_id = viewer.user_id.clone(); | 299 | + let user_id = viewer.user_id; |
| 299 | let kind = viewer.kind; | 300 | let kind = viewer.kind; |
| 300 | cx.spawn(async move |_, _| { | 301 | cx.spawn(async move |_, _| { |
| 301 | - let _ = network.unwatch_share(&user_id, kind).await; | 302 | + let _ = network.unwatch_share(user_id, kind).await; |
| 302 | }) | 303 | }) |
| 303 | .detach(); | 304 | .detach(); |
| 304 | } | 305 | } |
| @@ -309,7 +310,7 @@ impl Yumush { | |||
| 309 | let Some(viewer) = self.chat.viewer.as_mut() else { | 310 | let Some(viewer) = self.chat.viewer.as_mut() else { |
| 310 | return; | 311 | return; |
| 311 | }; | 312 | }; |
| 312 | - let Some(frame) = self.network.share_frame(&viewer.user_id, viewer.kind) else { | 313 | + let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else { |
| 313 | return; | 314 | return; |
| 314 | }; | 315 | }; |
| 315 | if viewer.generation == Some(frame.generation) { | 316 | if viewer.generation == Some(frame.generation) { |
| @@ -421,7 +422,7 @@ impl Yumush { | |||
| 421 | ) | 422 | ) |
| 422 | } | 423 | } |
| 423 | 424 | ||
| 424 | - fn share_top(&self, user_id: &str, kind: Kind) -> Quality { | 425 | + fn share_top(&self, user_id: Id, kind: Kind) -> Quality { |
| 425 | self.chat | 426 | self.chat |
| 426 | .voice_community() | 427 | .voice_community() |
| 427 | .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) | 428 | .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) |
| @@ -434,7 +435,7 @@ impl Yumush { | |||
| 434 | } else { | 435 | } else { |
| 435 | (IconName::Maximize, "Fullscreen") | 436 | (IconName::Maximize, "Fullscreen") |
| 436 | }; | 437 | }; |
| 437 | - let top = self.share_top(&viewer.user_id, viewer.kind); | 438 | + let top = self.share_top(viewer.user_id, viewer.kind); |
| 438 | let audio = viewer.kind == Kind::Screen; | 439 | let audio = viewer.kind == Kind::Screen; |
| 439 | 440 | ||
| 440 | div() | 441 | div() |
| @@ -477,7 +478,7 @@ impl Yumush { | |||
| 477 | .then(|| { | 478 | .then(|| { |
| 478 | self.chat | 479 | self.chat |
| 479 | .waves | 480 | .waves |
| 480 | - .share(&viewer.user_id) | 481 | + .share(viewer.user_id) |
| 481 | .map(|history| wave(history, 14., palette.alert)) | 482 | .map(|history| wave(history, 14., palette.alert)) |
| 482 | }) | 483 | }) |
| 483 | .flatten(), | 484 | .flatten(), |
| @@ -561,18 +562,16 @@ fn quality_chips( | |||
| 561 | 562 | ||
| 562 | pub(super) fn share_badge( | 563 | pub(super) fn share_badge( |
| 563 | entity: &Entity<Yumush>, | 564 | entity: &Entity<Yumush>, |
| 564 | - user_id: &str, | 565 | + user_id: Id, |
| 565 | sound: Option<&VecDeque<f32>>, | 566 | sound: Option<&VecDeque<f32>>, |
| 566 | palette: Palette, | 567 | palette: Palette, |
| 567 | ) -> impl IntoElement { | 568 | ) -> impl IntoElement { |
| 568 | let entity = entity.clone(); | 569 | let entity = entity.clone(); |
| 569 | - let user_id = user_id.to_string(); | ||
| 570 | 570 | ||
| 571 | clickable( | 571 | clickable( |
| 572 | format!("share_badge_{user_id}"), | 572 | format!("share_badge_{user_id}"), |
| 573 | palette, | 573 | palette, |
| 574 | move |window, cx| { | 574 | move |window, cx| { |
| 575 | - let user_id = user_id.clone(); | ||
| 576 | entity.update(cx, |yumush, cx| { | 575 | entity.update(cx, |yumush, cx| { |
| 577 | yumush.toggle_viewer(user_id, Kind::Screen, window, cx) | 576 | yumush.toggle_viewer(user_id, Kind::Screen, window, cx) |
| 578 | }); | 577 | }); |
crates/client/src/gui/sidebar.rsmodified+56 -62
| @@ -1,4 +1,5 @@ | |||
| 1 | use super::text; | 1 | use super::text; |
| 2 | +use common::model::Id; | ||
| 2 | use common::{ | 3 | use common::{ |
| 3 | model::{Community, CommunityKind, Invitation, Role, Unread, User}, | 4 | model::{Community, CommunityKind, Invitation, Role, Unread, User}, |
| 4 | permission, | 5 | permission, |
| @@ -146,10 +147,10 @@ impl Yumush { | |||
| 146 | let stats_entity = entity.clone(); | 147 | let stats_entity = entity.clone(); |
| 147 | let members: Vec<_> = self | 148 | let members: Vec<_> = self |
| 148 | .chat | 149 | .chat |
| 149 | - .voice_ids(&community.id) | 150 | + .voice_ids(community.id) |
| 150 | .iter() | 151 | .iter() |
| 151 | - .filter_map(|id| self.chat.author(id)) | 152 | + .filter_map(|id| self.chat.author(*id)) |
| 152 | - .map(|user| self.voice_member(entity, &community.id, user, palette)) | 153 | + .map(|user| self.voice_member(entity, community.id, user, palette)) |
| 153 | .collect(); | 154 | .collect(); |
| 154 | 155 | ||
| 155 | let controls = div() | 156 | let controls = div() |
| @@ -230,13 +231,13 @@ impl Yumush { | |||
| 230 | fn voice_member( | 231 | fn voice_member( |
| 231 | &self, | 232 | &self, |
| 232 | entity: &Entity<Self>, | 233 | entity: &Entity<Self>, |
| 233 | - community_id: &str, | 234 | + community_id: Id, |
| 234 | user: &User, | 235 | user: &User, |
| 235 | palette: Palette, | 236 | palette: Palette, |
| 236 | ) -> impl IntoElement { | 237 | ) -> impl IntoElement { |
| 237 | let speaking = self.chat.waves.speaking.contains(&user.id); | 238 | let speaking = self.chat.waves.speaking.contains(&user.id); |
| 238 | - let share = self.chat.waves.share(&user.id); | 239 | + let share = self.chat.waves.share(user.id); |
| 239 | - let sharing = share.is_none() && self.chat.is_sharing(community_id, &user.id); | 240 | + let sharing = share.is_none() && self.chat.is_sharing(community_id, user.id); |
| 240 | 241 | ||
| 241 | profile_popover( | 242 | profile_popover( |
| 242 | format!("voice_member_{}", user.id), | 243 | format!("voice_member_{}", user.id), |
| @@ -282,7 +283,7 @@ impl Yumush { | |||
| 282 | .children( | 283 | .children( |
| 283 | self.chat | 284 | self.chat |
| 284 | .waves | 285 | .waves |
| 285 | - .voice(&user.id) | 286 | + .voice(user.id) |
| 286 | .map(|history| wave(history, 12., palette.ok)), | 287 | .map(|history| wave(history, 12., palette.ok)), |
| 287 | ), | 288 | ), |
| 288 | ) | 289 | ) |
| @@ -317,12 +318,12 @@ impl Yumush { | |||
| 317 | 318 | ||
| 318 | pub(super) fn go_to_community( | 319 | pub(super) fn go_to_community( |
| 319 | &mut self, | 320 | &mut self, |
| 320 | - community_id: String, | 321 | + community_id: Id, |
| 321 | direct: bool, | 322 | direct: bool, |
| 322 | window: &mut Window, | 323 | window: &mut Window, |
| 323 | cx: &mut Context<Self>, | 324 | cx: &mut Context<Self>, |
| 324 | ) { | 325 | ) { |
| 325 | - if self.chat.view == View::Chat && self.chat.is_selected(&community_id) { | 326 | + if self.chat.view == View::Chat && self.chat.is_selected(community_id) { |
| 326 | return; | 327 | return; |
| 327 | } | 328 | } |
| 328 | self.chat.tab = if direct { | 329 | self.chat.tab = if direct { |
| @@ -408,7 +409,7 @@ impl Yumush { | |||
| 408 | .chat | 409 | .chat |
| 409 | .found | 410 | .found |
| 410 | .as_ref() | 411 | .as_ref() |
| 411 | - .filter(|user| !self.is_listed(&user.id)); | 412 | + .filter(|user| !self.is_listed(user.id)); |
| 412 | 413 | ||
| 413 | div() | 414 | div() |
| 414 | .flex() | 415 | .flex() |
| @@ -438,7 +439,7 @@ impl Yumush { | |||
| 438 | 439 | ||
| 439 | fn notes_row(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement { | 440 | fn notes_row(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement { |
| 440 | let notes = self.chat.notes(); | 441 | let notes = self.chat.notes(); |
| 441 | - let active = notes.is_some_and(|notes| self.chat.is_selected(¬es.id)); | 442 | + let active = notes.is_some_and(|notes| self.chat.is_selected(notes.id)); |
| 442 | let unread = notes.and_then(|notes| self.chat.unread.get(¬es.id)); | 443 | let unread = notes.and_then(|notes| self.chat.unread.get(¬es.id)); |
| 443 | let open = entity.clone(); | 444 | let open = entity.clone(); |
| 444 | 445 | ||
| @@ -460,7 +461,7 @@ impl Yumush { | |||
| 460 | .into_any_element() | 461 | .into_any_element() |
| 461 | } | 462 | } |
| 462 | 463 | ||
| 463 | - fn is_listed(&self, user_id: &str) -> bool { | 464 | + fn is_listed(&self, user_id: Id) -> bool { |
| 464 | self.chat | 465 | self.chat |
| 465 | .friends | 466 | .friends |
| 466 | .friends | 467 | .friends |
| @@ -469,7 +470,7 @@ impl Yumush { | |||
| 469 | || self.has_direct(user_id) | 470 | || self.has_direct(user_id) |
| 470 | } | 471 | } |
| 471 | 472 | ||
| 472 | - fn has_direct(&self, user_id: &str) -> bool { | 473 | + fn has_direct(&self, user_id: Id) -> bool { |
| 473 | self.chat.communities.iter().any(|community| { | 474 | self.chat.communities.iter().any(|community| { |
| 474 | matches!(&community.kind, CommunityKind::Direct { peer } if peer.id == user_id) | 475 | matches!(&community.kind, CommunityKind::Direct { peer } if peer.id == user_id) |
| 475 | }) | 476 | }) |
| @@ -483,7 +484,7 @@ impl Yumush { | |||
| 483 | .chain(self.chat.opened.as_ref()) | 484 | .chain(self.chat.opened.as_ref()) |
| 484 | .filter(|community| matches!(community.kind, CommunityKind::Group)) | 485 | .filter(|community| matches!(community.kind, CommunityKind::Group)) |
| 485 | .map(|community| { | 486 | .map(|community| { |
| 486 | - let active = self.chat.is_selected(&community.id); | 487 | + let active = self.chat.is_selected(community.id); |
| 487 | let muted = self.chat.muted.contains(&community.id); | 488 | let muted = self.chat.muted.contains(&community.id); |
| 488 | let can_leave = !active || permission::can_leave(self.actor_rank()); | 489 | let can_leave = !active || permission::can_leave(self.actor_rank()); |
| 489 | 490 | ||
| @@ -493,7 +494,7 @@ impl Yumush { | |||
| 493 | palette, | 494 | palette, |
| 494 | px(16.), | 495 | px(16.), |
| 495 | "community", | 496 | "community", |
| 496 | - community_menu(entity, community.id.clone(), can_leave, muted), | 497 | + community_menu(entity, community.id, can_leave, muted), |
| 497 | ) | 498 | ) |
| 498 | }), | 499 | }), |
| 499 | ) | 500 | ) |
| @@ -508,10 +509,10 @@ impl Yumush { | |||
| 508 | key: &str, | 509 | key: &str, |
| 509 | menu: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, | 510 | menu: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, |
| 510 | ) -> AnyElement { | 511 | ) -> AnyElement { |
| 511 | - let active = self.chat.is_selected(&community.id); | 512 | + let active = self.chat.is_selected(community.id); |
| 512 | let muted = self.chat.muted.contains(&community.id); | 513 | let muted = self.chat.muted.contains(&community.id); |
| 513 | let unread = self.chat.unread.get(&community.id); | 514 | let unread = self.chat.unread.get(&community.id); |
| 514 | - let community_id = community.id.clone(); | 515 | + let community_id = community.id; |
| 515 | let select = entity.clone(); | 516 | let select = entity.clone(); |
| 516 | 517 | ||
| 517 | let themed = palette.for_community(Some(community), &self.chat.hues); | 518 | let themed = palette.for_community(Some(community), &self.chat.hues); |
| @@ -528,7 +529,7 @@ impl Yumush { | |||
| 528 | ) | 529 | ) |
| 529 | .on_click(move |_, window, cx| { | 530 | .on_click(move |_, window, cx| { |
| 530 | select.update(cx, |yumush, cx| { | 531 | select.update(cx, |yumush, cx| { |
| 531 | - yumush.select_community(community_id.clone(), window, cx) | 532 | + yumush.select_community(community_id, window, cx) |
| 532 | }) | 533 | }) |
| 533 | }) | 534 | }) |
| 534 | .context_menu(menu) | 535 | .context_menu(menu) |
| @@ -567,7 +568,7 @@ impl Yumush { | |||
| 567 | .map(|community| { | 568 | .map(|community| { |
| 568 | let muted = self.chat.muted.contains(&community.id); | 569 | let muted = self.chat.muted.contains(&community.id); |
| 569 | let menu_entity = entity.clone(); | 570 | let menu_entity = entity.clone(); |
| 570 | - let menu_id = community.id.clone(); | 571 | + let menu_id = community.id; |
| 571 | 572 | ||
| 572 | self.sidebar_community_row( | 573 | self.sidebar_community_row( |
| 573 | entity, | 574 | entity, |
| @@ -575,7 +576,7 @@ impl Yumush { | |||
| 575 | palette, | 576 | palette, |
| 576 | px(20.), | 577 | px(20.), |
| 577 | "direct", | 578 | "direct", |
| 578 | - move |menu, _, _| mute_item(menu, &menu_entity, menu_id.clone(), muted), | 579 | + move |menu, _, _| mute_item(menu, &menu_entity, menu_id, muted), |
| 579 | ) | 580 | ) |
| 580 | }) | 581 | }) |
| 581 | .collect() | 582 | .collect() |
| @@ -586,12 +587,12 @@ impl Yumush { | |||
| 586 | .friends | 587 | .friends |
| 587 | .friends | 588 | .friends |
| 588 | .iter() | 589 | .iter() |
| 589 | - .filter(|user| matches_query(&user.username, query) && !self.has_direct(&user.id)) | 590 | + .filter(|user| matches_query(&user.username, query) && !self.has_direct(user.id)) |
| 590 | .map(|user| { | 591 | .map(|user| { |
| 591 | - let user_id = user.id.clone(); | 592 | + let user_id = user.id; |
| 592 | let open = entity.clone(); | 593 | let open = entity.clone(); |
| 593 | let remove = entity.clone(); | 594 | let remove = entity.clone(); |
| 594 | - let remove_id = user.id.clone(); | 595 | + let remove_id = user.id; |
| 595 | 596 | ||
| 596 | hoverable( | 597 | hoverable( |
| 597 | format!("friend_{}", user.id), | 598 | format!("friend_{}", user.id), |
| @@ -599,16 +600,14 @@ impl Yumush { | |||
| 599 | palette, | 600 | palette, |
| 600 | ) | 601 | ) |
| 601 | .on_click(move |_, window, cx| { | 602 | .on_click(move |_, window, cx| { |
| 602 | - open.update(cx, |yumush, cx| { | 603 | + open.update(cx, |yumush, cx| yumush.open_direct(user_id, window, cx)) |
| 603 | - yumush.open_direct(user_id.clone(), window, cx) | ||
| 604 | - }) | ||
| 605 | }) | 604 | }) |
| 606 | .context_menu(move |menu, _, _| { | 605 | .context_menu(move |menu, _, _| { |
| 607 | menu_action( | 606 | menu_action( |
| 608 | menu, | 607 | menu, |
| 609 | "Remove friend", | 608 | "Remove friend", |
| 610 | &remove, | 609 | &remove, |
| 611 | - remove_id.clone(), | 610 | + remove_id, |
| 612 | |yumush, id, window, cx| yumush.remove_friend(id, window, cx), | 611 | |yumush, id, window, cx| yumush.remove_friend(id, window, cx), |
| 613 | ) | 612 | ) |
| 614 | }) | 613 | }) |
| @@ -618,14 +617,14 @@ impl Yumush { | |||
| 618 | } | 617 | } |
| 619 | 618 | ||
| 620 | fn found_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement { | 619 | fn found_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement { |
| 621 | - let relation = self.relation(&user.id); | 620 | + let relation = self.relation(user.id); |
| 622 | let mut trailing = Vec::new(); | 621 | let mut trailing = Vec::new(); |
| 623 | 622 | ||
| 624 | if relation != Relation::Myself { | 623 | if relation != Relation::Myself { |
| 625 | trailing.push(row_button( | 624 | trailing.push(row_button( |
| 626 | entity, | 625 | entity, |
| 627 | "message", | 626 | "message", |
| 628 | - &user.id, | 627 | + user.id, |
| 629 | palette, | 628 | palette, |
| 630 | IconName::MessageSquare, | 629 | IconName::MessageSquare, |
| 631 | "Message", | 630 | "Message", |
| @@ -640,7 +639,7 @@ impl Yumush { | |||
| 640 | trailing.push(row_button( | 639 | trailing.push(row_button( |
| 641 | entity, | 640 | entity, |
| 642 | "friend_action", | 641 | "friend_action", |
| 643 | - &user.id, | 642 | + user.id, |
| 644 | palette, | 643 | palette, |
| 645 | icon, | 644 | icon, |
| 646 | label, | 645 | label, |
| @@ -662,7 +661,7 @@ impl Yumush { | |||
| 662 | false, | 661 | false, |
| 663 | presence_avatar( | 662 | presence_avatar( |
| 664 | avatar(palette, user, px(20.), text(10.), &self.chat.avatars), | 663 | avatar(palette, user, px(20.), text(10.), &self.chat.avatars), |
| 665 | - self.presence_of(&user.id), | 664 | + self.presence_of(user.id), |
| 666 | px(20.), | 665 | px(20.), |
| 667 | palette, | 666 | palette, |
| 668 | ), | 667 | ), |
| @@ -679,7 +678,7 @@ impl Yumush { | |||
| 679 | row_button( | 678 | row_button( |
| 680 | entity, | 679 | entity, |
| 681 | "accept_friend", | 680 | "accept_friend", |
| 682 | - &user.id, | 681 | + user.id, |
| 683 | palette, | 682 | palette, |
| 684 | IconName::Check, | 683 | IconName::Check, |
| 685 | "Accept", | 684 | "Accept", |
| @@ -688,7 +687,7 @@ impl Yumush { | |||
| 688 | row_button( | 687 | row_button( |
| 689 | entity, | 688 | entity, |
| 690 | "decline_friend", | 689 | "decline_friend", |
| 691 | - &user.id, | 690 | + user.id, |
| 692 | palette, | 691 | palette, |
| 693 | IconName::X, | 692 | IconName::X, |
| 694 | "Decline", | 693 | "Decline", |
| @@ -706,7 +705,7 @@ impl Yumush { | |||
| 706 | [row_button( | 705 | [row_button( |
| 707 | entity, | 706 | entity, |
| 708 | "cancel_friend", | 707 | "cancel_friend", |
| 709 | - &user.id, | 708 | + user.id, |
| 710 | palette, | 709 | palette, |
| 711 | IconName::X, | 710 | IconName::X, |
| 712 | "Cancel", | 711 | "Cancel", |
| @@ -739,7 +738,7 @@ impl Yumush { | |||
| 739 | row_button( | 738 | row_button( |
| 740 | entity, | 739 | entity, |
| 741 | "accept_invitation", | 740 | "accept_invitation", |
| 742 | - &community.id, | 741 | + community.id, |
| 743 | palette, | 742 | palette, |
| 744 | IconName::Check, | 743 | IconName::Check, |
| 745 | "Accept", | 744 | "Accept", |
| @@ -748,7 +747,7 @@ impl Yumush { | |||
| 748 | row_button( | 747 | row_button( |
| 749 | entity, | 748 | entity, |
| 750 | "decline_invitation", | 749 | "decline_invitation", |
| 751 | - &community.id, | 750 | + community.id, |
| 752 | palette, | 751 | palette, |
| 753 | IconName::X, | 752 | IconName::X, |
| 754 | "Decline", | 753 | "Decline", |
| @@ -806,7 +805,7 @@ impl Yumush { | |||
| 806 | .rounded(px(6.)) | 805 | .rounded(px(6.)) |
| 807 | .child(presence_avatar( | 806 | .child(presence_avatar( |
| 808 | avatar(palette, user, px(24.), text(12.), &self.chat.avatars), | 807 | avatar(palette, user, px(24.), text(12.), &self.chat.avatars), |
| 809 | - self.presence_of(&user.id), | 808 | + self.presence_of(user.id), |
| 810 | px(24.), | 809 | px(24.), |
| 811 | palette, | 810 | palette, |
| 812 | )) | 811 | )) |
| @@ -837,7 +836,7 @@ impl Yumush { | |||
| 837 | 836 | ||
| 838 | pub(super) fn open_community_settings( | 837 | pub(super) fn open_community_settings( |
| 839 | &mut self, | 838 | &mut self, |
| 840 | - community_id: String, | 839 | + community_id: Id, |
| 841 | window: &mut Window, | 840 | window: &mut Window, |
| 842 | cx: &mut Context<Self>, | 841 | cx: &mut Context<Self>, |
| 843 | ) { | 842 | ) { |
| @@ -851,10 +850,10 @@ fn go_to_call( | |||
| 851 | community: &Community, | 850 | community: &Community, |
| 852 | ) -> impl Fn(&mut Window, &mut App) + 'static { | 851 | ) -> impl Fn(&mut Window, &mut App) + 'static { |
| 853 | let direct = community.kind.is_direct(); | 852 | let direct = community.kind.is_direct(); |
| 854 | - let go_id = community.id.clone(); | 853 | + let go_id = community.id; |
| 855 | 854 | ||
| 856 | entity_action(entity, move |yumush, window, cx| { | 855 | entity_action(entity, move |yumush, window, cx| { |
| 857 | - yumush.go_to_community(go_id.clone(), direct, window, cx) | 856 | + yumush.go_to_community(go_id, direct, window, cx) |
| 858 | }) | 857 | }) |
| 859 | } | 858 | } |
| 860 | 859 | ||
| @@ -905,25 +904,20 @@ pub(super) fn unread_badge( | |||
| 905 | ) | 904 | ) |
| 906 | } | 905 | } |
| 907 | 906 | ||
| 908 | -fn mute_item( | 907 | +fn mute_item(menu: PopupMenu, entity: &Entity<Yumush>, community_id: Id, muted: bool) -> PopupMenu { |
| 909 | - menu: PopupMenu, | ||
| 910 | - entity: &Entity<Yumush>, | ||
| 911 | - community_id: String, | ||
| 912 | - muted: bool, | ||
| 913 | -) -> PopupMenu { | ||
| 914 | let entity = entity.clone(); | 908 | let entity = entity.clone(); |
| 915 | let label = if muted { "Unmute" } else { "Mute" }; | 909 | let label = if muted { "Unmute" } else { "Mute" }; |
| 916 | 910 | ||
| 917 | menu.item(PopupMenuItem::new(label).on_click(move |_, _, cx| { | 911 | menu.item(PopupMenuItem::new(label).on_click(move |_, _, cx| { |
| 918 | entity.update(cx, |yumush, cx| { | 912 | entity.update(cx, |yumush, cx| { |
| 919 | - yumush.toggle_community_mute(community_id.clone(), cx) | 913 | + yumush.toggle_community_mute(community_id, cx) |
| 920 | }) | 914 | }) |
| 921 | })) | 915 | })) |
| 922 | } | 916 | } |
| 923 | 917 | ||
| 924 | fn community_menu( | 918 | fn community_menu( |
| 925 | entity: &Entity<Yumush>, | 919 | entity: &Entity<Yumush>, |
| 926 | - community_id: String, | 920 | + community_id: Id, |
| 927 | can_leave: bool, | 921 | can_leave: bool, |
| 928 | muted: bool, | 922 | muted: bool, |
| 929 | ) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static { | 923 | ) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static { |
| @@ -934,17 +928,17 @@ fn community_menu( | |||
| 934 | menu, | 928 | menu, |
| 935 | "Invite", | 929 | "Invite", |
| 936 | &entity, | 930 | &entity, |
| 937 | - community_id.clone(), | 931 | + community_id, |
| 938 | |yumush, id, window, cx| yumush.open_invite(id, window, cx), | 932 | |yumush, id, window, cx| yumush.open_invite(id, window, cx), |
| 939 | ); | 933 | ); |
| 940 | let menu = menu_action( | 934 | let menu = menu_action( |
| 941 | menu, | 935 | menu, |
| 942 | "Settings", | 936 | "Settings", |
| 943 | &entity, | 937 | &entity, |
| 944 | - community_id.clone(), | 938 | + community_id, |
| 945 | |yumush, id, window, cx| yumush.open_community_settings(id, window, cx), | 939 | |yumush, id, window, cx| yumush.open_community_settings(id, window, cx), |
| 946 | ); | 940 | ); |
| 947 | - let menu = mute_item(menu, &entity, community_id.clone(), muted); | 941 | + let menu = mute_item(menu, &entity, community_id, muted); |
| 948 | 942 | ||
| 949 | if !can_leave { | 943 | if !can_leave { |
| 950 | return menu; | 944 | return menu; |
| @@ -954,7 +948,7 @@ fn community_menu( | |||
| 954 | menu, | 948 | menu, |
| 955 | "Leave", | 949 | "Leave", |
| 956 | &entity, | 950 | &entity, |
| 957 | - community_id.clone(), | 951 | + community_id, |
| 958 | |yumush, id, window, cx| yumush.leave_community(id, window, cx), | 952 | |yumush, id, window, cx| yumush.leave_community(id, window, cx), |
| 959 | ) | 953 | ) |
| 960 | } | 954 | } |
| @@ -1043,21 +1037,19 @@ fn entry( | |||
| 1043 | fn row_button( | 1037 | fn row_button( |
| 1044 | entity: &Entity<Yumush>, | 1038 | entity: &Entity<Yumush>, |
| 1045 | key: &str, | 1039 | key: &str, |
| 1046 | - id: &str, | 1040 | + id: Id, |
| 1047 | palette: Palette, | 1041 | palette: Palette, |
| 1048 | icon: IconName, | 1042 | icon: IconName, |
| 1049 | tip: &'static str, | 1043 | tip: &'static str, |
| 1050 | - run: impl Fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>) + 'static, | 1044 | + run: impl Fn(&mut Yumush, Id, &mut Window, &mut Context<Yumush>) + 'static, |
| 1051 | ) -> AnyElement { | 1045 | ) -> AnyElement { |
| 1052 | - let id = id.to_string(); | ||
| 1053 | - | ||
| 1054 | icon_button( | 1046 | icon_button( |
| 1055 | format!("{key}_{id}"), | 1047 | format!("{key}_{id}"), |
| 1056 | palette, | 1048 | palette, |
| 1057 | icon, | 1049 | icon, |
| 1058 | tip, | 1050 | tip, |
| 1059 | entity_action(entity, move |yumush, window, cx| { | 1051 | entity_action(entity, move |yumush, window, cx| { |
| 1060 | - run(yumush, id.clone(), window, cx) | 1052 | + run(yumush, id, window, cx) |
| 1061 | }), | 1053 | }), |
| 1062 | ) | 1054 | ) |
| 1063 | .into_any_element() | 1055 | .into_any_element() |
| @@ -1067,12 +1059,14 @@ fn menu_action( | |||
| 1067 | menu: PopupMenu, | 1059 | menu: PopupMenu, |
| 1068 | label: &'static str, | 1060 | label: &'static str, |
| 1069 | entity: &Entity<Yumush>, | 1061 | entity: &Entity<Yumush>, |
| 1070 | - id: String, | 1062 | + id: Id, |
| 1071 | - run: impl Fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>) + 'static, | 1063 | + run: impl Fn(&mut Yumush, Id, &mut Window, &mut Context<Yumush>) + 'static, |
| 1072 | ) -> PopupMenu { | 1064 | ) -> PopupMenu { |
| 1073 | let entity = entity.clone(); | 1065 | let entity = entity.clone(); |
| 1074 | 1066 | ||
| 1075 | - menu.item(PopupMenuItem::new(label).on_click(move |_, window, cx| { | 1067 | + menu.item( |
| 1076 | - entity.update(cx, |yumush, cx| run(yumush, id.clone(), window, cx)) | 1068 | + PopupMenuItem::new(label).on_click(move |_, window, cx| { |
| 1077 | - })) | 1069 | + entity.update(cx, |yumush, cx| run(yumush, id, window, cx)) |
| 1070 | + }), | ||
| 1071 | + ) | ||
| 1078 | } | 1072 | } |
crates/client/src/gui/snippet.rsmodified+8 -7
| @@ -7,7 +7,7 @@ use gpui_kit::{ | |||
| 7 | }; | 7 | }; |
| 8 | 8 | ||
| 9 | use super::{ | 9 | use super::{ |
| 10 | - Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link, | 10 | + Palette, Yumush, avatar, chat::Chat, media_view, millis_time, poll, profile::user_link, |
| 11 | widget::panel, | 11 | widget::panel, |
| 12 | }; | 12 | }; |
| 13 | 13 | ||
| @@ -50,12 +50,13 @@ fn snippet_row( | |||
| 50 | entity: &Entity<Yumush>, | 50 | entity: &Entity<Yumush>, |
| 51 | palette: Palette, | 51 | palette: Palette, |
| 52 | ) -> impl IntoElement { | 52 | ) -> impl IntoElement { |
| 53 | - let user = chat.author(&item.user_id).cloned().unwrap_or_else(|| User { | 53 | + let user = chat.author(item.user_id).cloned().unwrap_or_else(|| User { |
| 54 | - id: item.user_id.clone(), | 54 | + id: item.user_id, |
| 55 | username: item.username.clone(), | 55 | username: item.username.clone(), |
| 56 | role: Role::User, | 56 | role: Role::User, |
| 57 | status: String::new(), | 57 | status: String::new(), |
| 58 | - avatar_id: item.avatar_id.clone(), | 58 | + avatar_id: item.avatar_id, |
| 59 | + created_at: item.created_at, | ||
| 59 | }); | 60 | }); |
| 60 | 61 | ||
| 61 | div() | 62 | div() |
| @@ -85,14 +86,14 @@ fn snippet_row( | |||
| 85 | entity, | 86 | entity, |
| 86 | div() | 87 | div() |
| 87 | .font_weight(FontWeight::SEMIBOLD) | 88 | .font_weight(FontWeight::SEMIBOLD) |
| 88 | - .text_color(palette.tinted(&item.user_id)) | 89 | + .text_color(palette.tinted(item.user_id)) |
| 89 | .child(item.username.clone()), | 90 | .child(item.username.clone()), |
| 90 | )) | 91 | )) |
| 91 | .child( | 92 | .child( |
| 92 | div() | 93 | div() |
| 93 | .text_size(text(11.)) | 94 | .text_size(text(11.)) |
| 94 | .text_color(palette.muted) | 95 | .text_color(palette.muted) |
| 95 | - .child(id_time(&item.id, CLOCK)), | 96 | + .child(millis_time(item.created_at, CLOCK)), |
| 96 | ), | 97 | ), |
| 97 | ) | 98 | ) |
| 98 | .when(!item.body.is_empty(), |this| { | 99 | .when(!item.body.is_empty(), |this| { |
| @@ -112,7 +113,7 @@ fn snippet_row( | |||
| 112 | .children(item.poll.as_ref().map(|poll| { | 113 | .children(item.poll.as_ref().map(|poll| { |
| 113 | poll::poll_card( | 114 | poll::poll_card( |
| 114 | poll, | 115 | poll, |
| 115 | - poll::PollMode::Snapshot(&item.id), | 116 | + poll::PollMode::Snapshot(item.id), |
| 116 | None, | 117 | None, |
| 117 | chat, | 118 | chat, |
| 118 | entity, | 119 | entity, |
crates/client/src/gui/social.rsmodified+27 -40
| @@ -1,3 +1,4 @@ | |||
| 1 | +use common::model::Id; | ||
| 1 | use std::{fmt::Display, future::Future}; | 2 | use std::{fmt::Display, future::Future}; |
| 2 | 3 | ||
| 3 | use common::{ | 4 | use common::{ |
| @@ -71,7 +72,7 @@ fn spawn_community<E: Display + 'static>( | |||
| 71 | } | 72 | } |
| 72 | 73 | ||
| 73 | impl Yumush { | 74 | impl Yumush { |
| 74 | - pub(super) fn relation(&self, user_id: &str) -> Relation { | 75 | + pub(super) fn relation(&self, user_id: Id) -> Relation { |
| 75 | let friends = &self.chat.friends; | 76 | let friends = &self.chat.friends; |
| 76 | 77 | ||
| 77 | if self.is_me(user_id) { | 78 | if self.is_me(user_id) { |
| @@ -108,17 +109,17 @@ impl Yumush { | |||
| 108 | CommunityKind::Group | CommunityKind::Notes => None, | 109 | CommunityKind::Group | CommunityKind::Notes => None, |
| 109 | }), | 110 | }), |
| 110 | ); | 111 | ); |
| 111 | - let avatar_ids: Vec<String> = users | 112 | + let avatar_ids: Vec<Id> = users |
| 112 | - .filter_map(|user| user.avatar_id.clone()) | 113 | + .filter_map(|user| user.avatar_id) |
| 113 | .chain( | 114 | .chain( |
| 114 | chat.communities | 115 | chat.communities |
| 115 | .iter() | 116 | .iter() |
| 116 | - .filter_map(|community| community.avatar_id.clone()), | 117 | + .filter_map(|community| community.avatar_id), |
| 117 | ) | 118 | ) |
| 118 | .collect(); | 119 | .collect(); |
| 119 | 120 | ||
| 120 | for avatar_id in avatar_ids { | 121 | for avatar_id in avatar_ids { |
| 121 | - self.request_avatar(&avatar_id, cx); | 122 | + self.request_avatar(avatar_id, cx); |
| 122 | } | 123 | } |
| 123 | } | 124 | } |
| 124 | 125 | ||
| @@ -181,13 +182,13 @@ impl Yumush { | |||
| 181 | 182 | ||
| 182 | pub(super) fn open_found(&self, window: &mut Window, cx: &mut Context<Self>) { | 183 | pub(super) fn open_found(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 183 | if let Some(user) = &self.chat.found { | 184 | if let Some(user) = &self.chat.found { |
| 184 | - self.open_direct(user.id.clone(), window, cx); | 185 | + self.open_direct(user.id, window, cx); |
| 185 | } | 186 | } |
| 186 | } | 187 | } |
| 187 | 188 | ||
| 188 | pub(super) fn open_notes(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 189 | pub(super) fn open_notes(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 189 | if let Some(notes) = self.chat.notes() { | 190 | if let Some(notes) = self.chat.notes() { |
| 190 | - let community_id = notes.id.clone(); | 191 | + let community_id = notes.id; |
| 191 | self.select_community(community_id, window, cx); | 192 | self.select_community(community_id, window, cx); |
| 192 | return; | 193 | return; |
| 193 | } | 194 | } |
| @@ -196,7 +197,7 @@ impl Yumush { | |||
| 196 | spawn_community(window, cx, async move { network.call(OpenNotes).await }); | 197 | spawn_community(window, cx, async move { network.call(OpenNotes).await }); |
| 197 | } | 198 | } |
| 198 | 199 | ||
| 199 | - pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) { | 200 | + pub(super) fn open_direct(&self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 200 | let network = self.network.clone(); | 201 | let network = self.network.clone(); |
| 201 | 202 | ||
| 202 | spawn_community(window, cx, async move { | 203 | spawn_community(window, cx, async move { |
| @@ -207,7 +208,7 @@ impl Yumush { | |||
| 207 | pub(super) fn friend_action( | 208 | pub(super) fn friend_action( |
| 208 | &self, | 209 | &self, |
| 209 | relation: Relation, | 210 | relation: Relation, |
| 210 | - user_id: String, | 211 | + user_id: Id, |
| 211 | window: &mut Window, | 212 | window: &mut Window, |
| 212 | cx: &mut Context<Self>, | 213 | cx: &mut Context<Self>, |
| 213 | ) { | 214 | ) { |
| @@ -219,7 +220,7 @@ impl Yumush { | |||
| 219 | } | 220 | } |
| 220 | } | 221 | } |
| 221 | 222 | ||
| 222 | - pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) { | 223 | + pub(super) fn add_friend(&self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 223 | let network = self.network.clone(); | 224 | let network = self.network.clone(); |
| 224 | 225 | ||
| 225 | spawn_done(window, cx, async move { | 226 | spawn_done(window, cx, async move { |
| @@ -227,12 +228,7 @@ impl Yumush { | |||
| 227 | }); | 228 | }); |
| 228 | } | 229 | } |
| 229 | 230 | ||
| 230 | - pub(super) fn accept_friend( | 231 | + pub(super) fn accept_friend(&self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 231 | - &self, | ||
| 232 | - user_id: String, | ||
| 233 | - window: &mut Window, | ||
| 234 | - cx: &mut Context<Self>, | ||
| 235 | - ) { | ||
| 236 | let network = self.network.clone(); | 232 | let network = self.network.clone(); |
| 237 | 233 | ||
| 238 | spawn_done(window, cx, async move { | 234 | spawn_done(window, cx, async move { |
| @@ -240,12 +236,7 @@ impl Yumush { | |||
| 240 | }); | 236 | }); |
| 241 | } | 237 | } |
| 242 | 238 | ||
| 243 | - pub(super) fn remove_friend( | 239 | + pub(super) fn remove_friend(&self, user_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 244 | - &self, | ||
| 245 | - user_id: String, | ||
| 246 | - window: &mut Window, | ||
| 247 | - cx: &mut Context<Self>, | ||
| 248 | - ) { | ||
| 249 | let network = self.network.clone(); | 240 | let network = self.network.clone(); |
| 250 | 241 | ||
| 251 | spawn_done(window, cx, async move { | 242 | spawn_done(window, cx, async move { |
| @@ -255,7 +246,7 @@ impl Yumush { | |||
| 255 | 246 | ||
| 256 | pub(super) fn accept_invitation( | 247 | pub(super) fn accept_invitation( |
| 257 | &self, | 248 | &self, |
| 258 | - community_id: String, | 249 | + community_id: Id, |
| 259 | window: &mut Window, | 250 | window: &mut Window, |
| 260 | cx: &mut Context<Self>, | 251 | cx: &mut Context<Self>, |
| 261 | ) { | 252 | ) { |
| @@ -268,7 +259,7 @@ impl Yumush { | |||
| 268 | 259 | ||
| 269 | pub(super) fn decline_invitation( | 260 | pub(super) fn decline_invitation( |
| 270 | &self, | 261 | &self, |
| 271 | - community_id: String, | 262 | + community_id: Id, |
| 272 | window: &mut Window, | 263 | window: &mut Window, |
| 273 | cx: &mut Context<Self>, | 264 | cx: &mut Context<Self>, |
| 274 | ) { | 265 | ) { |
| @@ -281,21 +272,21 @@ impl Yumush { | |||
| 281 | 272 | ||
| 282 | pub(super) fn open_invite( | 273 | pub(super) fn open_invite( |
| 283 | &mut self, | 274 | &mut self, |
| 284 | - community_id: String, | 275 | + community_id: Id, |
| 285 | window: &mut Window, | 276 | window: &mut Window, |
| 286 | cx: &mut Context<Self>, | 277 | cx: &mut Context<Self>, |
| 287 | ) { | 278 | ) { |
| 288 | self.chat.invite = InviteLookup::Idle; | 279 | self.chat.invite = InviteLookup::Idle; |
| 289 | let input = new_input("Username...", window, cx); | 280 | let input = new_input("Username...", window, cx); |
| 290 | - let enter_id = community_id.clone(); | 281 | + let enter_id = community_id; |
| 291 | - let lookup_id = community_id.clone(); | 282 | + let lookup_id = community_id; |
| 292 | 283 | ||
| 293 | cx.subscribe_in( | 284 | cx.subscribe_in( |
| 294 | &input, | 285 | &input, |
| 295 | window, | 286 | window, |
| 296 | move |this, input, event, window, cx| match event { | 287 | move |this, input, event, window, cx| match event { |
| 297 | - InputEvent::Change => this.lookup_invite(lookup_id.clone(), input, window, cx), | 288 | + InputEvent::Change => this.lookup_invite(lookup_id, input, window, cx), |
| 298 | - InputEvent::PressEnter { .. } => this.send_invite(enter_id.clone(), window, cx), | 289 | + InputEvent::PressEnter { .. } => this.send_invite(enter_id, window, cx), |
| 299 | _ => {} | 290 | _ => {} |
| 300 | }, | 291 | }, |
| 301 | ) | 292 | ) |
| @@ -306,8 +297,7 @@ impl Yumush { | |||
| 306 | window.open_dialog(cx, move |dialog, _, cx| { | 297 | window.open_dialog(cx, move |dialog, _, cx| { |
| 307 | let yumush = entity.read(cx); | 298 | let yumush = entity.read(cx); |
| 308 | let palette = yumush.themed(cx); | 299 | let palette = yumush.themed(cx); |
| 309 | - let result = | 300 | + let result = invite_result(&yumush.chat.invite, community_id, &entity, yumush, palette); |
| 310 | - invite_result(&yumush.chat.invite, &community_id, &entity, yumush, palette); | ||
| 311 | 301 | ||
| 312 | dialog.title("Invite").child( | 302 | dialog.title("Invite").child( |
| 313 | div() | 303 | div() |
| @@ -325,7 +315,7 @@ impl Yumush { | |||
| 325 | 315 | ||
| 326 | fn lookup_invite( | 316 | fn lookup_invite( |
| 327 | &mut self, | 317 | &mut self, |
| 328 | - community_id: String, | 318 | + community_id: Id, |
| 329 | input: &Entity<InputState>, | 319 | input: &Entity<InputState>, |
| 330 | window: &mut Window, | 320 | window: &mut Window, |
| 331 | cx: &mut Context<Self>, | 321 | cx: &mut Context<Self>, |
| @@ -348,9 +338,7 @@ impl Yumush { | |||
| 348 | { | 338 | { |
| 349 | Ok(user) => { | 339 | Ok(user) => { |
| 350 | let members = network | 340 | let members = network |
| 351 | - .call(ListMembers { | 341 | + .call(ListMembers { community_id }) |
| 352 | - community_id: community_id.clone(), | ||
| 353 | - }) | ||
| 354 | .await | 342 | .await |
| 355 | .unwrap_or_default(); | 343 | .unwrap_or_default(); |
| 356 | if members.iter().any(|member| member.user.id == user.id) { | 344 | if members.iter().any(|member| member.user.id == user.id) { |
| @@ -375,12 +363,12 @@ impl Yumush { | |||
| 375 | .detach(); | 363 | .detach(); |
| 376 | } | 364 | } |
| 377 | 365 | ||
| 378 | - fn send_invite(&self, community_id: String, window: &mut Window, cx: &mut Context<Self>) { | 366 | + fn send_invite(&self, community_id: Id, window: &mut Window, cx: &mut Context<Self>) { |
| 379 | let InviteLookup::Found(user) = &self.chat.invite else { | 367 | let InviteLookup::Found(user) = &self.chat.invite else { |
| 380 | return; | 368 | return; |
| 381 | }; | 369 | }; |
| 382 | let network = self.network.clone(); | 370 | let network = self.network.clone(); |
| 383 | - let user_id = user.id.clone(); | 371 | + let user_id = user.id; |
| 384 | 372 | ||
| 385 | cx.spawn_in(window, async move |this, cx| { | 373 | cx.spawn_in(window, async move |this, cx| { |
| 386 | match network | 374 | match network |
| @@ -402,7 +390,7 @@ impl Yumush { | |||
| 402 | 390 | ||
| 403 | fn invite_result( | 391 | fn invite_result( |
| 404 | lookup: &InviteLookup, | 392 | lookup: &InviteLookup, |
| 405 | - community_id: &str, | 393 | + community_id: Id, |
| 406 | entity: &Entity<Yumush>, | 394 | entity: &Entity<Yumush>, |
| 407 | yumush: &Yumush, | 395 | yumush: &Yumush, |
| 408 | palette: Palette, | 396 | palette: Palette, |
| @@ -428,14 +416,13 @@ fn invite_result( | |||
| 428 | ), | 416 | ), |
| 429 | InviteLookup::Found(user) => { | 417 | InviteLookup::Found(user) => { |
| 430 | let entity = entity.clone(); | 418 | let entity = entity.clone(); |
| 431 | - let community_id = community_id.to_string(); | ||
| 432 | 419 | ||
| 433 | Some( | 420 | Some( |
| 434 | user_row(user, yumush, palette) | 421 | user_row(user, yumush, palette) |
| 435 | .child( | 422 | .child( |
| 436 | primary_button("invite_send", palette, move |window, cx| { | 423 | primary_button("invite_send", palette, move |window, cx| { |
| 437 | entity.update(cx, |yumush, cx| { | 424 | entity.update(cx, |yumush, cx| { |
| 438 | - yumush.send_invite(community_id.clone(), window, cx) | 425 | + yumush.send_invite(community_id, window, cx) |
| 439 | }) | 426 | }) |
| 440 | }) | 427 | }) |
| 441 | .h(px(30.)) | 428 | .h(px(30.)) |
crates/client/src/gui/voice_note.rsmodified+2 -2
| @@ -257,7 +257,7 @@ impl Yumush { | |||
| 257 | return; | 257 | return; |
| 258 | }; | 258 | }; |
| 259 | drain(&mut consumer, &mut samples); | 259 | drain(&mut consumer, &mut samples); |
| 260 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | 260 | + let Some(community_id) = self.chat.selected_community_id else { |
| 261 | return; | 261 | return; |
| 262 | }; | 262 | }; |
| 263 | let network = self.network.clone(); | 263 | let network = self.network.clone(); |
| @@ -276,7 +276,7 @@ impl Yumush { | |||
| 276 | return; | 276 | return; |
| 277 | }; | 277 | }; |
| 278 | let uploaded = | 278 | let uploaded = |
| 279 | - upload_file(&this, &network, &community_id, path.clone(), maximum, cx).await; | 279 | + upload_file(&this, &network, community_id, path.clone(), maximum, cx).await; |
| 280 | let _ = std::fs::remove_file(&path); | 280 | let _ = std::fs::remove_file(&path); |
| 281 | let attachment = match uploaded { | 281 | let attachment = match uploaded { |
| 282 | Ok(attachment) => attachment, | 282 | Ok(attachment) => attachment, |
crates/client/src/gui/voice_stats.rsmodified+5 -6
| @@ -1,6 +1,6 @@ | |||
| 1 | use std::collections::VecDeque; | 1 | use std::collections::VecDeque; |
| 2 | 2 | ||
| 3 | -use common::share::Layer; | 3 | +use common::{model::Id, share::Layer}; |
| 4 | use gpui_kit::{ | 4 | use gpui_kit::{ |
| 5 | Context, Div, Entity, FontWeight, Hsla, ParentElement, Styled, div, hsla, | 5 | Context, Div, Entity, FontWeight, Hsla, ParentElement, Styled, div, hsla, |
| 6 | prelude::FluentBuilder as _, px, | 6 | prelude::FluentBuilder as _, px, |
| @@ -224,12 +224,11 @@ fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div { | |||
| 224 | })) | 224 | })) |
| 225 | } | 225 | } |
| 226 | 226 | ||
| 227 | -fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palette) -> Div { | 227 | +fn watching_body(watching: &[(Id, WatchStats)], chat: &Chat, palette: Palette) -> Div { |
| 228 | column().children(watching.iter().map(|(user_id, stats)| { | 228 | column().children(watching.iter().map(|(user_id, stats)| { |
| 229 | - let name = chat.author(user_id).map_or_else( | 229 | + let name = chat |
| 230 | - || user_id.chars().take(8).collect(), | 230 | + .author(*user_id) |
| 231 | - |user| user.username.clone(), | 231 | + .map_or_else(|| user_id.to_string(), |user| user.username.clone()); |
| 232 | - ); | ||
| 233 | let tiles = [ | 232 | let tiles = [ |
| 234 | ("Bitrate", format!("{} kbps", stats.kbps)), | 233 | ("Bitrate", format!("{} kbps", stats.kbps)), |
| 235 | ("FPS", format!("{:.0}", stats.fps)), | 234 | ("FPS", format!("{:.0}", stats.fps)), |
crates/client/src/gui/wave.rsmodified+16 -18
| @@ -1,5 +1,6 @@ | |||
| 1 | use std::collections::{HashMap, HashSet, VecDeque}; | 1 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 2 | 2 | ||
| 3 | +use common::model::Id; | ||
| 3 | use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px}; | 4 | use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px}; |
| 4 | 5 | ||
| 5 | use crate::net::Levels; | 6 | use crate::net::Levels; |
| @@ -35,17 +36,17 @@ impl Wave { | |||
| 35 | 36 | ||
| 36 | #[derive(Default)] | 37 | #[derive(Default)] |
| 37 | pub struct Waves { | 38 | pub struct Waves { |
| 38 | - pub speaking: HashSet<String>, | 39 | + pub speaking: HashSet<Id>, |
| 39 | - voice: HashMap<String, Wave>, | 40 | + voice: HashMap<Id, Wave>, |
| 40 | - share: HashMap<String, Wave>, | 41 | + share: HashMap<Id, Wave>, |
| 41 | } | 42 | } |
| 42 | 43 | ||
| 43 | -fn advance(waves: &mut HashMap<String, Wave>, levels: Vec<(String, Vec<f32>)>) -> bool { | 44 | +fn advance(waves: &mut HashMap<Id, Wave>, levels: Vec<(Id, Vec<f32>)>) -> bool { |
| 44 | - let mut levels: HashMap<String, Vec<f32>> = levels.into_iter().collect(); | 45 | + let mut levels: HashMap<Id, Vec<f32>> = levels.into_iter().collect(); |
| 45 | - let ids: HashSet<String> = waves.keys().chain(levels.keys()).cloned().collect(); | 46 | + let ids: HashSet<Id> = waves.keys().chain(levels.keys()).copied().collect(); |
| 46 | for id in ids { | 47 | for id in ids { |
| 47 | let bands = levels.remove(&id).unwrap_or_default(); | 48 | let bands = levels.remove(&id).unwrap_or_default(); |
| 48 | - let wave = waves.entry(id.clone()).or_insert_with(Wave::new); | 49 | + let wave = waves.entry(id).or_insert_with(Wave::new); |
| 49 | wave.push(&bands); | 50 | wave.push(&bands); |
| 50 | if wave.silent() { | 51 | if wave.silent() { |
| 51 | waves.remove(&id); | 52 | waves.remove(&id); |
| @@ -55,22 +56,19 @@ fn advance(waves: &mut HashMap<String, Wave>, levels: Vec<(String, Vec<f32>)>) - | |||
| 55 | } | 56 | } |
| 56 | 57 | ||
| 57 | impl Waves { | 58 | impl Waves { |
| 58 | - pub fn update(&mut self, levels: Levels, me: Option<&str>, silent: bool) -> bool { | 59 | + pub fn update(&mut self, levels: Levels, me: Option<Id>, silent: bool) -> bool { |
| 59 | let mut voice = levels.voice; | 60 | let mut voice = levels.voice; |
| 60 | if silent { | 61 | if silent { |
| 61 | - voice.retain(|(id, _)| Some(id.as_str()) != me); | 62 | + voice.retain(|(id, _)| Some(*id) != me); |
| 62 | } | 63 | } |
| 63 | - let speaking: HashSet<String> = voice.iter().map(|(id, _)| id.clone()).collect(); | 64 | + let speaking: HashSet<Id> = voice.iter().map(|(id, _)| *id).collect(); |
| 64 | let mut changed = speaking != self.speaking; | 65 | let mut changed = speaking != self.speaking; |
| 65 | self.speaking = speaking; | 66 | self.speaking = speaking; |
| 66 | let had = !self.voice.is_empty() || !self.share.is_empty(); | 67 | let had = !self.voice.is_empty() || !self.share.is_empty(); |
| 67 | changed |= advance(&mut self.voice, voice); | 68 | changed |= advance(&mut self.voice, voice); |
| 68 | 69 | ||
| 69 | let mut share = levels.watching; | 70 | let mut share = levels.watching; |
| 70 | - share.extend( | 71 | + share.extend(me.zip(levels.sharing)); |
| 71 | - me.zip(levels.sharing) | ||
| 72 | - .map(|(id, levels)| (id.to_string(), levels)), | ||
| 73 | - ); | ||
| 74 | changed |= advance(&mut self.share, share); | 72 | changed |= advance(&mut self.share, share); |
| 75 | changed || had | 73 | changed || had |
| 76 | } | 74 | } |
| @@ -79,13 +77,13 @@ impl Waves { | |||
| 79 | *self = Self::default(); | 77 | *self = Self::default(); |
| 80 | } | 78 | } |
| 81 | 79 | ||
| 82 | - pub fn voice(&self, id: &str) -> Option<&VecDeque<f32>> { | 80 | + pub fn voice(&self, id: Id) -> Option<&VecDeque<f32>> { |
| 83 | - self.voice.get(id).map(|wave| &wave.bars) | 81 | + self.voice.get(&id).map(|wave| &wave.bars) |
| 84 | } | 82 | } |
| 85 | 83 | ||
| 86 | - pub fn share(&self, id: &str) -> Option<&VecDeque<f32>> { | 84 | + pub fn share(&self, id: Id) -> Option<&VecDeque<f32>> { |
| 87 | self.share | 85 | self.share |
| 88 | - .get(id) | 86 | + .get(&id) |
| 89 | .filter(|wave| wave.bars.iter().any(|bar| *bar >= AUDIBLE)) | 87 | .filter(|wave| wave.bars.iter().any(|bar| *bar >= AUDIBLE)) |
| 90 | .map(|wave| &wave.bars) | 88 | .map(|wave| &wave.bars) |
| 91 | } | 89 | } |
crates/client/src/mutes.rsmodified+6 -4
| @@ -1,12 +1,14 @@ | |||
| 1 | use std::collections::HashSet; | 1 | use std::collections::HashSet; |
| 2 | 2 | ||
| 3 | +use common::model::Id; | ||
| 4 | + | ||
| 3 | use crate::{read_config, write_config}; | 5 | use crate::{read_config, write_config}; |
| 4 | 6 | ||
| 5 | -fn prefix(account_user_id: &str) -> String { | 7 | +fn prefix(account_user_id: Id) -> String { |
| 6 | format!("{account_user_id}\t") | 8 | format!("{account_user_id}\t") |
| 7 | } | 9 | } |
| 8 | 10 | ||
| 9 | -pub fn load(account_user_id: &str) -> HashSet<String> { | 11 | +pub fn load(account_user_id: Id) -> HashSet<Id> { |
| 10 | let Some(content) = read_config("mutes") else { | 12 | let Some(content) = read_config("mutes") else { |
| 11 | return HashSet::new(); | 13 | return HashSet::new(); |
| 12 | }; | 14 | }; |
| @@ -15,11 +17,11 @@ pub fn load(account_user_id: &str) -> HashSet<String> { | |||
| 15 | content | 17 | content |
| 16 | .lines() | 18 | .lines() |
| 17 | .filter_map(|line| line.strip_prefix(&prefix)) | 19 | .filter_map(|line| line.strip_prefix(&prefix)) |
| 18 | - .map(String::from) | 20 | + .filter_map(|community_id| community_id.parse().ok()) |
| 19 | .collect() | 21 | .collect() |
| 20 | } | 22 | } |
| 21 | 23 | ||
| 22 | -pub fn save(account_user_id: &str, muted: &HashSet<String>) { | 24 | +pub fn save(account_user_id: Id, muted: &HashSet<Id>) { |
| 23 | let prefix = prefix(account_user_id); | 25 | let prefix = prefix(account_user_id); |
| 24 | let mut content: String = read_config("mutes") | 26 | let mut content: String = read_config("mutes") |
| 25 | .unwrap_or_default() | 27 | .unwrap_or_default() |
crates/client/src/net/link.rsmodified+5 -5
| @@ -5,19 +5,19 @@ use common::{ | |||
| 5 | constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, | 5 | constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, |
| 6 | error::Error, | 6 | error::Error, |
| 7 | frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX}, | 7 | frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX}, |
| 8 | - model::{Attachment, User}, | 8 | + model::{Attachment, Id, User}, |
| 9 | open::{Blob, Open, Upload}, | 9 | open::{Blob, Open, Upload}, |
| 10 | session::{Hello, Welcome}, | 10 | session::{Hello, Welcome}, |
| 11 | transport::{ALPN, Close, transport}, | 11 | transport::{ALPN, Close, transport}, |
| 12 | validate::{validate_attachment_name, validate_attachment_size}, | 12 | validate::{validate_attachment_name, validate_attachment_size}, |
| 13 | }; | 13 | }; |
| 14 | -use quinn::{Endpoint, crypto::rustls::QuicClientConfig, rustls}; | ||
| 15 | #[cfg(debug_assertions)] | 14 | #[cfg(debug_assertions)] |
| 16 | use quinn::rustls::{ | 15 | use quinn::rustls::{ |
| 17 | DigitallySignedStruct, SignatureScheme, | 16 | DigitallySignedStruct, SignatureScheme, |
| 18 | client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, | 17 | client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, |
| 19 | pki_types::{CertificateDer, ServerName, UnixTime}, | 18 | pki_types::{CertificateDer, ServerName, UnixTime}, |
| 20 | }; | 19 | }; |
| 20 | +use quinn::{Endpoint, crypto::rustls::QuicClientConfig, rustls}; | ||
| 21 | #[cfg(debug_assertions)] | 21 | #[cfg(debug_assertions)] |
| 22 | use rustls_platform_verifier as _; | 22 | use rustls_platform_verifier as _; |
| 23 | use tokio::{ | 23 | use tokio::{ |
| @@ -266,7 +266,7 @@ async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result< | |||
| 266 | 266 | ||
| 267 | pub(super) async fn upload( | 267 | pub(super) async fn upload( |
| 268 | connection: &quinn::Connection, | 268 | connection: &quinn::Connection, |
| 269 | - community_id: &str, | 269 | + community_id: Id, |
| 270 | path: &Path, | 270 | path: &Path, |
| 271 | maximum: Option<u64>, | 271 | maximum: Option<u64>, |
| 272 | ) -> Result<Attachment, Fail> { | 272 | ) -> Result<Attachment, Fail> { |
| @@ -285,7 +285,7 @@ pub(super) async fn upload( | |||
| 285 | let (send_stream, mut receive_stream) = connection.open_bi().await?; | 285 | let (send_stream, mut receive_stream) = connection.open_bi().await?; |
| 286 | let mut send_stream = Sending::new(send_stream); | 286 | let mut send_stream = Sending::new(send_stream); |
| 287 | let header = Upload { | 287 | let header = Upload { |
| 288 | - community_id: community_id.to_string(), | 288 | + community_id, |
| 289 | name, | 289 | name, |
| 290 | size, | 290 | size, |
| 291 | }; | 291 | }; |
| @@ -476,7 +476,7 @@ async fn actor( | |||
| 476 | Some(Command::Upload { community_id, path, maximum, reply }) => { | 476 | Some(Command::Upload { community_id, path, maximum, reply }) => { |
| 477 | let connection = connection.clone(); | 477 | let connection = connection.clone(); |
| 478 | 478 | ||
| 479 | - answer(reply, async move { upload(&connection, &community_id, &path, maximum).await }); | 479 | + answer(reply, async move { upload(&connection, community_id, &path, maximum).await }); |
| 480 | } | 480 | } |
| 481 | Some(Command::Download { blob, reply }) => { | 481 | Some(Command::Download { blob, reply }) => { |
| 482 | let connection = connection.clone(); | 482 | let connection = connection.clone(); |
crates/client/src/net/media.rsmodified+37 -58
| @@ -12,12 +12,12 @@ use common::{ | |||
| 12 | }, | 12 | }, |
| 13 | datagram::{Packet, RELAY_PREFIX}, | 13 | datagram::{Packet, RELAY_PREFIX}, |
| 14 | event::{Event, Media as Down}, | 14 | event::{Event, Media as Down}, |
| 15 | + model::Id, | ||
| 15 | share::{Fps, Kind, Quality, Resolution, Source}, | 16 | share::{Fps, Kind, Quality, Resolution, Source}, |
| 16 | }; | 17 | }; |
| 17 | use quinn::Connection; | 18 | use quinn::Connection; |
| 18 | use tokio::{runtime::Handle, sync::mpsc}; | 19 | use tokio::{runtime::Handle, sync::mpsc}; |
| 19 | use tracing::warn; | 20 | use tracing::warn; |
| 20 | -use uuid::Uuid; | ||
| 21 | 21 | ||
| 22 | use crate::{ | 22 | use crate::{ |
| 23 | settings::{ShareSettings, VoiceSettings}, | 23 | settings::{ShareSettings, VoiceSettings}, |
| @@ -43,7 +43,7 @@ const CAMERA_TOP: Quality = Quality { | |||
| 43 | 43 | ||
| 44 | #[derive(Clone)] | 44 | #[derive(Clone)] |
| 45 | struct Want { | 45 | struct Want { |
| 46 | - community_id: String, | 46 | + community_id: Id, |
| 47 | settings: VoiceSettings, | 47 | settings: VoiceSettings, |
| 48 | muted: bool, | 48 | muted: bool, |
| 49 | deafened: bool, | 49 | deafened: bool, |
| @@ -58,7 +58,7 @@ struct Inner { | |||
| 58 | joining: u32, | 58 | joining: u32, |
| 59 | mic_test: Option<Voice>, | 59 | mic_test: Option<Voice>, |
| 60 | sharing: HashMap<Kind, Sharing>, | 60 | sharing: HashMap<Kind, Sharing>, |
| 61 | - watching: HashMap<(String, Kind), Watching>, | 61 | + watching: HashMap<(Id, Kind), Watching>, |
| 62 | } | 62 | } |
| 63 | 63 | ||
| 64 | impl Inner { | 64 | impl Inner { |
| @@ -86,12 +86,12 @@ impl Inner { | |||
| 86 | self.want_voice = Some(want); | 86 | self.want_voice = Some(want); |
| 87 | } | 87 | } |
| 88 | 88 | ||
| 89 | - fn watch_requests(&self) -> Vec<((String, Kind), WatchShare)> { | 89 | + fn watch_requests(&self) -> Vec<((Id, Kind), WatchShare)> { |
| 90 | self.watching | 90 | self.watching |
| 91 | .iter() | 91 | .iter() |
| 92 | .map(|((user_id, kind), watching)| { | 92 | .map(|((user_id, kind), watching)| { |
| 93 | - let request = watch_request(user_id.clone(), *kind, watching.wanted()); | 93 | + let request = watch_request(*user_id, *kind, watching.wanted()); |
| 94 | - ((user_id.clone(), *kind), request) | 94 | + ((*user_id, *kind), request) |
| 95 | }) | 95 | }) |
| 96 | .collect() | 96 | .collect() |
| 97 | } | 97 | } |
| @@ -177,7 +177,7 @@ impl Media { | |||
| 177 | want: Want, | 177 | want: Want, |
| 178 | events: mpsc::Sender<NetworkEvent>, | 178 | events: mpsc::Sender<NetworkEvent>, |
| 179 | ) { | 179 | ) { |
| 180 | - let joined = join(&connection, &want.community_id).await; | 180 | + let joined = join(&connection, want.community_id).await; |
| 181 | let next = { | 181 | let next = { |
| 182 | let mut inner = self.lock(); | 182 | let mut inner = self.lock(); |
| 183 | if !inner.current(epoch) { | 183 | if !inner.current(epoch) { |
| @@ -247,7 +247,7 @@ impl Media { | |||
| 247 | 247 | ||
| 248 | pub(super) fn pushed(&self, event: &Event) { | 248 | pub(super) fn pushed(&self, event: &Event) { |
| 249 | if let Event::ShareStopped { user_id, kind, .. } = event { | 249 | if let Event::ShareStopped { user_id, kind, .. } = event { |
| 250 | - self.lock().watching.remove(&(user_id.clone(), *kind)); | 250 | + self.lock().watching.remove(&(*user_id, *kind)); |
| 251 | } | 251 | } |
| 252 | } | 252 | } |
| 253 | 253 | ||
| @@ -285,7 +285,7 @@ impl Media { | |||
| 285 | Packet::ScreenAudio { .. } => Kind::Screen, | 285 | Packet::ScreenAudio { .. } => Kind::Screen, |
| 286 | Packet::Video { kind, .. } => kind, | 286 | Packet::Video { kind, .. } => kind, |
| 287 | }; | 287 | }; |
| 288 | - let key = (Uuid::from_bytes(*from).to_string(), kind); | 288 | + let key = (Id::from_be_bytes(*from), kind); |
| 289 | if let Some(watching) = inner.watching.get(&key) { | 289 | if let Some(watching) = inner.watching.get(&key) { |
| 290 | watching.receive(datagram, &packet); | 290 | watching.receive(datagram, &packet); |
| 291 | } | 291 | } |
| @@ -293,9 +293,9 @@ impl Media { | |||
| 293 | 293 | ||
| 294 | async fn join_voice( | 294 | async fn join_voice( |
| 295 | self: Arc<Self>, | 295 | self: Arc<Self>, |
| 296 | - community_id: String, | 296 | + community_id: Id, |
| 297 | settings: VoiceSettings, | 297 | settings: VoiceSettings, |
| 298 | - ) -> Result<Vec<String>, Fail> { | 298 | + ) -> Result<Vec<Id>, Fail> { |
| 299 | self.lock().joining += 1; | 299 | self.lock().joining += 1; |
| 300 | let result = self.join_voice_inner(community_id, settings).await; | 300 | let result = self.join_voice_inner(community_id, settings).await; |
| 301 | self.lock().joining -= 1; | 301 | self.lock().joining -= 1; |
| @@ -305,11 +305,11 @@ impl Media { | |||
| 305 | 305 | ||
| 306 | async fn join_voice_inner( | 306 | async fn join_voice_inner( |
| 307 | &self, | 307 | &self, |
| 308 | - community_id: String, | 308 | + community_id: Id, |
| 309 | settings: VoiceSettings, | 309 | settings: VoiceSettings, |
| 310 | - ) -> Result<Vec<String>, Fail> { | 310 | + ) -> Result<Vec<Id>, Fail> { |
| 311 | let (connection, epoch) = self.current_wait().await?; | 311 | let (connection, epoch) = self.current_wait().await?; |
| 312 | - let participants = join(&connection, &community_id).await?; | 312 | + let participants = join(&connection, community_id).await?; |
| 313 | let voice = voice::start(Some(connection), &settings); | 313 | let voice = voice::start(Some(connection), &settings); |
| 314 | let mut inner = self.lock(); | 314 | let mut inner = self.lock(); |
| 315 | if !inner.current(epoch) { | 315 | if !inner.current(epoch) { |
| @@ -397,7 +397,7 @@ impl Media { | |||
| 397 | } | 397 | } |
| 398 | } | 398 | } |
| 399 | 399 | ||
| 400 | -fn watch_request(user_id: String, kind: Kind, quality: Quality) -> WatchShare { | 400 | +fn watch_request(user_id: Id, kind: Kind, quality: Quality) -> WatchShare { |
| 401 | WatchShare { | 401 | WatchShare { |
| 402 | user_id, | 402 | user_id, |
| 403 | kind, | 403 | kind, |
| @@ -412,10 +412,8 @@ enum Rejoin { | |||
| 412 | Skip, | 412 | Skip, |
| 413 | } | 413 | } |
| 414 | 414 | ||
| 415 | -async fn join(connection: &Connection, community_id: &str) -> Result<Vec<String>, Fail> { | 415 | +async fn join(connection: &Connection, community_id: Id) -> Result<Vec<Id>, Fail> { |
| 416 | - let request = JoinVoice { | 416 | + let request = JoinVoice { community_id }; |
| 417 | - community_id: community_id.to_string(), | ||
| 418 | - }; | ||
| 419 | 417 | ||
| 420 | call(connection, request).await | 418 | call(connection, request).await |
| 421 | } | 419 | } |
| @@ -440,12 +438,12 @@ async fn tick_loop(media: Arc<Media>) { | |||
| 440 | match tick { | 438 | match tick { |
| 441 | Tick::Quality(quality) => tokio::spawn(send_quietly( | 439 | Tick::Quality(quality) => tokio::spawn(send_quietly( |
| 442 | connection, | 440 | connection, |
| 443 | - watch_request(user_id.clone(), *kind, quality), | 441 | + watch_request(*user_id, *kind, quality), |
| 444 | )), | 442 | )), |
| 445 | Tick::Keyframe => tokio::spawn(send_quietly( | 443 | Tick::Keyframe => tokio::spawn(send_quietly( |
| 446 | connection, | 444 | connection, |
| 447 | RequestKeyframe { | 445 | RequestKeyframe { |
| 448 | - user_id: user_id.clone(), | 446 | + user_id: *user_id, |
| 449 | kind: *kind, | 447 | kind: *kind, |
| 450 | }, | 448 | }, |
| 451 | )), | 449 | )), |
| @@ -462,14 +460,14 @@ impl NetworkHandle { | |||
| 462 | 460 | ||
| 463 | pub async fn join_voice( | 461 | pub async fn join_voice( |
| 464 | &self, | 462 | &self, |
| 465 | - community_id: &str, | 463 | + community_id: Id, |
| 466 | settings: &VoiceSettings, | 464 | settings: &VoiceSettings, |
| 467 | - ) -> Result<Vec<String>, Fail> { | 465 | + ) -> Result<Vec<Id>, Fail> { |
| 468 | self.media() | 466 | self.media() |
| 469 | .run( | 467 | .run( |
| 470 | self.media() | 468 | self.media() |
| 471 | .clone() | 469 | .clone() |
| 472 | - .join_voice(community_id.to_string(), settings.clone()), | 470 | + .join_voice(community_id, settings.clone()), |
| 473 | ) | 471 | ) |
| 474 | .await | 472 | .await |
| 475 | } | 473 | } |
| @@ -566,7 +564,7 @@ impl NetworkHandle { | |||
| 566 | .watching | 564 | .watching |
| 567 | .iter() | 565 | .iter() |
| 568 | .filter(|((_, kind), _)| *kind == Kind::Screen) | 566 | .filter(|((_, kind), _)| *kind == Kind::Screen) |
| 569 | - .map(|((user_id, _), watching)| (user_id.clone(), watching.level())) | 567 | + .map(|((user_id, _), watching)| (*user_id, watching.level())) |
| 570 | .collect(), | 568 | .collect(), |
| 571 | sharing: inner.sharing.get(&Kind::Screen).map(Sharing::level), | 569 | sharing: inner.sharing.get(&Kind::Screen).map(Sharing::level), |
| 572 | } | 570 | } |
| @@ -622,23 +620,20 @@ impl NetworkHandle { | |||
| 622 | .map(Sharing::source) | 620 | .map(Sharing::source) |
| 623 | } | 621 | } |
| 624 | 622 | ||
| 625 | - pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Fail> { | 623 | + pub async fn shares(&self, community_id: Id) -> Result<Vec<common::share::Share>, Fail> { |
| 626 | - self.call(ListShares { | 624 | + self.call(ListShares { community_id }).await |
| 627 | - community_id: community_id.to_string(), | ||
| 628 | - }) | ||
| 629 | - .await | ||
| 630 | } | 625 | } |
| 631 | 626 | ||
| 632 | pub async fn watch_share( | 627 | pub async fn watch_share( |
| 633 | &self, | 628 | &self, |
| 634 | - user_id: &str, | 629 | + user_id: Id, |
| 635 | kind: Kind, | 630 | kind: Kind, |
| 636 | watch: WatchQuality, | 631 | watch: WatchQuality, |
| 637 | volume: f32, | 632 | volume: f32, |
| 638 | choice: Choice, | 633 | choice: Choice, |
| 639 | ) -> Result<(), Fail> { | 634 | ) -> Result<(), Fail> { |
| 640 | let media = self.media().clone(); | 635 | let media = self.media().clone(); |
| 641 | - let key = (user_id.to_string(), kind); | 636 | + let key = (user_id, kind); |
| 642 | let watching = Watching::new(kind, watch, volume, choice); | 637 | let watching = Watching::new(kind, watch, volume, choice); |
| 643 | let quality = watching.wanted(); | 638 | let quality = watching.wanted(); |
| 644 | 639 | ||
| @@ -650,9 +645,9 @@ impl NetworkHandle { | |||
| 650 | if !inner.current(epoch) { | 645 | if !inner.current(epoch) { |
| 651 | return Err(Fail::Offline); | 646 | return Err(Fail::Offline); |
| 652 | } | 647 | } |
| 653 | - inner.watching.insert(key.clone(), watching); | 648 | + inner.watching.insert(key, watching); |
| 654 | } | 649 | } |
| 655 | - let result = call(&connection, watch_request(key.0.clone(), kind, quality)).await; | 650 | + let result = call(&connection, watch_request(key.0, kind, quality)).await; |
| 656 | if result.is_err() { | 651 | if result.is_err() { |
| 657 | media.lock().watching.remove(&key); | 652 | media.lock().watching.remove(&key); |
| 658 | } | 653 | } |
| @@ -662,26 +657,14 @@ impl NetworkHandle { | |||
| 662 | .await | 657 | .await |
| 663 | } | 658 | } |
| 664 | 659 | ||
| 665 | - pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Fail> { | 660 | + pub async fn unwatch_share(&self, user_id: Id, kind: Kind) -> Result<(), Fail> { |
| 666 | - self.media() | 661 | + self.media().lock().watching.remove(&(user_id, kind)); |
| 667 | - .lock() | ||
| 668 | - .watching | ||
| 669 | - .remove(&(user_id.to_string(), kind)); | ||
| 670 | 662 | ||
| 671 | - self.call(UnwatchShare { | 663 | + self.call(UnwatchShare { user_id, kind }).await |
| 672 | - user_id: user_id.to_string(), | ||
| 673 | - kind, | ||
| 674 | - }) | ||
| 675 | - .await | ||
| 676 | } | 664 | } |
| 677 | 665 | ||
| 678 | - pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { | 666 | + pub fn set_watch_quality(&self, user_id: Id, kind: Kind, quality: WatchQuality) { |
| 679 | - if let Some(watching) = self | 667 | + if let Some(watching) = self.media().lock().watching.get_mut(&(user_id, kind)) { |
| 680 | - .media() | ||
| 681 | - .lock() | ||
| 682 | - .watching | ||
| 683 | - .get_mut(&(user_id.to_string(), kind)) | ||
| 684 | - { | ||
| 685 | watching.set_quality(quality); | 668 | watching.set_quality(quality); |
| 686 | } | 669 | } |
| 687 | } | 670 | } |
| @@ -707,17 +690,13 @@ impl NetworkHandle { | |||
| 707 | .watching | 690 | .watching |
| 708 | .iter_mut() | 691 | .iter_mut() |
| 709 | .filter(|((_, kind), _)| *kind == Kind::Screen) | 692 | .filter(|((_, kind), _)| *kind == Kind::Screen) |
| 710 | - .map(|((user_id, _), watching)| (user_id.clone(), watching.stats())) | 693 | + .map(|((user_id, _), watching)| (*user_id, watching.stats())) |
| 711 | .collect(), | 694 | .collect(), |
| 712 | } | 695 | } |
| 713 | } | 696 | } |
| 714 | 697 | ||
| 715 | - pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> { | 698 | + pub fn share_frame(&self, user_id: Id, kind: Kind) -> Option<crate::media::Frame> { |
| 716 | - self.media() | 699 | + self.media().lock().watching.get(&(user_id, kind))?.frame() |
| 717 | - .lock() | ||
| 718 | - .watching | ||
| 719 | - .get(&(user_id.to_string(), kind))? | ||
| 720 | - .frame() | ||
| 721 | } | 700 | } |
| 722 | 701 | ||
| 723 | pub fn audio_apps(&self) -> Vec<AudioApp> { | 702 | pub fn audio_apps(&self) -> Vec<AudioApp> { |
crates/client/src/net/mod.rsmodified+9 -10
| @@ -3,7 +3,7 @@ use std::{path::PathBuf, sync::Arc}; | |||
| 3 | use common::{ | 3 | use common::{ |
| 4 | call::{Call, GetStorageUsage, Login, Logout, Register, Session}, | 4 | call::{Call, GetStorageUsage, Login, Logout, Register, Session}, |
| 5 | event::Event, | 5 | event::Event, |
| 6 | - model::{Attachment, CommunityUsage, Usage, User}, | 6 | + model::{Attachment, CommunityUsage, Id, Usage, User}, |
| 7 | open::Blob, | 7 | open::Blob, |
| 8 | }; | 8 | }; |
| 9 | use tokio::sync::{mpsc, oneshot}; | 9 | use tokio::sync::{mpsc, oneshot}; |
| @@ -41,8 +41,8 @@ struct Shared { | |||
| 41 | 41 | ||
| 42 | #[derive(Default)] | 42 | #[derive(Default)] |
| 43 | pub struct Levels { | 43 | pub struct Levels { |
| 44 | - pub voice: Vec<(String, Vec<f32>)>, | 44 | + pub voice: Vec<(Id, Vec<f32>)>, |
| 45 | - pub watching: Vec<(String, Vec<f32>)>, | 45 | + pub watching: Vec<(Id, Vec<f32>)>, |
| 46 | pub sharing: Option<Vec<f32>>, | 46 | pub sharing: Option<Vec<f32>>, |
| 47 | } | 47 | } |
| 48 | 48 | ||
| @@ -63,7 +63,7 @@ enum Command { | |||
| 63 | reply: oneshot::Sender<Result<Option<User>, Fail>>, | 63 | reply: oneshot::Sender<Result<Option<User>, Fail>>, |
| 64 | }, | 64 | }, |
| 65 | Upload { | 65 | Upload { |
| 66 | - community_id: String, | 66 | + community_id: Id, |
| 67 | path: PathBuf, | 67 | path: PathBuf, |
| 68 | maximum: Option<u64>, | 68 | maximum: Option<u64>, |
| 69 | reply: oneshot::Sender<Result<Attachment, Fail>>, | 69 | reply: oneshot::Sender<Result<Attachment, Fail>>, |
| @@ -176,12 +176,12 @@ impl NetworkHandle { | |||
| 176 | 176 | ||
| 177 | pub async fn upload_attachment( | 177 | pub async fn upload_attachment( |
| 178 | &self, | 178 | &self, |
| 179 | - community_id: &str, | 179 | + community_id: Id, |
| 180 | path: PathBuf, | 180 | path: PathBuf, |
| 181 | maximum: Option<u64>, | 181 | maximum: Option<u64>, |
| 182 | ) -> Result<Attachment, Fail> { | 182 | ) -> Result<Attachment, Fail> { |
| 183 | self.ask(|reply| Command::Upload { | 183 | self.ask(|reply| Command::Upload { |
| 184 | - community_id: community_id.to_string(), | 184 | + community_id, |
| 185 | path, | 185 | path, |
| 186 | maximum, | 186 | maximum, |
| 187 | reply, | 187 | reply, |
| @@ -191,14 +191,13 @@ impl NetworkHandle { | |||
| 191 | 191 | ||
| 192 | pub async fn download_attachment( | 192 | pub async fn download_attachment( |
| 193 | &self, | 193 | &self, |
| 194 | - attachment_id: &str, | 194 | + attachment_id: Id, |
| 195 | thumbnail: bool, | 195 | thumbnail: bool, |
| 196 | ) -> Result<Vec<u8>, Fail> { | 196 | ) -> Result<Vec<u8>, Fail> { |
| 197 | - let id = attachment_id.to_string(); | ||
| 198 | let blob = if thumbnail { | 197 | let blob = if thumbnail { |
| 199 | - Blob::Thumbnail(id) | 198 | + Blob::Thumbnail(attachment_id) |
| 200 | } else { | 199 | } else { |
| 201 | - Blob::Attachment(id) | 200 | + Blob::Attachment(attachment_id) |
| 202 | }; | 201 | }; |
| 203 | self.ask(|reply| Command::Download { blob, reply }).await | 202 | self.ask(|reply| Command::Download { blob, reply }).await |
| 204 | } | 203 | } |
crates/client/src/settings.rsmodified+3 -2
| @@ -2,6 +2,7 @@ use std::{collections::BTreeMap, fmt::Display, ops::RangeInclusive}; | |||
| 2 | 2 | ||
| 3 | use common::{ | 3 | use common::{ |
| 4 | config::Config, | 4 | config::Config, |
| 5 | + model::Id, | ||
| 5 | share::{Codec, Fps, Quality, Resolution}, | 6 | share::{Codec, Fps, Quality, Resolution}, |
| 6 | string_enum, | 7 | string_enum, |
| 7 | }; | 8 | }; |
| @@ -107,7 +108,7 @@ pub struct VoiceSettings { | |||
| 107 | pub activation: Activation, | 108 | pub activation: Activation, |
| 108 | pub profile: Profile, | 109 | pub profile: Profile, |
| 109 | pub push_to_talk_key: String, | 110 | pub push_to_talk_key: String, |
| 110 | - pub user_volumes: BTreeMap<String, f32>, | 111 | + pub user_volumes: BTreeMap<Id, f32>, |
| 111 | } | 112 | } |
| 112 | 113 | ||
| 113 | impl Default for VoiceSettings { | 114 | impl Default for VoiceSettings { |
| @@ -267,7 +268,7 @@ pub fn load() -> Settings { | |||
| 267 | .split(',') | 268 | .split(',') |
| 268 | .filter_map(|pair| pair.split_once('=')) | 269 | .filter_map(|pair| pair.split_once('=')) |
| 269 | .filter_map(|(user_id, volume)| { | 270 | .filter_map(|(user_id, volume)| { |
| 270 | - Some((user_id.to_string(), volume.parse().ok()?)) | 271 | + Some((user_id.parse().ok()?, volume.parse().ok()?)) |
| 271 | }) | 272 | }) |
| 272 | .filter(|(_, volume)| VOLUME.contains(volume)) | 273 | .filter(|(_, volume)| VOLUME.contains(volume)) |
| 273 | .collect() | 274 | .collect() |
crates/client/src/share/session.rsmodified+2 -1
| @@ -16,6 +16,7 @@ use common::{ | |||
| 16 | VOICE_SAMPLE_RATE, | 16 | VOICE_SAMPLE_RATE, |
| 17 | }, | 17 | }, |
| 18 | datagram::{self, Packet, RELAY_PREFIX, fragments, split, warn_if_small}, | 18 | datagram::{self, Packet, RELAY_PREFIX, fragments, split, warn_if_small}, |
| 19 | + model::Id, | ||
| 19 | share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options}, | 20 | share::{Codec, Fps, Kind, Layer, Quality, Resolution, Source, options}, |
| 20 | }; | 21 | }; |
| 21 | use ec_opus::{Application, Decoder, Encoder}; | 22 | use ec_opus::{Application, Decoder, Encoder}; |
| @@ -91,7 +92,7 @@ pub struct WatchStats { | |||
| 91 | #[derive(Default)] | 92 | #[derive(Default)] |
| 92 | pub struct ShareSample { | 93 | pub struct ShareSample { |
| 93 | pub sending: Vec<LayerStats>, | 94 | pub sending: Vec<LayerStats>, |
| 94 | - pub watching: Vec<(String, WatchStats)>, | 95 | + pub watching: Vec<(Id, WatchStats)>, |
| 95 | } | 96 | } |
| 96 | 97 | ||
| 97 | struct Tally { | 98 | struct Tally { |
crates/client/src/voice/engine.rsmodified+8 -8
| @@ -8,9 +8,9 @@ use common::{ | |||
| 8 | MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, | 8 | MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, |
| 9 | }, | 9 | }, |
| 10 | datagram::{Packet, RELAY_PREFIX, VOICE_HEADER}, | 10 | datagram::{Packet, RELAY_PREFIX, VOICE_HEADER}, |
| 11 | + model::Id, | ||
| 11 | }; | 12 | }; |
| 12 | use ec_opus::{Application, Bandwidth, Decoder, Encoder}; | 13 | use ec_opus::{Application, Bandwidth, Decoder, Encoder}; |
| 13 | -use uuid::Uuid; | ||
| 14 | 14 | ||
| 15 | use crate::{ | 15 | use crate::{ |
| 16 | media::meter::{Spectrum, rms}, | 16 | media::meter::{Spectrum, rms}, |
| @@ -182,8 +182,8 @@ pub struct Engine { | |||
| 182 | sending: bool, | 182 | sending: bool, |
| 183 | level_db: f32, | 183 | level_db: f32, |
| 184 | sent: Spectrum, | 184 | sent: Spectrum, |
| 185 | - volumes: HashMap<String, f32>, | 185 | + volumes: HashMap<Id, f32>, |
| 186 | - speakers: HashMap<String, Speaker>, | 186 | + speakers: HashMap<Id, Speaker>, |
| 187 | sent_bytes: usize, | 187 | sent_bytes: usize, |
| 188 | received_bytes: usize, | 188 | received_bytes: usize, |
| 189 | expected: u32, | 189 | expected: u32, |
| @@ -291,7 +291,7 @@ impl Engine { | |||
| 291 | } | 291 | } |
| 292 | 292 | ||
| 293 | pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) { | 293 | pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) { |
| 294 | - let user_id = Uuid::from_bytes(*from).to_string(); | 294 | + let user_id = Id::from_be_bytes(*from); |
| 295 | let now = Instant::now(); | 295 | let now = Instant::now(); |
| 296 | self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len(); | 296 | self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len(); |
| 297 | 297 | ||
| @@ -349,13 +349,13 @@ impl Engine { | |||
| 349 | } | 349 | } |
| 350 | } | 350 | } |
| 351 | 351 | ||
| 352 | - pub fn levels(&mut self) -> Vec<(String, Vec<f32>)> { | 352 | + pub fn levels(&mut self) -> Vec<(Id, Vec<f32>)> { |
| 353 | let now = Instant::now(); | 353 | let now = Instant::now(); |
| 354 | 354 | ||
| 355 | self.speakers | 355 | self.speakers |
| 356 | .iter_mut() | 356 | .iter_mut() |
| 357 | .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW) | 357 | .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW) |
| 358 | - .map(|(user_id, speaker)| (user_id.clone(), speaker.spectrum.take())) | 358 | + .map(|(user_id, speaker)| (*user_id, speaker.spectrum.take())) |
| 359 | .collect() | 359 | .collect() |
| 360 | } | 360 | } |
| 361 | 361 | ||
| @@ -415,11 +415,11 @@ impl Engine { | |||
| 415 | output_volume: f32, | 415 | output_volume: f32, |
| 416 | activation: Activation, | 416 | activation: Activation, |
| 417 | profile: Profile, | 417 | profile: Profile, |
| 418 | - volumes: &BTreeMap<String, f32>, | 418 | + volumes: &BTreeMap<Id, f32>, |
| 419 | ) { | 419 | ) { |
| 420 | self.volumes = volumes | 420 | self.volumes = volumes |
| 421 | .iter() | 421 | .iter() |
| 422 | - .map(|(user_id, volume)| (user_id.clone(), volume / 100.0)) | 422 | + .map(|(user_id, volume)| (*user_id, volume / 100.0)) |
| 423 | .collect(); | 423 | .collect(); |
| 424 | self.gate = 10f32.powf(sensitivity_db / 20.0); | 424 | self.gate = 10f32.powf(sensitivity_db / 20.0); |
| 425 | self.input_gain = input_volume / 100.0; | 425 | self.input_gain = input_volume / 100.0; |
crates/client/src/voice/mod.rsmodified+2 -1
| @@ -10,6 +10,7 @@ use bytes::Bytes; | |||
| 10 | use common::{ | 10 | use common::{ |
| 11 | constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, | 11 | constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, |
| 12 | datagram::{self, Packet, RELAY_PREFIX}, | 12 | datagram::{self, Packet, RELAY_PREFIX}, |
| 13 | + model::Id, | ||
| 13 | }; | 14 | }; |
| 14 | use quinn::Connection; | 15 | use quinn::Connection; |
| 15 | use rtrb::{Consumer, Producer, RingBuffer}; | 16 | use rtrb::{Consumer, Producer, RingBuffer}; |
| @@ -293,7 +294,7 @@ impl Voice { | |||
| 293 | self.with_engine((), |engine| engine.receive(from, seq, opus)); | 294 | self.with_engine((), |engine| engine.receive(from, seq, opus)); |
| 294 | } | 295 | } |
| 295 | 296 | ||
| 296 | - pub fn levels(&self) -> Vec<(String, Vec<f32>)> { | 297 | + pub fn levels(&self) -> Vec<(Id, Vec<f32>)> { |
| 297 | self.with_engine(Vec::new(), Engine::levels) | 298 | self.with_engine(Vec::new(), Engine::levels) |
| 298 | } | 299 | } |
| 299 | 300 | ||
crates/common/Cargo.tomlmodified+0 -1
| @@ -9,7 +9,6 @@ quinn.workspace = true | |||
| 9 | bytes = "1.12.2" | 9 | bytes = "1.12.2" |
| 10 | tracing = "0.1.44" | 10 | tracing = "0.1.44" |
| 11 | thiserror = "2.0.21" | 11 | thiserror = "2.0.21" |
| 12 | -uuid = { version = "1.29.3", features = ["v7"] } | ||
| 13 | reed-solomon-simd = "3.1.0" | 12 | reed-solomon-simd = "3.1.0" |
| 14 | 13 | ||
| 15 | [lints] | 14 | [lints] |
crates/common/src/call.rsmodified+90 -90
| @@ -4,10 +4,10 @@ use crate::{ | |||
| 4 | constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, | 4 | constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, |
| 5 | error::Error, | 5 | error::Error, |
| 6 | model::{ | 6 | model::{ |
| 7 | - Account, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community, | 7 | + Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, |
| 8 | - CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, | 8 | + Community, CommunitySummary, CommunityUsage, DayStat, Friends, Id, Invitation, InviteCode, |
| 9 | - Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, | 9 | + LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, |
| 10 | - ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, | 10 | + Role, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, |
| 11 | }, | 11 | }, |
| 12 | share::{Codec, Kind, Quality, Share, Source}, | 12 | share::{Codec, Kind, Quality, Share, Source}, |
| 13 | validate::{ | 13 | validate::{ |
| @@ -67,7 +67,7 @@ pub struct GetSettings; | |||
| 67 | 67 | ||
| 68 | #[derive(Debug, Clone, Encode, Decode)] | 68 | #[derive(Debug, Clone, Encode, Decode)] |
| 69 | pub struct GetUser { | 69 | pub struct GetUser { |
| 70 | - pub user_id: String, | 70 | + pub user_id: Id, |
| 71 | } | 71 | } |
| 72 | 72 | ||
| 73 | #[derive(Debug, Clone, Encode, Decode)] | 73 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -98,18 +98,18 @@ pub struct RemoveAvatar; | |||
| 98 | 98 | ||
| 99 | #[derive(Debug, Clone, Encode, Decode)] | 99 | #[derive(Debug, Clone, Encode, Decode)] |
| 100 | pub struct GetAvatar { | 100 | pub struct GetAvatar { |
| 101 | - pub avatar_id: String, | 101 | + pub avatar_id: Id, |
| 102 | } | 102 | } |
| 103 | 103 | ||
| 104 | #[derive(Debug, Clone, Encode, Decode)] | 104 | #[derive(Debug, Clone, Encode, Decode)] |
| 105 | pub struct ListSessions { | 105 | pub struct ListSessions { |
| 106 | - pub user_id: String, | 106 | + pub user_id: Id, |
| 107 | } | 107 | } |
| 108 | 108 | ||
| 109 | #[derive(Debug, Clone, Encode, Decode)] | 109 | #[derive(Debug, Clone, Encode, Decode)] |
| 110 | pub struct RevokeSession { | 110 | pub struct RevokeSession { |
| 111 | - pub user_id: String, | 111 | + pub user_id: Id, |
| 112 | - pub session_id: String, | 112 | + pub session_id: Id, |
| 113 | } | 113 | } |
| 114 | 114 | ||
| 115 | #[derive(Debug, Clone, Encode, Decode)] | 115 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -119,29 +119,29 @@ pub struct CreateCommunity { | |||
| 119 | 119 | ||
| 120 | #[derive(Debug, Clone, Encode, Decode)] | 120 | #[derive(Debug, Clone, Encode, Decode)] |
| 121 | pub struct GetCommunity { | 121 | pub struct GetCommunity { |
| 122 | - pub community_id: String, | 122 | + pub community_id: Id, |
| 123 | } | 123 | } |
| 124 | 124 | ||
| 125 | #[derive(Debug, Clone, Encode, Decode)] | 125 | #[derive(Debug, Clone, Encode, Decode)] |
| 126 | pub struct UpdateCommunity { | 126 | pub struct UpdateCommunity { |
| 127 | - pub community_id: String, | 127 | + pub community_id: Id, |
| 128 | pub name: String, | 128 | pub name: String, |
| 129 | } | 129 | } |
| 130 | 130 | ||
| 131 | #[derive(Debug, Clone, Encode, Decode)] | 131 | #[derive(Debug, Clone, Encode, Decode)] |
| 132 | pub struct UpdateCommunityAvatar { | 132 | pub struct UpdateCommunityAvatar { |
| 133 | - pub community_id: String, | 133 | + pub community_id: Id, |
| 134 | pub image: Option<Vec<u8>>, | 134 | pub image: Option<Vec<u8>>, |
| 135 | } | 135 | } |
| 136 | 136 | ||
| 137 | #[derive(Debug, Clone, Encode, Decode)] | 137 | #[derive(Debug, Clone, Encode, Decode)] |
| 138 | pub struct DeleteCommunity { | 138 | pub struct DeleteCommunity { |
| 139 | - pub community_id: String, | 139 | + pub community_id: Id, |
| 140 | } | 140 | } |
| 141 | 141 | ||
| 142 | #[derive(Debug, Clone, Encode, Decode)] | 142 | #[derive(Debug, Clone, Encode, Decode)] |
| 143 | pub struct LeaveCommunity { | 143 | pub struct LeaveCommunity { |
| 144 | - pub community_id: String, | 144 | + pub community_id: Id, |
| 145 | } | 145 | } |
| 146 | 146 | ||
| 147 | #[derive(Debug, Clone, Encode, Decode)] | 147 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -149,75 +149,75 @@ pub struct ListCommunities; | |||
| 149 | 149 | ||
| 150 | #[derive(Debug, Clone, Encode, Decode)] | 150 | #[derive(Debug, Clone, Encode, Decode)] |
| 151 | pub struct ListMembers { | 151 | pub struct ListMembers { |
| 152 | - pub community_id: String, | 152 | + pub community_id: Id, |
| 153 | } | 153 | } |
| 154 | 154 | ||
| 155 | #[derive(Debug, Clone, Encode, Decode)] | 155 | #[derive(Debug, Clone, Encode, Decode)] |
| 156 | pub struct Kick { | 156 | pub struct Kick { |
| 157 | - pub community_id: String, | 157 | + pub community_id: Id, |
| 158 | - pub user_id: String, | 158 | + pub user_id: Id, |
| 159 | pub reason: Option<String>, | 159 | pub reason: Option<String>, |
| 160 | } | 160 | } |
| 161 | 161 | ||
| 162 | #[derive(Debug, Clone, Encode, Decode)] | 162 | #[derive(Debug, Clone, Encode, Decode)] |
| 163 | pub struct BanMember { | 163 | pub struct BanMember { |
| 164 | - pub community_id: String, | 164 | + pub community_id: Id, |
| 165 | - pub user_id: String, | 165 | + pub user_id: Id, |
| 166 | pub reason: Option<String>, | 166 | pub reason: Option<String>, |
| 167 | } | 167 | } |
| 168 | 168 | ||
| 169 | #[derive(Debug, Clone, Encode, Decode)] | 169 | #[derive(Debug, Clone, Encode, Decode)] |
| 170 | pub struct Unban { | 170 | pub struct Unban { |
| 171 | - pub community_id: String, | 171 | + pub community_id: Id, |
| 172 | - pub user_id: String, | 172 | + pub user_id: Id, |
| 173 | } | 173 | } |
| 174 | 174 | ||
| 175 | #[derive(Debug, Clone, Encode, Decode)] | 175 | #[derive(Debug, Clone, Encode, Decode)] |
| 176 | pub struct ListBans { | 176 | pub struct ListBans { |
| 177 | - pub community_id: String, | 177 | + pub community_id: Id, |
| 178 | } | 178 | } |
| 179 | 179 | ||
| 180 | #[derive(Debug, Clone, Encode, Decode)] | 180 | #[derive(Debug, Clone, Encode, Decode)] |
| 181 | pub struct SetRank { | 181 | pub struct SetRank { |
| 182 | - pub community_id: String, | 182 | + pub community_id: Id, |
| 183 | - pub user_id: String, | 183 | + pub user_id: Id, |
| 184 | pub rank: Rank, | 184 | pub rank: Rank, |
| 185 | } | 185 | } |
| 186 | 186 | ||
| 187 | #[derive(Debug, Clone, Encode, Decode)] | 187 | #[derive(Debug, Clone, Encode, Decode)] |
| 188 | pub struct ListLogs { | 188 | pub struct ListLogs { |
| 189 | - pub community_id: String, | 189 | + pub community_id: Id, |
| 190 | } | 190 | } |
| 191 | 191 | ||
| 192 | #[derive(Debug, Clone, Encode, Decode)] | 192 | #[derive(Debug, Clone, Encode, Decode)] |
| 193 | pub struct CreateMessage { | 193 | pub struct CreateMessage { |
| 194 | - pub community_id: String, | 194 | + pub community_id: Id, |
| 195 | pub body: String, | 195 | pub body: String, |
| 196 | - pub attachments: Vec<String>, | 196 | + pub attachments: Vec<Id>, |
| 197 | - pub reply_to: Option<String>, | 197 | + pub reply_to: Option<Id>, |
| 198 | } | 198 | } |
| 199 | 199 | ||
| 200 | #[derive(Debug, Clone, Encode, Decode)] | 200 | #[derive(Debug, Clone, Encode, Decode)] |
| 201 | pub struct ForwardMessages { | 201 | pub struct ForwardMessages { |
| 202 | - pub message_ids: Vec<String>, | 202 | + pub message_ids: Vec<Id>, |
| 203 | - pub community_id: String, | 203 | + pub community_id: Id, |
| 204 | pub snippet: bool, | 204 | pub snippet: bool, |
| 205 | } | 205 | } |
| 206 | 206 | ||
| 207 | #[derive(Debug, Clone, Encode, Decode)] | 207 | #[derive(Debug, Clone, Encode, Decode)] |
| 208 | pub struct UpdateMessage { | 208 | pub struct UpdateMessage { |
| 209 | - pub message_id: String, | 209 | + pub message_id: Id, |
| 210 | pub body: String, | 210 | pub body: String, |
| 211 | } | 211 | } |
| 212 | 212 | ||
| 213 | #[derive(Debug, Clone, Encode, Decode)] | 213 | #[derive(Debug, Clone, Encode, Decode)] |
| 214 | pub struct DeleteMessage { | 214 | pub struct DeleteMessage { |
| 215 | - pub message_id: String, | 215 | + pub message_id: Id, |
| 216 | } | 216 | } |
| 217 | 217 | ||
| 218 | #[derive(Debug, Clone, Encode, Decode)] | 218 | #[derive(Debug, Clone, Encode, Decode)] |
| 219 | pub struct CreatePoll { | 219 | pub struct CreatePoll { |
| 220 | - pub community_id: String, | 220 | + pub community_id: Id, |
| 221 | pub question: String, | 221 | pub question: String, |
| 222 | pub options: Vec<String>, | 222 | pub options: Vec<String>, |
| 223 | pub multiple: bool, | 223 | pub multiple: bool, |
| @@ -225,36 +225,36 @@ pub struct CreatePoll { | |||
| 225 | 225 | ||
| 226 | #[derive(Debug, Clone, Encode, Decode)] | 226 | #[derive(Debug, Clone, Encode, Decode)] |
| 227 | pub struct Vote { | 227 | pub struct Vote { |
| 228 | - pub message_id: String, | 228 | + pub message_id: Id, |
| 229 | pub positions: Vec<u32>, | 229 | pub positions: Vec<u32>, |
| 230 | } | 230 | } |
| 231 | 231 | ||
| 232 | #[derive(Debug, Clone, Encode, Decode)] | 232 | #[derive(Debug, Clone, Encode, Decode)] |
| 233 | pub struct ClosePoll { | 233 | pub struct ClosePoll { |
| 234 | - pub message_id: String, | 234 | + pub message_id: Id, |
| 235 | } | 235 | } |
| 236 | 236 | ||
| 237 | #[derive(Debug, Clone, Encode, Decode)] | 237 | #[derive(Debug, Clone, Encode, Decode)] |
| 238 | pub struct React { | 238 | pub struct React { |
| 239 | - pub message_id: String, | 239 | + pub message_id: Id, |
| 240 | pub emoji: String, | 240 | pub emoji: String, |
| 241 | } | 241 | } |
| 242 | 242 | ||
| 243 | #[derive(Debug, Clone, Encode, Decode)] | 243 | #[derive(Debug, Clone, Encode, Decode)] |
| 244 | pub struct Pin { | 244 | pub struct Pin { |
| 245 | - pub message_id: String, | 245 | + pub message_id: Id, |
| 246 | pub pinned: bool, | 246 | pub pinned: bool, |
| 247 | } | 247 | } |
| 248 | 248 | ||
| 249 | #[derive(Debug, Clone, Encode, Decode)] | 249 | #[derive(Debug, Clone, Encode, Decode)] |
| 250 | pub struct ListPins { | 250 | pub struct ListPins { |
| 251 | - pub community_id: String, | 251 | + pub community_id: Id, |
| 252 | } | 252 | } |
| 253 | 253 | ||
| 254 | #[derive(Debug, Clone, Encode, Decode)] | 254 | #[derive(Debug, Clone, Encode, Decode)] |
| 255 | pub struct ListMessages { | 255 | pub struct ListMessages { |
| 256 | - pub community_id: String, | 256 | + pub community_id: Id, |
| 257 | - pub before: Option<String>, | 257 | + pub before: Option<Id>, |
| 258 | } | 258 | } |
| 259 | 259 | ||
| 260 | #[derive(Debug, Clone, Encode, Decode)] | 260 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -262,13 +262,13 @@ pub struct ListUnreads; | |||
| 262 | 262 | ||
| 263 | #[derive(Debug, Clone, Encode, Decode)] | 263 | #[derive(Debug, Clone, Encode, Decode)] |
| 264 | pub struct MarkRead { | 264 | pub struct MarkRead { |
| 265 | - pub community_id: String, | 265 | + pub community_id: Id, |
| 266 | - pub message_id: String, | 266 | + pub message_id: Id, |
| 267 | } | 267 | } |
| 268 | 268 | ||
| 269 | #[derive(Debug, Clone, Encode, Decode)] | 269 | #[derive(Debug, Clone, Encode, Decode)] |
| 270 | pub struct Typing { | 270 | pub struct Typing { |
| 271 | - pub community_id: String, | 271 | + pub community_id: Id, |
| 272 | } | 272 | } |
| 273 | 273 | ||
| 274 | #[derive(Debug, Clone, Encode, Decode)] | 274 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -278,7 +278,7 @@ pub struct FindUser { | |||
| 278 | 278 | ||
| 279 | #[derive(Debug, Clone, Encode, Decode)] | 279 | #[derive(Debug, Clone, Encode, Decode)] |
| 280 | pub struct OpenDirect { | 280 | pub struct OpenDirect { |
| 281 | - pub user_id: String, | 281 | + pub user_id: Id, |
| 282 | } | 282 | } |
| 283 | 283 | ||
| 284 | #[derive(Debug, Clone, Encode, Decode)] | 284 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -289,23 +289,23 @@ pub struct ListFriends; | |||
| 289 | 289 | ||
| 290 | #[derive(Debug, Clone, Encode, Decode)] | 290 | #[derive(Debug, Clone, Encode, Decode)] |
| 291 | pub struct AddFriend { | 291 | pub struct AddFriend { |
| 292 | - pub user_id: String, | 292 | + pub user_id: Id, |
| 293 | } | 293 | } |
| 294 | 294 | ||
| 295 | #[derive(Debug, Clone, Encode, Decode)] | 295 | #[derive(Debug, Clone, Encode, Decode)] |
| 296 | pub struct AcceptFriend { | 296 | pub struct AcceptFriend { |
| 297 | - pub user_id: String, | 297 | + pub user_id: Id, |
| 298 | } | 298 | } |
| 299 | 299 | ||
| 300 | #[derive(Debug, Clone, Encode, Decode)] | 300 | #[derive(Debug, Clone, Encode, Decode)] |
| 301 | pub struct RemoveFriend { | 301 | pub struct RemoveFriend { |
| 302 | - pub user_id: String, | 302 | + pub user_id: Id, |
| 303 | } | 303 | } |
| 304 | 304 | ||
| 305 | #[derive(Debug, Clone, Encode, Decode)] | 305 | #[derive(Debug, Clone, Encode, Decode)] |
| 306 | pub struct Invite { | 306 | pub struct Invite { |
| 307 | - pub community_id: String, | 307 | + pub community_id: Id, |
| 308 | - pub user_id: String, | 308 | + pub user_id: Id, |
| 309 | } | 309 | } |
| 310 | 310 | ||
| 311 | #[derive(Debug, Clone, Encode, Decode)] | 311 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -313,23 +313,23 @@ pub struct ListInvitations; | |||
| 313 | 313 | ||
| 314 | #[derive(Debug, Clone, Encode, Decode)] | 314 | #[derive(Debug, Clone, Encode, Decode)] |
| 315 | pub struct AcceptInvitation { | 315 | pub struct AcceptInvitation { |
| 316 | - pub community_id: String, | 316 | + pub community_id: Id, |
| 317 | } | 317 | } |
| 318 | 318 | ||
| 319 | #[derive(Debug, Clone, Encode, Decode)] | 319 | #[derive(Debug, Clone, Encode, Decode)] |
| 320 | pub struct DeclineInvitation { | 320 | pub struct DeclineInvitation { |
| 321 | - pub community_id: String, | 321 | + pub community_id: Id, |
| 322 | } | 322 | } |
| 323 | 323 | ||
| 324 | #[derive(Debug, Clone, Encode, Decode)] | 324 | #[derive(Debug, Clone, Encode, Decode)] |
| 325 | pub struct ReportMessage { | 325 | pub struct ReportMessage { |
| 326 | - pub message_id: String, | 326 | + pub message_id: Id, |
| 327 | pub reason: String, | 327 | pub reason: String, |
| 328 | } | 328 | } |
| 329 | 329 | ||
| 330 | #[derive(Debug, Clone, Encode, Decode)] | 330 | #[derive(Debug, Clone, Encode, Decode)] |
| 331 | pub struct ReportUser { | 331 | pub struct ReportUser { |
| 332 | - pub user_id: String, | 332 | + pub user_id: Id, |
| 333 | pub reason: String, | 333 | pub reason: String, |
| 334 | } | 334 | } |
| 335 | 335 | ||
| @@ -340,13 +340,13 @@ pub struct ListReports { | |||
| 340 | 340 | ||
| 341 | #[derive(Debug, Clone, Encode, Decode)] | 341 | #[derive(Debug, Clone, Encode, Decode)] |
| 342 | pub struct HandleReport { | 342 | pub struct HandleReport { |
| 343 | - pub report_id: String, | 343 | + pub report_id: Id, |
| 344 | pub status: ReportStatus, | 344 | pub status: ReportStatus, |
| 345 | } | 345 | } |
| 346 | 346 | ||
| 347 | #[derive(Debug, Clone, Encode, Decode)] | 347 | #[derive(Debug, Clone, Encode, Decode)] |
| 348 | pub struct JoinVoice { | 348 | pub struct JoinVoice { |
| 349 | - pub community_id: String, | 349 | + pub community_id: Id, |
| 350 | } | 350 | } |
| 351 | 351 | ||
| 352 | #[derive(Debug, Clone, Encode, Decode)] | 352 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -365,12 +365,12 @@ pub struct StopShare { | |||
| 365 | 365 | ||
| 366 | #[derive(Debug, Clone, Encode, Decode)] | 366 | #[derive(Debug, Clone, Encode, Decode)] |
| 367 | pub struct ListShares { | 367 | pub struct ListShares { |
| 368 | - pub community_id: String, | 368 | + pub community_id: Id, |
| 369 | } | 369 | } |
| 370 | 370 | ||
| 371 | #[derive(Debug, Clone, Encode, Decode)] | 371 | #[derive(Debug, Clone, Encode, Decode)] |
| 372 | pub struct WatchShare { | 372 | pub struct WatchShare { |
| 373 | - pub user_id: String, | 373 | + pub user_id: Id, |
| 374 | pub kind: Kind, | 374 | pub kind: Kind, |
| 375 | pub quality: Quality, | 375 | pub quality: Quality, |
| 376 | pub decode: Vec<Codec>, | 376 | pub decode: Vec<Codec>, |
| @@ -378,24 +378,24 @@ pub struct WatchShare { | |||
| 378 | 378 | ||
| 379 | #[derive(Debug, Clone, Encode, Decode)] | 379 | #[derive(Debug, Clone, Encode, Decode)] |
| 380 | pub struct UnwatchShare { | 380 | pub struct UnwatchShare { |
| 381 | - pub user_id: String, | 381 | + pub user_id: Id, |
| 382 | pub kind: Kind, | 382 | pub kind: Kind, |
| 383 | } | 383 | } |
| 384 | 384 | ||
| 385 | #[derive(Debug, Clone, Encode, Decode)] | 385 | #[derive(Debug, Clone, Encode, Decode)] |
| 386 | pub struct RequestKeyframe { | 386 | pub struct RequestKeyframe { |
| 387 | - pub user_id: String, | 387 | + pub user_id: Id, |
| 388 | pub kind: Kind, | 388 | pub kind: Kind, |
| 389 | } | 389 | } |
| 390 | 390 | ||
| 391 | #[derive(Debug, Clone, Encode, Decode)] | 391 | #[derive(Debug, Clone, Encode, Decode)] |
| 392 | pub struct DeclineCall { | 392 | pub struct DeclineCall { |
| 393 | - pub community_id: String, | 393 | + pub community_id: Id, |
| 394 | } | 394 | } |
| 395 | 395 | ||
| 396 | #[derive(Debug, Clone, Encode, Decode)] | 396 | #[derive(Debug, Clone, Encode, Decode)] |
| 397 | pub struct ListVoiceParticipants { | 397 | pub struct ListVoiceParticipants { |
| 398 | - pub community_id: String, | 398 | + pub community_id: Id, |
| 399 | } | 399 | } |
| 400 | 400 | ||
| 401 | #[derive(Debug, Clone, Encode, Decode)] | 401 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -403,12 +403,12 @@ pub struct ListVoiceRooms; | |||
| 403 | 403 | ||
| 404 | #[derive(Debug, Clone, Encode, Decode)] | 404 | #[derive(Debug, Clone, Encode, Decode)] |
| 405 | pub struct KickFromVoice { | 405 | pub struct KickFromVoice { |
| 406 | - pub user_id: String, | 406 | + pub user_id: Id, |
| 407 | } | 407 | } |
| 408 | 408 | ||
| 409 | #[derive(Debug, Clone, Encode, Decode)] | 409 | #[derive(Debug, Clone, Encode, Decode)] |
| 410 | pub struct ServerMute { | 410 | pub struct ServerMute { |
| 411 | - pub user_id: String, | 411 | + pub user_id: Id, |
| 412 | pub muted: bool, | 412 | pub muted: bool, |
| 413 | } | 413 | } |
| 414 | 414 | ||
| @@ -430,12 +430,12 @@ pub struct Logout; | |||
| 430 | 430 | ||
| 431 | #[derive(Debug, Clone, Encode, Decode)] | 431 | #[derive(Debug, Clone, Encode, Decode)] |
| 432 | pub struct DeleteUser { | 432 | pub struct DeleteUser { |
| 433 | - pub user_id: String, | 433 | + pub user_id: Id, |
| 434 | } | 434 | } |
| 435 | 435 | ||
| 436 | #[derive(Debug, Clone, Encode, Decode)] | 436 | #[derive(Debug, Clone, Encode, Decode)] |
| 437 | pub struct WatchCommunity { | 437 | pub struct WatchCommunity { |
| 438 | - pub community_id: Option<String>, | 438 | + pub community_id: Option<Id>, |
| 439 | } | 439 | } |
| 440 | 440 | ||
| 441 | #[derive(Debug, Clone, Encode, Decode)] | 441 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -443,15 +443,15 @@ pub struct ListUsers; | |||
| 443 | 443 | ||
| 444 | #[derive(Debug, Clone, Encode, Decode)] | 444 | #[derive(Debug, Clone, Encode, Decode)] |
| 445 | pub struct SetRole { | 445 | pub struct SetRole { |
| 446 | - pub user_id: String, | 446 | + pub user_id: Id, |
| 447 | pub role: Role, | 447 | pub role: Role, |
| 448 | } | 448 | } |
| 449 | 449 | ||
| 450 | #[derive(Debug, Clone, Encode, Decode)] | 450 | #[derive(Debug, Clone, Encode, Decode)] |
| 451 | pub struct ListAdminLogs { | 451 | pub struct ListAdminLogs { |
| 452 | - pub actor_id: Option<String>, | 452 | + pub actor_id: Option<Id>, |
| 453 | - pub target_id: Option<String>, | 453 | + pub target_id: Option<Id>, |
| 454 | - pub action: Option<String>, | 454 | + pub action: Option<AdminActionKind>, |
| 455 | pub after_ms: Option<u64>, | 455 | pub after_ms: Option<u64>, |
| 456 | pub before_ms: Option<u64>, | 456 | pub before_ms: Option<u64>, |
| 457 | } | 457 | } |
| @@ -461,24 +461,24 @@ pub struct GetOverview; | |||
| 461 | 461 | ||
| 462 | #[derive(Debug, Clone, Encode, Decode)] | 462 | #[derive(Debug, Clone, Encode, Decode)] |
| 463 | pub struct SuspendUser { | 463 | pub struct SuspendUser { |
| 464 | - pub user_id: String, | 464 | + pub user_id: Id, |
| 465 | pub suspended: bool, | 465 | pub suspended: bool, |
| 466 | } | 466 | } |
| 467 | 467 | ||
| 468 | #[derive(Debug, Clone, Encode, Decode)] | 468 | #[derive(Debug, Clone, Encode, Decode)] |
| 469 | pub struct RevokeSessions { | 469 | pub struct RevokeSessions { |
| 470 | - pub user_id: String, | 470 | + pub user_id: Id, |
| 471 | } | 471 | } |
| 472 | 472 | ||
| 473 | #[derive(Debug, Clone, Encode, Decode)] | 473 | #[derive(Debug, Clone, Encode, Decode)] |
| 474 | pub struct ResetPassword { | 474 | pub struct ResetPassword { |
| 475 | - pub user_id: String, | 475 | + pub user_id: Id, |
| 476 | pub password: String, | 476 | pub password: String, |
| 477 | } | 477 | } |
| 478 | 478 | ||
| 479 | #[derive(Debug, Clone, Encode, Decode)] | 479 | #[derive(Debug, Clone, Encode, Decode)] |
| 480 | pub struct ClearProfile { | 480 | pub struct ClearProfile { |
| 481 | - pub user_id: String, | 481 | + pub user_id: Id, |
| 482 | } | 482 | } |
| 483 | 483 | ||
| 484 | #[derive(Debug, Clone, Encode, Decode)] | 484 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -486,8 +486,8 @@ pub struct ListAllCommunities; | |||
| 486 | 486 | ||
| 487 | #[derive(Debug, Clone, Encode, Decode)] | 487 | #[derive(Debug, Clone, Encode, Decode)] |
| 488 | pub struct TransferOwnership { | 488 | pub struct TransferOwnership { |
| 489 | - pub community_id: String, | 489 | + pub community_id: Id, |
| 490 | - pub user_id: String, | 490 | + pub user_id: Id, |
| 491 | } | 491 | } |
| 492 | 492 | ||
| 493 | #[derive(Debug, Clone, Encode, Decode)] | 493 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -503,19 +503,19 @@ pub struct CreateUser { | |||
| 503 | 503 | ||
| 504 | #[derive(Debug, Clone, Encode, Decode)] | 504 | #[derive(Debug, Clone, Encode, Decode)] |
| 505 | pub struct RenameUser { | 505 | pub struct RenameUser { |
| 506 | - pub user_id: String, | 506 | + pub user_id: Id, |
| 507 | pub username: String, | 507 | pub username: String, |
| 508 | } | 508 | } |
| 509 | 509 | ||
| 510 | #[derive(Debug, Clone, Encode, Decode)] | 510 | #[derive(Debug, Clone, Encode, Decode)] |
| 511 | pub struct TimeoutUser { | 511 | pub struct TimeoutUser { |
| 512 | - pub user_id: String, | 512 | + pub user_id: Id, |
| 513 | pub minutes: u32, | 513 | pub minutes: u32, |
| 514 | } | 514 | } |
| 515 | 515 | ||
| 516 | #[derive(Debug, Clone, Encode, Decode)] | 516 | #[derive(Debug, Clone, Encode, Decode)] |
| 517 | pub struct BanUser { | 517 | pub struct BanUser { |
| 518 | - pub user_id: String, | 518 | + pub user_id: Id, |
| 519 | pub reason: Option<String>, | 519 | pub reason: Option<String>, |
| 520 | pub scope: BanScope, | 520 | pub scope: BanScope, |
| 521 | } | 521 | } |
| @@ -525,7 +525,7 @@ pub struct ListServerBans; | |||
| 525 | 525 | ||
| 526 | #[derive(Debug, Clone, Encode, Decode)] | 526 | #[derive(Debug, Clone, Encode, Decode)] |
| 527 | pub struct RemoveServerBan { | 527 | pub struct RemoveServerBan { |
| 528 | - pub id: String, | 528 | + pub id: Id, |
| 529 | } | 529 | } |
| 530 | 530 | ||
| 531 | #[derive(Debug, Clone, Encode, Decode)] | 531 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -545,38 +545,38 @@ pub struct DeleteInviteCode { | |||
| 545 | #[derive(Debug, Clone, Encode, Decode)] | 545 | #[derive(Debug, Clone, Encode, Decode)] |
| 546 | pub struct SearchMessages { | 546 | pub struct SearchMessages { |
| 547 | pub text: Option<String>, | 547 | pub text: Option<String>, |
| 548 | - pub user_id: Option<String>, | 548 | + pub user_id: Option<Id>, |
| 549 | - pub community_id: Option<String>, | 549 | + pub community_id: Option<Id>, |
| 550 | pub after_ms: Option<u64>, | 550 | pub after_ms: Option<u64>, |
| 551 | pub before_ms: Option<u64>, | 551 | pub before_ms: Option<u64>, |
| 552 | } | 552 | } |
| 553 | 553 | ||
| 554 | #[derive(Debug, Clone, Encode, Decode)] | 554 | #[derive(Debug, Clone, Encode, Decode)] |
| 555 | pub struct SearchCommunity { | 555 | pub struct SearchCommunity { |
| 556 | - pub community_id: String, | 556 | + pub community_id: Id, |
| 557 | pub text: String, | 557 | pub text: String, |
| 558 | } | 558 | } |
| 559 | 559 | ||
| 560 | #[derive(Debug, Clone, Encode, Decode)] | 560 | #[derive(Debug, Clone, Encode, Decode)] |
| 561 | pub struct PurgeUser { | 561 | pub struct PurgeUser { |
| 562 | - pub user_id: String, | 562 | + pub user_id: Id, |
| 563 | } | 563 | } |
| 564 | 564 | ||
| 565 | #[derive(Debug, Clone, Encode, Decode)] | 565 | #[derive(Debug, Clone, Encode, Decode)] |
| 566 | pub struct SetCommunityVoice { | 566 | pub struct SetCommunityVoice { |
| 567 | - pub community_id: String, | 567 | + pub community_id: Id, |
| 568 | pub enabled: bool, | 568 | pub enabled: bool, |
| 569 | } | 569 | } |
| 570 | 570 | ||
| 571 | #[derive(Debug, Clone, Encode, Decode)] | 571 | #[derive(Debug, Clone, Encode, Decode)] |
| 572 | pub struct ListAttachments { | 572 | pub struct ListAttachments { |
| 573 | - pub user_id: Option<String>, | 573 | + pub user_id: Option<Id>, |
| 574 | - pub community_id: Option<String>, | 574 | + pub community_id: Option<Id>, |
| 575 | } | 575 | } |
| 576 | 576 | ||
| 577 | #[derive(Debug, Clone, Encode, Decode)] | 577 | #[derive(Debug, Clone, Encode, Decode)] |
| 578 | pub struct DeleteAttachment { | 578 | pub struct DeleteAttachment { |
| 579 | - pub attachment_id: String, | 579 | + pub attachment_id: Id, |
| 580 | } | 580 | } |
| 581 | 581 | ||
| 582 | #[derive(Debug, Clone, Encode, Decode)] | 582 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -621,7 +621,7 @@ calls! { | |||
| 621 | UpdateUser: User -> User, |c| validate_username(&c.username); | 621 | UpdateUser: User -> User, |c| validate_username(&c.username); |
| 622 | UpdateStatus: User -> User, |c| validate_status(&c.status); | 622 | UpdateStatus: User -> User, |c| validate_status(&c.status); |
| 623 | UpdatePresence: User -> (); | 623 | UpdatePresence: User -> (); |
| 624 | - ListPresences: User -> Vec<(String, Presence)>; | 624 | + ListPresences: User -> Vec<(Id, Presence)>; |
| 625 | UpdateAvatar: User -> User, |c| validate_avatar_size(&c.image, MAXIMUM_AVATAR_BYTES as u64); | 625 | UpdateAvatar: User -> User, |c| validate_avatar_size(&c.image, MAXIMUM_AVATAR_BYTES as u64); |
| 626 | RemoveAvatar: User -> User; | 626 | RemoveAvatar: User -> User; |
| 627 | GetAvatar: User -> Vec<u8>; | 627 | GetAvatar: User -> Vec<u8>; |
| @@ -670,7 +670,7 @@ calls! { | |||
| 670 | ReportUser: User -> (), |c| validate_reason(Some(&c.reason)); | 670 | ReportUser: User -> (), |c| validate_reason(Some(&c.reason)); |
| 671 | ListReports: Builder -> Vec<Report>; | 671 | ListReports: Builder -> Vec<Report>; |
| 672 | HandleReport: User -> (); | 672 | HandleReport: User -> (); |
| 673 | - JoinVoice: User -> Vec<String>; | 673 | + JoinVoice: User -> Vec<Id>; |
| 674 | LeaveVoice: User -> (); | 674 | LeaveVoice: User -> (); |
| 675 | StartShare: User -> (); | 675 | StartShare: User -> (); |
| 676 | StopShare: User -> (); | 676 | StopShare: User -> (); |
| @@ -679,7 +679,7 @@ calls! { | |||
| 679 | UnwatchShare: User -> (); | 679 | UnwatchShare: User -> (); |
| 680 | RequestKeyframe: User -> (); | 680 | RequestKeyframe: User -> (); |
| 681 | DeclineCall: User -> (); | 681 | DeclineCall: User -> (); |
| 682 | - ListVoiceParticipants: User -> Vec<String>; | 682 | + ListVoiceParticipants: User -> Vec<Id>; |
| 683 | ListVoiceRooms: Builder -> Vec<VoiceRoom>; | 683 | ListVoiceRooms: Builder -> Vec<VoiceRoom>; |
| 684 | KickFromVoice: User -> (); | 684 | KickFromVoice: User -> (); |
| 685 | ServerMute: User -> (); | 685 | ServerMute: User -> (); |
crates/common/src/datagram.rsmodified+6 -2
| @@ -11,7 +11,7 @@ use crate::{ | |||
| 11 | share::{Kind, Layer}, | 11 | share::{Kind, Layer}, |
| 12 | }; | 12 | }; |
| 13 | 13 | ||
| 14 | -pub const RELAY_PREFIX: usize = 16; | 14 | +pub const RELAY_PREFIX: usize = 8; |
| 15 | const MAX_DATAGRAM: usize = 1200 - 48; | 15 | const MAX_DATAGRAM: usize = 1200 - 48; |
| 16 | 16 | ||
| 17 | pub const VOICE_HEADER: usize = 5; | 17 | pub const VOICE_HEADER: usize = 5; |
| @@ -257,7 +257,11 @@ pub fn send(connection: &Connection, bytes: Bytes) { | |||
| 257 | pub fn warn_if_small(connection: &Connection) { | 257 | pub fn warn_if_small(connection: &Connection) { |
| 258 | let max = connection.max_datagram_size(); | 258 | let max = connection.max_datagram_size(); |
| 259 | if max.is_none_or(|size| size < MAX_DATAGRAM) { | 259 | if max.is_none_or(|size| size < MAX_DATAGRAM) { |
| 260 | - warn!(?max, needed = MAX_DATAGRAM, "datagram size limit below media packets"); | 260 | + warn!( |
| 261 | + ?max, | ||
| 262 | + needed = MAX_DATAGRAM, | ||
| 263 | + "datagram size limit below media packets" | ||
| 264 | + ); | ||
| 261 | } | 265 | } |
| 262 | } | 266 | } |
| 263 | 267 | ||
crates/common/src/event.rsmodified+24 -23
| @@ -1,7 +1,8 @@ | |||
| 1 | use bitcode::{Decode, Encode}; | 1 | use bitcode::{Decode, Encode}; |
| 2 | 2 | ||
| 3 | use crate::model::{ | 3 | use crate::model::{ |
| 4 | - Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, ServerSettings, User, | 4 | + Community, Friends, Id, Invitation, Member, Message, Presence, Rank, Sanction, ServerSettings, |
| 5 | + User, | ||
| 5 | }; | 6 | }; |
| 6 | use crate::share::{Kind, Layer, Share}; | 7 | use crate::share::{Kind, Layer, Share}; |
| 7 | 8 | ||
| @@ -10,26 +11,26 @@ pub enum Event { | |||
| 10 | MessageCreated(Message), | 11 | MessageCreated(Message), |
| 11 | MessageUpdated(Message), | 12 | MessageUpdated(Message), |
| 12 | MessagesDeleted { | 13 | MessagesDeleted { |
| 13 | - community_id: String, | 14 | + community_id: Id, |
| 14 | - ids: Vec<String>, | 15 | + ids: Vec<Id>, |
| 15 | }, | 16 | }, |
| 16 | MemberJoined { | 17 | MemberJoined { |
| 17 | - community_id: String, | 18 | + community_id: Id, |
| 18 | member: Member, | 19 | member: Member, |
| 19 | }, | 20 | }, |
| 20 | MemberLeft { | 21 | MemberLeft { |
| 21 | - community_id: String, | 22 | + community_id: Id, |
| 22 | - user_id: String, | 23 | + user_id: Id, |
| 23 | }, | 24 | }, |
| 24 | RankChanged { | 25 | RankChanged { |
| 25 | - community_id: String, | 26 | + community_id: Id, |
| 26 | - user_id: String, | 27 | + user_id: Id, |
| 27 | rank: Rank, | 28 | rank: Rank, |
| 28 | }, | 29 | }, |
| 29 | CommunityUpdated(Community), | 30 | CommunityUpdated(Community), |
| 30 | CommunityAdded(Community), | 31 | CommunityAdded(Community), |
| 31 | Removed { | 32 | Removed { |
| 32 | - community_id: String, | 33 | + community_id: Id, |
| 33 | community_name: String, | 34 | community_name: String, |
| 34 | sanction: Sanction, | 35 | sanction: Sanction, |
| 35 | reason: Option<String>, | 36 | reason: Option<String>, |
| @@ -37,42 +38,42 @@ pub enum Event { | |||
| 37 | FriendsUpdated(Friends), | 38 | FriendsUpdated(Friends), |
| 38 | InvitationsUpdated(Vec<Invitation>), | 39 | InvitationsUpdated(Vec<Invitation>), |
| 39 | CommunityDeleted { | 40 | CommunityDeleted { |
| 40 | - community_id: String, | 41 | + community_id: Id, |
| 41 | }, | 42 | }, |
| 42 | UserDeleted { | 43 | UserDeleted { |
| 43 | - user_id: String, | 44 | + user_id: Id, |
| 44 | }, | 45 | }, |
| 45 | UserUpdated(User), | 46 | UserUpdated(User), |
| 46 | PresenceChanged { | 47 | PresenceChanged { |
| 47 | - user_id: String, | 48 | + user_id: Id, |
| 48 | presence: Presence, | 49 | presence: Presence, |
| 49 | }, | 50 | }, |
| 50 | VoiceJoined { | 51 | VoiceJoined { |
| 51 | - community_id: String, | 52 | + community_id: Id, |
| 52 | - user_id: String, | 53 | + user_id: Id, |
| 53 | }, | 54 | }, |
| 54 | VoiceLeft { | 55 | VoiceLeft { |
| 55 | - community_id: String, | 56 | + community_id: Id, |
| 56 | - user_id: String, | 57 | + user_id: Id, |
| 57 | }, | 58 | }, |
| 58 | ReportCreated, | 59 | ReportCreated, |
| 59 | VoiceMuted { | 60 | VoiceMuted { |
| 60 | - community_id: Option<String>, | 61 | + community_id: Option<Id>, |
| 61 | - user_id: String, | 62 | + user_id: Id, |
| 62 | muted: bool, | 63 | muted: bool, |
| 63 | }, | 64 | }, |
| 64 | SettingsUpdated(ServerSettings), | 65 | SettingsUpdated(ServerSettings), |
| 65 | Typing { | 66 | Typing { |
| 66 | - community_id: String, | 67 | + community_id: Id, |
| 67 | - user_id: String, | 68 | + user_id: Id, |
| 68 | }, | 69 | }, |
| 69 | ShareStarted { | 70 | ShareStarted { |
| 70 | - community_id: String, | 71 | + community_id: Id, |
| 71 | share: Share, | 72 | share: Share, |
| 72 | }, | 73 | }, |
| 73 | ShareStopped { | 74 | ShareStopped { |
| 74 | - community_id: String, | 75 | + community_id: Id, |
| 75 | - user_id: String, | 76 | + user_id: Id, |
| 76 | kind: Kind, | 77 | kind: Kind, |
| 77 | }, | 78 | }, |
| 78 | } | 79 | } |
crates/common/src/model.rsmodified+54 -52
| @@ -5,6 +5,13 @@ use crate::constant::{ | |||
| 5 | MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH, | 5 | MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH, |
| 6 | }; | 6 | }; |
| 7 | 7 | ||
| 8 | +pub type Id = i64; | ||
| 9 | + | ||
| 10 | +pub trait Named: Sized + Copy { | ||
| 11 | + fn as_str(self) -> &'static str; | ||
| 12 | + fn parse(text: &str) -> Option<Self>; | ||
| 13 | +} | ||
| 14 | + | ||
| 8 | #[macro_export] | 15 | #[macro_export] |
| 9 | macro_rules! string_enum { | 16 | macro_rules! string_enum { |
| 10 | ($(#[$meta:meta])* $name:ident { $($variant:ident => $text:literal),+ $(,)? }) => { | 17 | ($(#[$meta:meta])* $name:ident { $($variant:ident => $text:literal),+ $(,)? }) => { |
| @@ -26,6 +33,16 @@ macro_rules! string_enum { | |||
| 26 | Self::ALL.into_iter().find(|item| item.as_str() == text) | 33 | Self::ALL.into_iter().find(|item| item.as_str() == text) |
| 27 | } | 34 | } |
| 28 | } | 35 | } |
| 36 | + | ||
| 37 | + impl $crate::model::Named for $name { | ||
| 38 | + fn as_str(self) -> &'static str { | ||
| 39 | + $name::as_str(self) | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + fn parse(text: &str) -> Option<Self> { | ||
| 43 | + $name::parse(text) | ||
| 44 | + } | ||
| 45 | + } | ||
| 29 | }; | 46 | }; |
| 30 | } | 47 | } |
| 31 | 48 | ||
| @@ -90,11 +107,12 @@ impl Rank { | |||
| 90 | 107 | ||
| 91 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 108 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 92 | pub struct User { | 109 | pub struct User { |
| 93 | - pub id: String, | 110 | + pub id: Id, |
| 94 | pub username: String, | 111 | pub username: String, |
| 95 | pub role: Role, | 112 | pub role: Role, |
| 96 | pub status: String, | 113 | pub status: String, |
| 97 | - pub avatar_id: Option<String>, | 114 | + pub avatar_id: Option<Id>, |
| 115 | + pub created_at: u64, | ||
| 98 | } | 116 | } |
| 99 | 117 | ||
| 100 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 118 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| @@ -108,7 +126,7 @@ pub struct Account { | |||
| 108 | 126 | ||
| 109 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 127 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 110 | pub struct SessionInfo { | 128 | pub struct SessionInfo { |
| 111 | - pub id: String, | 129 | + pub id: Id, |
| 112 | pub device: String, | 130 | pub device: String, |
| 113 | pub last_seen: Option<u64>, | 131 | pub last_seen: Option<u64>, |
| 114 | } | 132 | } |
| @@ -146,19 +164,19 @@ pub enum BanScope { | |||
| 146 | 164 | ||
| 147 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 165 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 148 | pub struct Community { | 166 | pub struct Community { |
| 149 | - pub id: String, | 167 | + pub id: Id, |
| 150 | pub name: String, | 168 | pub name: String, |
| 151 | pub kind: CommunityKind, | 169 | pub kind: CommunityKind, |
| 152 | - pub avatar_id: Option<String>, | 170 | + pub avatar_id: Option<Id>, |
| 153 | pub voice_enabled: bool, | 171 | pub voice_enabled: bool, |
| 154 | } | 172 | } |
| 155 | 173 | ||
| 156 | #[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)] | 174 | #[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)] |
| 157 | pub struct Unread { | 175 | pub struct Unread { |
| 158 | - pub community_id: String, | 176 | + pub community_id: Id, |
| 159 | pub messages: u32, | 177 | pub messages: u32, |
| 160 | pub mentions: u32, | 178 | pub mentions: u32, |
| 161 | - pub last_read: Option<String>, | 179 | + pub last_read: Option<Id>, |
| 162 | } | 180 | } |
| 163 | 181 | ||
| 164 | pub fn mentions(body: &str, username: &str) -> bool { | 182 | pub fn mentions(body: &str, username: &str) -> bool { |
| @@ -172,11 +190,11 @@ pub fn mentions(body: &str, username: &str) -> bool { | |||
| 172 | 190 | ||
| 173 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 191 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 174 | pub struct VoiceRoom { | 192 | pub struct VoiceRoom { |
| 175 | - pub community_id: String, | 193 | + pub community_id: Id, |
| 176 | pub community: String, | 194 | pub community: String, |
| 177 | pub users: Vec<User>, | 195 | pub users: Vec<User>, |
| 178 | - pub muted: Vec<String>, | 196 | + pub muted: Vec<Id>, |
| 179 | - pub ghosts: Vec<String>, | 197 | + pub ghosts: Vec<Id>, |
| 180 | } | 198 | } |
| 181 | 199 | ||
| 182 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 200 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| @@ -210,7 +228,8 @@ pub enum LogAction { | |||
| 210 | 228 | ||
| 211 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 229 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 212 | pub struct LogEntry { | 230 | pub struct LogEntry { |
| 213 | - pub id: String, | 231 | + pub id: Id, |
| 232 | + pub created_at: u64, | ||
| 214 | pub actor: Option<User>, | 233 | pub actor: Option<User>, |
| 215 | pub target: Option<User>, | 234 | pub target: Option<User>, |
| 216 | pub action: LogAction, | 235 | pub action: LogAction, |
| @@ -252,7 +271,7 @@ pub enum AdminAction { | |||
| 252 | } | 271 | } |
| 253 | 272 | ||
| 254 | string_enum! { | 273 | string_enum! { |
| 255 | - #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 274 | + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] |
| 256 | AdminActionKind { | 275 | AdminActionKind { |
| 257 | RoleChanged => "role_changed", | 276 | RoleChanged => "role_changed", |
| 258 | UserDeleted => "user_deleted", | 277 | UserDeleted => "user_deleted", |
| @@ -324,35 +343,14 @@ impl AdminAction { | |||
| 324 | AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, | 343 | AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, |
| 325 | } | 344 | } |
| 326 | } | 345 | } |
| 327 | - | ||
| 328 | - pub fn name(&self) -> &'static str { | ||
| 329 | - self.kind().as_str() | ||
| 330 | - } | ||
| 331 | -} | ||
| 332 | - | ||
| 333 | -pub fn action_detail(action: &AdminAction) -> Option<String> { | ||
| 334 | - match action { | ||
| 335 | - AdminAction::RoleChanged { role } => Some(role.as_str().to_string()), | ||
| 336 | - AdminAction::UserRenamed { from } => Some(from.clone()), | ||
| 337 | - AdminAction::UserTimedOut { minutes } => Some(minutes.to_string()), | ||
| 338 | - AdminAction::UserBanned { reason } => reason.clone(), | ||
| 339 | - AdminAction::ReportHandled { status } => Some(status.as_str().to_string()), | ||
| 340 | - AdminAction::UserPurged { messages } => Some(messages.to_string()), | ||
| 341 | - AdminAction::VoiceMuted { muted } => Some(muted.to_string()), | ||
| 342 | - AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()), | ||
| 343 | - AdminAction::GhostVoice { seconds } => Some(seconds.to_string()), | ||
| 344 | - AdminAction::BackupCreated { name } | ||
| 345 | - | AdminAction::BackupDeleted { name } | ||
| 346 | - | AdminAction::BackupDownloaded { name } => Some(name.clone()), | ||
| 347 | - _ => None, | ||
| 348 | - } | ||
| 349 | } | 346 | } |
| 350 | 347 | ||
| 351 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 348 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 352 | pub struct AdminLogEntry { | 349 | pub struct AdminLogEntry { |
| 353 | - pub id: String, | 350 | + pub id: Id, |
| 354 | pub actor: Option<User>, | 351 | pub actor: Option<User>, |
| 355 | pub target: Option<User>, | 352 | pub target: Option<User>, |
| 353 | + pub created_at: u64, | ||
| 356 | pub community: Option<String>, | 354 | pub community: Option<String>, |
| 357 | pub action: AdminAction, | 355 | pub action: AdminAction, |
| 358 | } | 356 | } |
| @@ -378,11 +376,12 @@ impl ReportStatus { | |||
| 378 | 376 | ||
| 379 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 377 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 380 | pub struct Report { | 378 | pub struct Report { |
| 381 | - pub id: String, | 379 | + pub id: Id, |
| 380 | + pub created_at: u64, | ||
| 382 | pub reporter: Option<User>, | 381 | pub reporter: Option<User>, |
| 383 | pub target: Option<User>, | 382 | pub target: Option<User>, |
| 384 | - pub message_id: Option<String>, | 383 | + pub message_id: Option<Id>, |
| 385 | - pub community_id: Option<String>, | 384 | + pub community_id: Option<Id>, |
| 386 | pub community: Option<String>, | 385 | pub community: Option<String>, |
| 387 | pub body: Option<String>, | 386 | pub body: Option<String>, |
| 388 | pub reason: String, | 387 | pub reason: String, |
| @@ -452,7 +451,7 @@ pub struct Usage { | |||
| 452 | 451 | ||
| 453 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 452 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 454 | pub struct CommunityUsage { | 453 | pub struct CommunityUsage { |
| 455 | - pub community_id: String, | 454 | + pub community_id: Id, |
| 456 | pub community: String, | 455 | pub community: String, |
| 457 | pub bytes: u64, | 456 | pub bytes: u64, |
| 458 | pub count: u64, | 457 | pub count: u64, |
| @@ -468,7 +467,7 @@ string_enum! { | |||
| 468 | 467 | ||
| 469 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 468 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 470 | pub struct ServerBan { | 469 | pub struct ServerBan { |
| 471 | - pub id: String, | 470 | + pub id: Id, |
| 472 | pub kind: ServerBanKind, | 471 | pub kind: ServerBanKind, |
| 473 | pub value: String, | 472 | pub value: String, |
| 474 | pub reason: Option<String>, | 473 | pub reason: Option<String>, |
| @@ -523,28 +522,30 @@ string_enum! { | |||
| 523 | 522 | ||
| 524 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 523 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 525 | pub struct Attachment { | 524 | pub struct Attachment { |
| 526 | - pub id: String, | 525 | + pub id: Id, |
| 527 | pub name: String, | 526 | pub name: String, |
| 528 | pub size: u64, | 527 | pub size: u64, |
| 529 | pub kind: AttachmentKind, | 528 | pub kind: AttachmentKind, |
| 529 | + pub created_at: u64, | ||
| 530 | pub width: Option<u32>, | 530 | pub width: Option<u32>, |
| 531 | pub height: Option<u32>, | 531 | pub height: Option<u32>, |
| 532 | } | 532 | } |
| 533 | 533 | ||
| 534 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 534 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 535 | pub struct Quote { | 535 | pub struct Quote { |
| 536 | - pub message_id: String, | 536 | + pub message_id: Id, |
| 537 | - pub user_id: String, | 537 | + pub user_id: Id, |
| 538 | pub body: String, | 538 | pub body: String, |
| 539 | - pub attachments: usize, | 539 | + pub attachments: u32, |
| 540 | } | 540 | } |
| 541 | 541 | ||
| 542 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 542 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 543 | pub struct SnippetMessage { | 543 | pub struct SnippetMessage { |
| 544 | - pub id: String, | 544 | + pub id: Id, |
| 545 | - pub user_id: String, | 545 | + pub user_id: Id, |
| 546 | pub username: String, | 546 | pub username: String, |
| 547 | - pub avatar_id: Option<String>, | 547 | + pub avatar_id: Option<Id>, |
| 548 | + pub created_at: u64, | ||
| 548 | pub body: String, | 549 | pub body: String, |
| 549 | pub attachments: Vec<Attachment>, | 550 | pub attachments: Vec<Attachment>, |
| 550 | pub poll: Option<Poll>, | 551 | pub poll: Option<Poll>, |
| @@ -559,13 +560,13 @@ pub struct Snippet { | |||
| 559 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 560 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 560 | pub struct Reaction { | 561 | pub struct Reaction { |
| 561 | pub emoji: String, | 562 | pub emoji: String, |
| 562 | - pub user_ids: Vec<String>, | 563 | + pub user_ids: Vec<Id>, |
| 563 | } | 564 | } |
| 564 | 565 | ||
| 565 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 566 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 566 | pub struct PollOption { | 567 | pub struct PollOption { |
| 567 | pub text: String, | 568 | pub text: String, |
| 568 | - pub voter_ids: Vec<String>, | 569 | + pub voter_ids: Vec<Id>, |
| 569 | } | 570 | } |
| 570 | 571 | ||
| 571 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 572 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| @@ -578,9 +579,10 @@ pub struct Poll { | |||
| 578 | 579 | ||
| 579 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 580 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 580 | pub struct Message { | 581 | pub struct Message { |
| 581 | - pub id: String, | 582 | + pub id: Id, |
| 582 | - pub user_id: String, | 583 | + pub user_id: Id, |
| 583 | - pub community_id: String, | 584 | + pub community_id: Id, |
| 585 | + pub created_at: u64, | ||
| 584 | pub body: String, | 586 | pub body: String, |
| 585 | pub attachments: Vec<Attachment>, | 587 | pub attachments: Vec<Attachment>, |
| 586 | pub reactions: Vec<Reaction>, | 588 | pub reactions: Vec<Reaction>, |
crates/common/src/open.rsmodified+4 -4
| @@ -1,6 +1,6 @@ | |||
| 1 | use bitcode::{Decode, Encode}; | 1 | use bitcode::{Decode, Encode}; |
| 2 | 2 | ||
| 3 | -use crate::call::Request; | 3 | +use crate::{call::Request, model::Id}; |
| 4 | 4 | ||
| 5 | #[derive(Debug, Clone, Encode, Decode)] | 5 | #[derive(Debug, Clone, Encode, Decode)] |
| 6 | pub enum Open { | 6 | pub enum Open { |
| @@ -11,14 +11,14 @@ pub enum Open { | |||
| 11 | 11 | ||
| 12 | #[derive(Debug, Clone, Encode, Decode)] | 12 | #[derive(Debug, Clone, Encode, Decode)] |
| 13 | pub struct Upload { | 13 | pub struct Upload { |
| 14 | - pub community_id: String, | 14 | + pub community_id: Id, |
| 15 | pub name: String, | 15 | pub name: String, |
| 16 | pub size: u64, | 16 | pub size: u64, |
| 17 | } | 17 | } |
| 18 | 18 | ||
| 19 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)] | 19 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)] |
| 20 | pub enum Blob { | 20 | pub enum Blob { |
| 21 | - Attachment(String), | 21 | + Attachment(Id), |
| 22 | - Thumbnail(String), | 22 | + Thumbnail(Id), |
| 23 | Backup(String), | 23 | Backup(String), |
| 24 | } | 24 | } |
crates/common/src/share.rsmodified+2 -2
| @@ -1,6 +1,6 @@ | |||
| 1 | use bitcode::{Decode, Encode}; | 1 | use bitcode::{Decode, Encode}; |
| 2 | 2 | ||
| 3 | -use crate::constant::MAXIMUM_SHARE_LAYERS; | 3 | +use crate::{constant::MAXIMUM_SHARE_LAYERS, model::Id}; |
| 4 | 4 | ||
| 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] | 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] |
| 6 | pub enum Codec { | 6 | pub enum Codec { |
| @@ -147,7 +147,7 @@ pub enum Kind { | |||
| 147 | 147 | ||
| 148 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 148 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| 149 | pub struct Share { | 149 | pub struct Share { |
| 150 | - pub user_id: String, | 150 | + pub user_id: Id, |
| 151 | pub kind: Kind, | 151 | pub kind: Kind, |
| 152 | pub source: Source, | 152 | pub source: Source, |
| 153 | } | 153 | } |
crates/common/src/time.rsmodified+0 -20
| @@ -10,23 +10,3 @@ pub fn now_ms() -> u64 { | |||
| 10 | .map(|elapsed| elapsed.as_millis() as u64) | 10 | .map(|elapsed| elapsed.as_millis() as u64) |
| 11 | .unwrap_or_default() | 11 | .unwrap_or_default() |
| 12 | } | 12 | } |
| 13 | - | ||
| 14 | -pub fn created_at_ms(id: &str) -> Option<u64> { | ||
| 15 | - let (seconds, nanos) = uuid::Uuid::parse_str(id).ok()?.get_timestamp()?.to_unix(); | ||
| 16 | - | ||
| 17 | - Some(seconds * 1000 + u64::from(nanos) / 1_000_000) | ||
| 18 | -} | ||
| 19 | - | ||
| 20 | -pub fn id_bound(ms: u64) -> String { | ||
| 21 | - format!("{:08x}-{:04x}", ms >> 16, ms & 0xffff) | ||
| 22 | -} | ||
| 23 | - | ||
| 24 | -pub fn range_bounds( | ||
| 25 | - after_ms: Option<u64>, | ||
| 26 | - before_ms: Option<u64>, | ||
| 27 | -) -> (Option<String>, Option<String>) { | ||
| 28 | - ( | ||
| 29 | - after_ms.map(id_bound), | ||
| 30 | - before_ms.map(|before| id_bound(before.saturating_add(1))), | ||
| 31 | - ) | ||
| 32 | -} | ||
crates/server/Cargo.tomlmodified+2 -2
| @@ -10,8 +10,8 @@ quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } | |||
| 10 | rcgen = "0.14.10" | 10 | rcgen = "0.14.10" |
| 11 | bitcode.workspace = true | 11 | bitcode.workspace = true |
| 12 | rustls.workspace = true | 12 | rustls.workspace = true |
| 13 | -turso = "0.9.0-pre.6" | 13 | +turso = { version = "0.9.0-pre.6", default-features = false } |
| 14 | -uuid = { version = "1.29.3", features = ["v7"] } | 14 | +sha2 = "0.11.2" |
| 15 | bytes = "1.12.2" | 15 | bytes = "1.12.2" |
| 16 | argon2 = "0.6.0" | 16 | argon2 = "0.6.0" |
| 17 | getrandom = "0.4.3" | 17 | getrandom = "0.4.3" |
crates/server/src/admin_log.rsdeleted+0 -117
| @@ -1,117 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - constant::LOG_PAGE_LIMIT, | ||
| 3 | - model::{AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail}, | ||
| 4 | - time, | ||
| 5 | -}; | ||
| 6 | -use turso::Connection; | ||
| 7 | - | ||
| 8 | -use crate::{database::new_id, error::ServerError, user}; | ||
| 9 | - | ||
| 10 | -fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> { | ||
| 11 | - Some(match AdminActionKind::parse(text)? { | ||
| 12 | - AdminActionKind::RoleChanged => AdminAction::RoleChanged { | ||
| 13 | - role: Role::parse(&detail?)?, | ||
| 14 | - }, | ||
| 15 | - AdminActionKind::UserDeleted => AdminAction::UserDeleted, | ||
| 16 | - AdminActionKind::UserSuspended => AdminAction::UserSuspended, | ||
| 17 | - AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended, | ||
| 18 | - AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked, | ||
| 19 | - AdminActionKind::PasswordReset => AdminAction::PasswordReset, | ||
| 20 | - AdminActionKind::ProfileCleared => AdminAction::ProfileCleared, | ||
| 21 | - AdminActionKind::UserCreated => AdminAction::UserCreated, | ||
| 22 | - AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted, | ||
| 23 | - AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred, | ||
| 24 | - AdminActionKind::SettingsChanged => AdminAction::SettingsChanged, | ||
| 25 | - AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? }, | ||
| 26 | - AdminActionKind::UserTimedOut => AdminAction::UserTimedOut { | ||
| 27 | - minutes: detail?.parse().ok()?, | ||
| 28 | - }, | ||
| 29 | - AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail }, | ||
| 30 | - AdminActionKind::BanRemoved => AdminAction::BanRemoved, | ||
| 31 | - AdminActionKind::InviteCreated => AdminAction::InviteCreated, | ||
| 32 | - AdminActionKind::InviteDeleted => AdminAction::InviteDeleted, | ||
| 33 | - AdminActionKind::ReportHandled => AdminAction::ReportHandled { | ||
| 34 | - status: ReportStatus::parse(&detail?)?, | ||
| 35 | - }, | ||
| 36 | - AdminActionKind::MessageDeleted => AdminAction::MessageDeleted, | ||
| 37 | - AdminActionKind::UserPurged => AdminAction::UserPurged { | ||
| 38 | - messages: detail?.parse().ok()?, | ||
| 39 | - }, | ||
| 40 | - AdminActionKind::VoiceKicked => AdminAction::VoiceKicked, | ||
| 41 | - AdminActionKind::VoiceMuted => AdminAction::VoiceMuted { | ||
| 42 | - muted: detail?.parse().ok()?, | ||
| 43 | - }, | ||
| 44 | - AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet { | ||
| 45 | - enabled: detail?.parse().ok()?, | ||
| 46 | - }, | ||
| 47 | - AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted, | ||
| 48 | - AdminActionKind::GhostEnabled => AdminAction::GhostEnabled, | ||
| 49 | - AdminActionKind::GhostDisabled => AdminAction::GhostDisabled, | ||
| 50 | - AdminActionKind::GhostVisit => AdminAction::GhostVisit, | ||
| 51 | - AdminActionKind::GhostVoice => AdminAction::GhostVoice { | ||
| 52 | - seconds: detail?.parse().ok()?, | ||
| 53 | - }, | ||
| 54 | - AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? }, | ||
| 55 | - AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? }, | ||
| 56 | - AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? }, | ||
| 57 | - }) | ||
| 58 | -} | ||
| 59 | - | ||
| 60 | -pub async fn record( | ||
| 61 | - actor_id: Option<&str>, | ||
| 62 | - target_id: Option<&str>, | ||
| 63 | - community: Option<&str>, | ||
| 64 | - action: &AdminAction, | ||
| 65 | - conn: &Connection, | ||
| 66 | -) -> Result<(), ServerError> { | ||
| 67 | - let id = new_id(); | ||
| 68 | - let detail = action_detail(action); | ||
| 69 | - conn.execute( | ||
| 70 | - "INSERT INTO admin_log (id, actor_id, target_id, community, action, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | ||
| 71 | - ( | ||
| 72 | - id.as_str(), | ||
| 73 | - actor_id, | ||
| 74 | - target_id, | ||
| 75 | - community, | ||
| 76 | - action.name(), | ||
| 77 | - detail.as_deref(), | ||
| 78 | - ), | ||
| 79 | - ) | ||
| 80 | - .await?; | ||
| 81 | - | ||
| 82 | - Ok(()) | ||
| 83 | -} | ||
| 84 | - | ||
| 85 | -pub async fn list( | ||
| 86 | - actor_id: Option<&str>, | ||
| 87 | - target_id: Option<&str>, | ||
| 88 | - action: Option<&str>, | ||
| 89 | - after_ms: Option<u64>, | ||
| 90 | - before_ms: Option<u64>, | ||
| 91 | - conn: &Connection, | ||
| 92 | -) -> Result<Vec<AdminLogEntry>, ServerError> { | ||
| 93 | - let (after, before) = time::range_bounds(after_ms, before_ms); | ||
| 94 | - let mut rows = conn | ||
| 95 | - .query( | ||
| 96 | - &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")), | ||
| 97 | - (actor_id, target_id, action, after, before), | ||
| 98 | - ) | ||
| 99 | - .await?; | ||
| 100 | - | ||
| 101 | - let mut entries = Vec::new(); | ||
| 102 | - while let Some(row) = rows.next().await? { | ||
| 103 | - let text: String = row.get(1)?; | ||
| 104 | - let Some(action) = action_of(&text, row.get(2)?) else { | ||
| 105 | - continue; | ||
| 106 | - }; | ||
| 107 | - entries.push(AdminLogEntry { | ||
| 108 | - id: row.get(0)?, | ||
| 109 | - actor: user::from_row_at(&row, 3)?, | ||
| 110 | - target: user::from_row_at(&row, 8)?, | ||
| 111 | - community: row.get(13)?, | ||
| 112 | - action, | ||
| 113 | - }); | ||
| 114 | - } | ||
| 115 | - | ||
| 116 | - Ok(entries) | ||
| 117 | -} | ||
crates/server/src/attachment.rsdeleted+0 -746
| @@ -1,746 +0,0 @@ | |||
| 1 | -use std::{ | ||
| 2 | - collections::HashSet, | ||
| 3 | - io::{BufReader, Cursor}, | ||
| 4 | - path::{Path, PathBuf}, | ||
| 5 | - time::{Duration, SystemTime}, | ||
| 6 | -}; | ||
| 7 | - | ||
| 8 | -use common::{ | ||
| 9 | - constant::{ | ||
| 10 | - ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, MAXIMUM_ATTACHMENTS_PER_MESSAGE, | ||
| 11 | - THUMBNAIL_SIZE, | ||
| 12 | - }, | ||
| 13 | - error::{Error as CommonError, Field, Problem}, | ||
| 14 | - frame::{self, DOWN_MAX, Sending}, | ||
| 15 | - model::{ | ||
| 16 | - Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, | ||
| 17 | - }, | ||
| 18 | - open::{Blob, Upload}, | ||
| 19 | - permission, | ||
| 20 | - time::{self, HOUR_MILLIS}, | ||
| 21 | - validate::{validate_attachment_name, validate_attachment_size}, | ||
| 22 | -}; | ||
| 23 | -use image::{ImageFormat, ImageReader, Limits}; | ||
| 24 | -use quinn::{RecvStream, VarInt}; | ||
| 25 | -use tokio::{ | ||
| 26 | - fs::File, | ||
| 27 | - io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, | ||
| 28 | -}; | ||
| 29 | -use tracing::error; | ||
| 30 | -use turso::{Connection, Row}; | ||
| 31 | - | ||
| 32 | -use crate::{ | ||
| 33 | - backup, community, | ||
| 34 | - database::{self, DB, new_id}, | ||
| 35 | - error::ServerError, | ||
| 36 | - request::{actor_rank, ensure}, | ||
| 37 | - server_settings, user, | ||
| 38 | -}; | ||
| 39 | - | ||
| 40 | -const COLLECT_INTERVAL: Duration = Duration::from_secs(600); | ||
| 41 | -const MAXIMUM_IMAGE_SIDE: u32 = 16384; | ||
| 42 | -const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; | ||
| 43 | -const LIST_LIMIT: i64 = 200; | ||
| 44 | -const USAGE_LIMIT: i64 = 50; | ||
| 45 | -const THUMB_SUFFIX: &str = ".thumb"; | ||
| 46 | -const PART_SUFFIX: &str = ".part"; | ||
| 47 | - | ||
| 48 | -pub struct Stored { | ||
| 49 | - pub attachment: Attachment, | ||
| 50 | - pub uploader_id: String, | ||
| 51 | - pub community_id: String, | ||
| 52 | - pub message_id: Option<String>, | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -fn from_row(row: &Row) -> Result<Attachment, ServerError> { | ||
| 56 | - let size: i64 = row.get(2)?; | ||
| 57 | - let kind: String = row.get(3)?; | ||
| 58 | - let width: Option<i64> = row.get(4)?; | ||
| 59 | - let height: Option<i64> = row.get(5)?; | ||
| 60 | - | ||
| 61 | - Ok(Attachment { | ||
| 62 | - id: row.get(0)?, | ||
| 63 | - name: row.get(1)?, | ||
| 64 | - size: size as u64, | ||
| 65 | - kind: AttachmentKind::parse(&kind).ok_or(CommonError::Server)?, | ||
| 66 | - width: width.map(|value| value as u32), | ||
| 67 | - height: height.map(|value| value as u32), | ||
| 68 | - }) | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -pub async fn of_message( | ||
| 72 | - message_id: &str, | ||
| 73 | - snippet_position: Option<i64>, | ||
| 74 | - conn: &Connection, | ||
| 75 | -) -> Result<Vec<Attachment>, ServerError> { | ||
| 76 | - let mut rows = conn | ||
| 77 | - .query( | ||
| 78 | - "SELECT id, name, size, kind, width, height FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id", | ||
| 79 | - (message_id, snippet_position), | ||
| 80 | - ) | ||
| 81 | - .await?; | ||
| 82 | - | ||
| 83 | - let mut attachments = Vec::new(); | ||
| 84 | - while let Some(row) = rows.next().await? { | ||
| 85 | - attachments.push(from_row(&row)?); | ||
| 86 | - } | ||
| 87 | - | ||
| 88 | - Ok(attachments) | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -pub async fn bind( | ||
| 92 | - message_id: &str, | ||
| 93 | - user_id: &str, | ||
| 94 | - community_id: &str, | ||
| 95 | - attachment_ids: &[String], | ||
| 96 | - conn: &Connection, | ||
| 97 | -) -> Result<(), ServerError> { | ||
| 98 | - if attachment_ids.len() > MAXIMUM_ATTACHMENTS_PER_MESSAGE { | ||
| 99 | - return Err(CommonError::NotFound.into()); | ||
| 100 | - } | ||
| 101 | - | ||
| 102 | - for attachment_id in attachment_ids { | ||
| 103 | - let bound = conn | ||
| 104 | - .execute( | ||
| 105 | - "UPDATE attachment SET message_id = ?1 WHERE id = ?2 AND uploader_id = ?3 AND community_id = ?4 AND message_id IS NULL", | ||
| 106 | - (message_id, attachment_id.as_str(), user_id, community_id), | ||
| 107 | - ) | ||
| 108 | - .await?; | ||
| 109 | - database::expect_one(bound)?; | ||
| 110 | - } | ||
| 111 | - | ||
| 112 | - Ok(()) | ||
| 113 | -} | ||
| 114 | - | ||
| 115 | -fn thumb_path(directory: &Path, id: &str) -> PathBuf { | ||
| 116 | - directory.join(format!("{id}{THUMB_SUFFIX}")) | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | -fn part_path(directory: &Path, id: &str) -> PathBuf { | ||
| 120 | - directory.join(format!("{id}{PART_SUFFIX}")) | ||
| 121 | -} | ||
| 122 | - | ||
| 123 | -fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> { | ||
| 124 | - std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop)) | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { | ||
| 128 | - tokio::task::spawn_blocking(move || link_or_copy(&source, &target)) | ||
| 129 | - .await | ||
| 130 | - .map_err(|_| CommonError::Server)? | ||
| 131 | - .map_err(|_| CommonError::Server)?; | ||
| 132 | - | ||
| 133 | - Ok(()) | ||
| 134 | -} | ||
| 135 | - | ||
| 136 | -async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), ServerError> { | ||
| 137 | - if tokio::fs::try_exists(&source) | ||
| 138 | - .await | ||
| 139 | - .map_err(|_| CommonError::Server)? | ||
| 140 | - { | ||
| 141 | - duplicate(source, target).await?; | ||
| 142 | - } | ||
| 143 | - | ||
| 144 | - Ok(()) | ||
| 145 | -} | ||
| 146 | - | ||
| 147 | -pub async fn copy( | ||
| 148 | - attachment: &Attachment, | ||
| 149 | - message_id: &str, | ||
| 150 | - user_id: &str, | ||
| 151 | - community_id: &str, | ||
| 152 | - snippet_position: Option<i64>, | ||
| 153 | - directory: &Path, | ||
| 154 | - conn: &Connection, | ||
| 155 | -) -> Result<(), ServerError> { | ||
| 156 | - let id = new_id(); | ||
| 157 | - conn.execute( | ||
| 158 | - "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)", | ||
| 159 | - ( | ||
| 160 | - id.as_str(), | ||
| 161 | - user_id, | ||
| 162 | - community_id, | ||
| 163 | - message_id, | ||
| 164 | - attachment.name.as_str(), | ||
| 165 | - attachment.size as i64, | ||
| 166 | - attachment.kind.as_str(), | ||
| 167 | - attachment.width.map(i64::from), | ||
| 168 | - attachment.height.map(i64::from), | ||
| 169 | - snippet_position, | ||
| 170 | - ), | ||
| 171 | - ) | ||
| 172 | - .await?; | ||
| 173 | - | ||
| 174 | - duplicate(directory.join(&attachment.id), directory.join(&id)).await?; | ||
| 175 | - duplicate_if_exists( | ||
| 176 | - thumb_path(directory, &attachment.id), | ||
| 177 | - thumb_path(directory, &id), | ||
| 178 | - ) | ||
| 179 | - .await | ||
| 180 | -} | ||
| 181 | - | ||
| 182 | -pub async fn ids_of_message( | ||
| 183 | - message_id: &str, | ||
| 184 | - conn: &Connection, | ||
| 185 | -) -> Result<Vec<String>, ServerError> { | ||
| 186 | - database::ids( | ||
| 187 | - conn, | ||
| 188 | - "SELECT id FROM attachment WHERE message_id = ?1", | ||
| 189 | - (message_id,), | ||
| 190 | - ) | ||
| 191 | - .await | ||
| 192 | -} | ||
| 193 | - | ||
| 194 | -pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 195 | - conn.execute("DELETE FROM attachment WHERE id = ?1", (attachment_id,)) | ||
| 196 | - .await?; | ||
| 197 | - | ||
| 198 | - Ok(()) | ||
| 199 | -} | ||
| 200 | - | ||
| 201 | -pub async fn all( | ||
| 202 | - user_id: Option<&str>, | ||
| 203 | - community_id: Option<&str>, | ||
| 204 | - conn: &Connection, | ||
| 205 | -) -> Result<Vec<AttachmentInfo>, ServerError> { | ||
| 206 | - let mut rows = conn | ||
| 207 | - .query( | ||
| 208 | - &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")), | ||
| 209 | - (user_id, community_id, LIST_LIMIT), | ||
| 210 | - ) | ||
| 211 | - .await?; | ||
| 212 | - | ||
| 213 | - let mut raw = Vec::new(); | ||
| 214 | - while let Some(row) = rows.next().await? { | ||
| 215 | - let community_id: String = row.get(6)?; | ||
| 216 | - raw.push((from_row(&row)?, user::from_row_at(&row, 7)?, community_id)); | ||
| 217 | - } | ||
| 218 | - drop(rows); | ||
| 219 | - | ||
| 220 | - let mut infos = Vec::new(); | ||
| 221 | - for (attachment, uploader, community_id) in raw { | ||
| 222 | - infos.push(AttachmentInfo { | ||
| 223 | - attachment, | ||
| 224 | - uploader, | ||
| 225 | - community: community::label(&community_id, conn).await?, | ||
| 226 | - }); | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - Ok(infos) | ||
| 230 | -} | ||
| 231 | - | ||
| 232 | -async fn totals(column: &str, conn: &Connection) -> Result<Vec<(String, u64, u64)>, ServerError> { | ||
| 233 | - let mut rows = conn | ||
| 234 | - .query( | ||
| 235 | - &format!( | ||
| 236 | - "SELECT {column}, SUM(size), COUNT(*) FROM attachment GROUP BY {column} ORDER BY SUM(size) DESC LIMIT ?1" | ||
| 237 | - ), | ||
| 238 | - (USAGE_LIMIT,), | ||
| 239 | - ) | ||
| 240 | - .await?; | ||
| 241 | - | ||
| 242 | - let mut totals = Vec::new(); | ||
| 243 | - while let Some(row) = rows.next().await? { | ||
| 244 | - let bytes: i64 = row.get(1)?; | ||
| 245 | - let count: i64 = row.get(2)?; | ||
| 246 | - totals.push((row.get(0)?, bytes as u64, count as u64)); | ||
| 247 | - } | ||
| 248 | - | ||
| 249 | - Ok(totals) | ||
| 250 | -} | ||
| 251 | - | ||
| 252 | -pub async fn usage(conn: &Connection) -> Result<(Vec<Usage>, Vec<CommunityUsage>), ServerError> { | ||
| 253 | - let mut users = Vec::new(); | ||
| 254 | - for (user_id, bytes, count) in totals("uploader_id", conn).await? { | ||
| 255 | - users.push(Usage { | ||
| 256 | - user: user::read(&user_id, conn).await?, | ||
| 257 | - bytes, | ||
| 258 | - count, | ||
| 259 | - }); | ||
| 260 | - } | ||
| 261 | - | ||
| 262 | - let mut communities = Vec::new(); | ||
| 263 | - for (community_id, bytes, count) in totals("community_id", conn).await? { | ||
| 264 | - communities.push(CommunityUsage { | ||
| 265 | - community: community::label(&community_id, conn).await?, | ||
| 266 | - community_id, | ||
| 267 | - bytes, | ||
| 268 | - count, | ||
| 269 | - }); | ||
| 270 | - } | ||
| 271 | - | ||
| 272 | - Ok((users, communities)) | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -async fn over_quota( | ||
| 276 | - sql: &str, | ||
| 277 | - key: &str, | ||
| 278 | - limit: u64, | ||
| 279 | - size: u64, | ||
| 280 | - conn: &Connection, | ||
| 281 | -) -> Result<bool, ServerError> { | ||
| 282 | - if limit == 0 { | ||
| 283 | - return Ok(false); | ||
| 284 | - } | ||
| 285 | - let used = database::scalar_i64(conn, sql, (key,)).await?; | ||
| 286 | - | ||
| 287 | - Ok(used as u64 + size > limit) | ||
| 288 | -} | ||
| 289 | - | ||
| 290 | -async fn ensure_quota( | ||
| 291 | - user_id: &str, | ||
| 292 | - community_id: &str, | ||
| 293 | - size: u64, | ||
| 294 | - settings: &ServerSettings, | ||
| 295 | - conn: &Connection, | ||
| 296 | -) -> Result<(), ServerError> { | ||
| 297 | - if over_quota( | ||
| 298 | - "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1", | ||
| 299 | - user_id, | ||
| 300 | - settings.user_quota_bytes, | ||
| 301 | - size, | ||
| 302 | - conn, | ||
| 303 | - ) | ||
| 304 | - .await? | ||
| 305 | - { | ||
| 306 | - return Err(CommonError::QuotaExceeded.into()); | ||
| 307 | - } | ||
| 308 | - if over_quota( | ||
| 309 | - "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?1", | ||
| 310 | - community_id, | ||
| 311 | - settings.community_quota_bytes, | ||
| 312 | - size, | ||
| 313 | - conn, | ||
| 314 | - ) | ||
| 315 | - .await? | ||
| 316 | - { | ||
| 317 | - return Err(CommonError::QuotaExceeded.into()); | ||
| 318 | - } | ||
| 319 | - | ||
| 320 | - Ok(()) | ||
| 321 | -} | ||
| 322 | - | ||
| 323 | -pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 324 | - database::ids( | ||
| 325 | - conn, | ||
| 326 | - "SELECT id FROM attachment WHERE uploader_id = ?1", | ||
| 327 | - (user_id,), | ||
| 328 | - ) | ||
| 329 | - .await | ||
| 330 | -} | ||
| 331 | - | ||
| 332 | -pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 333 | - conn.execute("DELETE FROM attachment WHERE uploader_id = ?1", (user_id,)) | ||
| 334 | - .await?; | ||
| 335 | - | ||
| 336 | - Ok(()) | ||
| 337 | -} | ||
| 338 | - | ||
| 339 | -pub fn remove_files(attachment_ids: &[String], directory: &Path) { | ||
| 340 | - for id in attachment_ids { | ||
| 341 | - let _ = std::fs::remove_file(directory.join(id)); | ||
| 342 | - let _ = std::fs::remove_file(thumb_path(directory, id)); | ||
| 343 | - } | ||
| 344 | -} | ||
| 345 | - | ||
| 346 | -pub async fn read(attachment_id: &str, conn: &Connection) -> Result<Stored, ServerError> { | ||
| 347 | - let mut rows = conn | ||
| 348 | - .query( | ||
| 349 | - "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id FROM attachment WHERE id = ?1", | ||
| 350 | - (attachment_id,), | ||
| 351 | - ) | ||
| 352 | - .await?; | ||
| 353 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 354 | - | ||
| 355 | - Ok(Stored { | ||
| 356 | - attachment: from_row(&row)?, | ||
| 357 | - uploader_id: row.get(6)?, | ||
| 358 | - community_id: row.get(7)?, | ||
| 359 | - message_id: row.get(8)?, | ||
| 360 | - }) | ||
| 361 | -} | ||
| 362 | - | ||
| 363 | -fn media_kind(head: &[u8]) -> AttachmentKind { | ||
| 364 | - if is_video(head) { | ||
| 365 | - AttachmentKind::Video | ||
| 366 | - } else if is_audio(head) { | ||
| 367 | - AttachmentKind::Audio | ||
| 368 | - } else { | ||
| 369 | - AttachmentKind::File | ||
| 370 | - } | ||
| 371 | -} | ||
| 372 | - | ||
| 373 | -fn is_image(head: &[u8]) -> bool { | ||
| 374 | - matches!( | ||
| 375 | - image::guess_format(head), | ||
| 376 | - Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) | ||
| 377 | - ) | ||
| 378 | -} | ||
| 379 | - | ||
| 380 | -fn is_video(head: &[u8]) -> bool { | ||
| 381 | - head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) | ||
| 382 | -} | ||
| 383 | - | ||
| 384 | -fn is_audio(head: &[u8]) -> bool { | ||
| 385 | - head.starts_with(b"OggS") | ||
| 386 | - || head.starts_with(b"fLaC") | ||
| 387 | - || head.starts_with(b"ID3") | ||
| 388 | - || head.starts_with(&[0xFF, 0xFB]) | ||
| 389 | - || head.starts_with(&[0xFF, 0xF3]) | ||
| 390 | - || head.starts_with(&[0xFF, 0xF2]) | ||
| 391 | - || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE")) | ||
| 392 | -} | ||
| 393 | - | ||
| 394 | -fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> { | ||
| 395 | - let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?)) | ||
| 396 | - .with_guessed_format() | ||
| 397 | - .ok()?; | ||
| 398 | - let mut limits = Limits::default(); | ||
| 399 | - limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE); | ||
| 400 | - limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE); | ||
| 401 | - limits.max_alloc = Some(MAXIMUM_DECODE_BYTES); | ||
| 402 | - reader.limits(limits); | ||
| 403 | - let image = reader.decode().ok()?; | ||
| 404 | - let (width, height) = (image.width(), image.height()); | ||
| 405 | - | ||
| 406 | - let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE { | ||
| 407 | - image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE) | ||
| 408 | - } else { | ||
| 409 | - image | ||
| 410 | - }; | ||
| 411 | - let mut bytes = Cursor::new(Vec::new()); | ||
| 412 | - fitted | ||
| 413 | - .to_rgb8() | ||
| 414 | - .write_to(&mut bytes, ImageFormat::Jpeg) | ||
| 415 | - .ok()?; | ||
| 416 | - std::fs::write(thumbnail, bytes.into_inner()).ok()?; | ||
| 417 | - | ||
| 418 | - Some((width, height)) | ||
| 419 | -} | ||
| 420 | - | ||
| 421 | -async fn receive_body<R: AsyncRead + Unpin>( | ||
| 422 | - reader: &mut R, | ||
| 423 | - part: &Path, | ||
| 424 | - size: u64, | ||
| 425 | -) -> Result<Vec<u8>, ServerError> { | ||
| 426 | - let mismatch = |actual: u64| CommonError::Invalid { | ||
| 427 | - field: Field::Attachment, | ||
| 428 | - problem: Problem::Length { | ||
| 429 | - min: size, | ||
| 430 | - max: size, | ||
| 431 | - actual, | ||
| 432 | - }, | ||
| 433 | - }; | ||
| 434 | - let mut file = File::create(part).await?; | ||
| 435 | - | ||
| 436 | - let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize]; | ||
| 437 | - reader.read_exact(&mut head).await?; | ||
| 438 | - file.write_all(&head).await?; | ||
| 439 | - | ||
| 440 | - let mut received = head.len() as u64; | ||
| 441 | - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; | ||
| 442 | - loop { | ||
| 443 | - let read = reader.read(&mut buffer).await?; | ||
| 444 | - if read == 0 { | ||
| 445 | - break; | ||
| 446 | - } | ||
| 447 | - | ||
| 448 | - received += read as u64; | ||
| 449 | - if received > size { | ||
| 450 | - return Err(mismatch(received).into()); | ||
| 451 | - } | ||
| 452 | - file.write_all(&buffer[..read]).await?; | ||
| 453 | - } | ||
| 454 | - | ||
| 455 | - if received != size { | ||
| 456 | - return Err(mismatch(received).into()); | ||
| 457 | - } | ||
| 458 | - file.flush().await?; | ||
| 459 | - | ||
| 460 | - Ok(head) | ||
| 461 | -} | ||
| 462 | - | ||
| 463 | -pub async fn store<R: AsyncRead + Unpin>( | ||
| 464 | - user: &User, | ||
| 465 | - header: &Upload, | ||
| 466 | - reader: &mut R, | ||
| 467 | - db: &DB, | ||
| 468 | - directory: &Path, | ||
| 469 | -) -> Result<Attachment, ServerError> { | ||
| 470 | - let conn = database::connect(db).await?; | ||
| 471 | - let rank = actor_rank(user, &header.community_id, &conn).await?; | ||
| 472 | - ensure(permission::can_post(rank))?; | ||
| 473 | - validate_attachment_name(&header.name)?; | ||
| 474 | - let settings = server_settings::read(&conn).await?; | ||
| 475 | - validate_attachment_size(header.size, settings.max_attachment_bytes)?; | ||
| 476 | - ensure_quota( | ||
| 477 | - &user.id, | ||
| 478 | - &header.community_id, | ||
| 479 | - header.size, | ||
| 480 | - &settings, | ||
| 481 | - &conn, | ||
| 482 | - ) | ||
| 483 | - .await?; | ||
| 484 | - | ||
| 485 | - let id = new_id(); | ||
| 486 | - let part = part_path(directory, &id); | ||
| 487 | - let path = directory.join(&id); | ||
| 488 | - let head = match receive_body(reader, &part, header.size).await { | ||
| 489 | - Ok(head) => head, | ||
| 490 | - Err(error) => { | ||
| 491 | - let _ = tokio::fs::remove_file(&part).await; | ||
| 492 | - return Err(error); | ||
| 493 | - } | ||
| 494 | - }; | ||
| 495 | - tokio::fs::rename(&part, &path).await?; | ||
| 496 | - | ||
| 497 | - let described = if is_image(&head) { | ||
| 498 | - let source = path.clone(); | ||
| 499 | - let thumbnail = thumb_path(directory, &id); | ||
| 500 | - tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)) | ||
| 501 | - .await | ||
| 502 | - .ok() | ||
| 503 | - .flatten() | ||
| 504 | - } else { | ||
| 505 | - None | ||
| 506 | - }; | ||
| 507 | - let (kind, width, height) = match described { | ||
| 508 | - Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)), | ||
| 509 | - None => (media_kind(&head), None, None), | ||
| 510 | - }; | ||
| 511 | - | ||
| 512 | - let mut rows = conn | ||
| 513 | - .query( | ||
| 514 | - "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", | ||
| 515 | - ( | ||
| 516 | - id.as_str(), | ||
| 517 | - user.id.as_str(), | ||
| 518 | - header.community_id.as_str(), | ||
| 519 | - header.name.as_str(), | ||
| 520 | - header.size as i64, | ||
| 521 | - kind.as_str(), | ||
| 522 | - width.map(i64::from), | ||
| 523 | - height.map(i64::from), | ||
| 524 | - ), | ||
| 525 | - ) | ||
| 526 | - .await?; | ||
| 527 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 528 | - | ||
| 529 | - from_row(&row) | ||
| 530 | -} | ||
| 531 | - | ||
| 532 | -pub async fn upload( | ||
| 533 | - user: Option<&User>, | ||
| 534 | - header: Upload, | ||
| 535 | - mut receive_stream: RecvStream, | ||
| 536 | - mut send_stream: Sending, | ||
| 537 | - db: &DB, | ||
| 538 | - directory: &Path, | ||
| 539 | -) -> Result<(), ServerError> { | ||
| 540 | - let stored = match user { | ||
| 541 | - Some(user) => store(user, &header, &mut receive_stream, db, directory).await, | ||
| 542 | - None => Err(CommonError::Unauthenticated.into()), | ||
| 543 | - }; | ||
| 544 | - let rejected = stored.is_err(); | ||
| 545 | - let reply = stored.map_err(CommonError::from); | ||
| 546 | - | ||
| 547 | - frame::write(&mut send_stream, &reply, DOWN_MAX).await?; | ||
| 548 | - send_stream.finish()?; | ||
| 549 | - if rejected { | ||
| 550 | - let _ = receive_stream.stop(VarInt::from_u32(0)); | ||
| 551 | - } | ||
| 552 | - | ||
| 553 | - Ok(()) | ||
| 554 | -} | ||
| 555 | - | ||
| 556 | -pub async fn locate( | ||
| 557 | - user: Option<&User>, | ||
| 558 | - attachment_id: &str, | ||
| 559 | - thumbnail: bool, | ||
| 560 | - db: &DB, | ||
| 561 | - directory: &Path, | ||
| 562 | -) -> Result<(PathBuf, u64), ServerError> { | ||
| 563 | - let user = user.ok_or(CommonError::Unauthenticated)?; | ||
| 564 | - let conn = database::connect(db).await?; | ||
| 565 | - let stored = read(attachment_id, &conn).await?; | ||
| 566 | - | ||
| 567 | - let rank = actor_rank(user, &stored.community_id, &conn).await?; | ||
| 568 | - ensure(permission::can_read(rank))?; | ||
| 569 | - ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; | ||
| 570 | - | ||
| 571 | - let path = if thumbnail { | ||
| 572 | - thumb_path(directory, &stored.attachment.id) | ||
| 573 | - } else { | ||
| 574 | - directory.join(&stored.attachment.id) | ||
| 575 | - }; | ||
| 576 | - let length = tokio::fs::metadata(&path) | ||
| 577 | - .await | ||
| 578 | - .map_err(|_| CommonError::NotFound)? | ||
| 579 | - .len(); | ||
| 580 | - | ||
| 581 | - Ok((path, length)) | ||
| 582 | -} | ||
| 583 | - | ||
| 584 | -pub async fn fetch( | ||
| 585 | - user: Option<&User>, | ||
| 586 | - blob: Blob, | ||
| 587 | - mut send_stream: Sending, | ||
| 588 | - db: &DB, | ||
| 589 | - directory: &Path, | ||
| 590 | - backups: &Path, | ||
| 591 | -) -> Result<(), ServerError> { | ||
| 592 | - let located = match &blob { | ||
| 593 | - Blob::Attachment(id) => locate(user, id, false, db, directory).await, | ||
| 594 | - Blob::Thumbnail(id) => locate(user, id, true, db, directory).await, | ||
| 595 | - Blob::Backup(name) => backup::locate(user, name, db, backups).await, | ||
| 596 | - }; | ||
| 597 | - let located = located.map_err(CommonError::from); | ||
| 598 | - let reply = located | ||
| 599 | - .as_ref() | ||
| 600 | - .map(|(_, length)| *length) | ||
| 601 | - .map_err(Clone::clone); | ||
| 602 | - frame::write(&mut send_stream, &reply, DOWN_MAX).await?; | ||
| 603 | - | ||
| 604 | - if let Ok((path, _)) = located { | ||
| 605 | - let mut file = File::open(path).await?; | ||
| 606 | - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; | ||
| 607 | - loop { | ||
| 608 | - let read = file.read(&mut buffer).await?; | ||
| 609 | - if read == 0 { | ||
| 610 | - break; | ||
| 611 | - } | ||
| 612 | - send_stream.get().write_all(&buffer[..read]).await?; | ||
| 613 | - } | ||
| 614 | - } | ||
| 615 | - send_stream.finish()?; | ||
| 616 | - | ||
| 617 | - Ok(()) | ||
| 618 | -} | ||
| 619 | - | ||
| 620 | -pub async fn collect(db: DB, directory: PathBuf) { | ||
| 621 | - let mut interval = tokio::time::interval(COLLECT_INTERVAL); | ||
| 622 | - loop { | ||
| 623 | - interval.tick().await; | ||
| 624 | - if let Err(error) = sweep(&db, &directory).await { | ||
| 625 | - error!("attachment sweep: {error}"); | ||
| 626 | - } | ||
| 627 | - } | ||
| 628 | -} | ||
| 629 | - | ||
| 630 | -async fn sweep(db: &DB, directory: &Path) -> Result<(), ServerError> { | ||
| 631 | - let conn = database::connect(db).await?; | ||
| 632 | - let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS); | ||
| 633 | - let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); | ||
| 634 | - let stale_id = time::id_bound(stale_ms); | ||
| 635 | - | ||
| 636 | - conn.execute( | ||
| 637 | - "DELETE FROM attachment WHERE message_id IS NULL AND id < ?1", | ||
| 638 | - (stale_id.as_str(),), | ||
| 639 | - ) | ||
| 640 | - .await?; | ||
| 641 | - | ||
| 642 | - let mut rows = conn.query("SELECT id FROM attachment", ()).await?; | ||
| 643 | - let mut ids = HashSet::new(); | ||
| 644 | - while let Some(row) = rows.next().await? { | ||
| 645 | - ids.insert(row.get::<String>(0)?); | ||
| 646 | - } | ||
| 647 | - drop(rows); | ||
| 648 | - | ||
| 649 | - for entry in std::fs::read_dir(directory)? { | ||
| 650 | - let Ok(entry) = entry else { continue }; | ||
| 651 | - let name = entry.file_name().to_string_lossy().into_owned(); | ||
| 652 | - let id = name | ||
| 653 | - .strip_suffix(THUMB_SUFFIX) | ||
| 654 | - .or_else(|| name.strip_suffix(PART_SUFFIX)) | ||
| 655 | - .unwrap_or(&name); | ||
| 656 | - let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { | ||
| 657 | - continue; | ||
| 658 | - }; | ||
| 659 | - let stale = modified < stale_at && id < stale_id.as_str(); | ||
| 660 | - | ||
| 661 | - if stale && !ids.contains(id) { | ||
| 662 | - let _ = std::fs::remove_file(entry.path()); | ||
| 663 | - } | ||
| 664 | - } | ||
| 665 | - | ||
| 666 | - Ok(()) | ||
| 667 | -} | ||
| 668 | - | ||
| 669 | -#[cfg(test)] | ||
| 670 | -mod tests { | ||
| 671 | - use std::io::Cursor; | ||
| 672 | - | ||
| 673 | - use common::{ | ||
| 674 | - call::CreateMessage, | ||
| 675 | - model::{AttachmentKind, Rank}, | ||
| 676 | - open::Upload, | ||
| 677 | - }; | ||
| 678 | - use image::{ImageFormat, RgbImage}; | ||
| 679 | - | ||
| 680 | - use crate::{ | ||
| 681 | - attachment::{store, thumb_path}, | ||
| 682 | - call::{Cx, Handle, Me}, | ||
| 683 | - community, database, | ||
| 684 | - hub::{Client, Signed}, | ||
| 685 | - message, | ||
| 686 | - network::{Services, Shared}, | ||
| 687 | - test, user, user_community, | ||
| 688 | - }; | ||
| 689 | - | ||
| 690 | - #[tokio::test] | ||
| 691 | - async fn upload_then_read_in_message() { | ||
| 692 | - let db = test::get_database().await; | ||
| 693 | - let conn = database::connect(&db).await.unwrap(); | ||
| 694 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 695 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 696 | - user_community::join(&user.id, &community.id, Rank::Member, &conn) | ||
| 697 | - .await | ||
| 698 | - .unwrap(); | ||
| 699 | - | ||
| 700 | - let mut png = Cursor::new(Vec::new()); | ||
| 701 | - RgbImage::new(2, 3) | ||
| 702 | - .write_to(&mut png, ImageFormat::Png) | ||
| 703 | - .unwrap(); | ||
| 704 | - let png = png.into_inner(); | ||
| 705 | - let directory = test::directory(); | ||
| 706 | - let header = Upload { | ||
| 707 | - community_id: community.id.clone(), | ||
| 708 | - name: "pixel.png".to_string(), | ||
| 709 | - size: png.len() as u64, | ||
| 710 | - }; | ||
| 711 | - let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) | ||
| 712 | - .await | ||
| 713 | - .unwrap(); | ||
| 714 | - | ||
| 715 | - let client = Client::detached(Some(Signed { | ||
| 716 | - user_id: user.id.clone(), | ||
| 717 | - token: "token".to_string(), | ||
| 718 | - })); | ||
| 719 | - let shared = Shared { | ||
| 720 | - db: db.clone(), | ||
| 721 | - services: Services::default(), | ||
| 722 | - directory: test::directory(), | ||
| 723 | - backups: test::directory(), | ||
| 724 | - }; | ||
| 725 | - let mut cx = Cx::new(&client, &shared, database::connect(&db).await.unwrap()); | ||
| 726 | - CreateMessage { | ||
| 727 | - community_id: community.id.clone(), | ||
| 728 | - body: String::new(), | ||
| 729 | - attachments: vec![attachment.id.clone()], | ||
| 730 | - reply_to: None, | ||
| 731 | - } | ||
| 732 | - .handle(Me::User(user), &mut cx) | ||
| 733 | - .await | ||
| 734 | - .unwrap(); | ||
| 735 | - | ||
| 736 | - let messages = message::read_page(&community.id, None, &conn) | ||
| 737 | - .await | ||
| 738 | - .unwrap(); | ||
| 739 | - assert_eq!(vec![attachment.clone()], messages[0].attachments); | ||
| 740 | - assert_eq!(AttachmentKind::Image, attachment.kind); | ||
| 741 | - assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); | ||
| 742 | - | ||
| 743 | - std::fs::remove_file(directory.join(&attachment.id)).unwrap(); | ||
| 744 | - std::fs::remove_file(thumb_path(&directory, &attachment.id)).unwrap(); | ||
| 745 | - } | ||
| 746 | -} | ||
crates/server/src/authentication.rsmodified+172 -171
| @@ -1,15 +1,19 @@ | |||
| 1 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; | 1 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; |
| 2 | use common::{ | 2 | use common::{ |
| 3 | + call::{Call, Login, Register, Session}, | ||
| 3 | error::Error as CommonError, | 4 | error::Error as CommonError, |
| 4 | - model::{SessionInfo, User}, | 5 | + model::{Id, Role, ServerSettings, User}, |
| 5 | - permission, time, | 6 | + permission, |
| 6 | transport::Close, | 7 | transport::Close, |
| 7 | - validate::{validate_device, validate_password, validate_username}, | ||
| 8 | }; | 8 | }; |
| 9 | -use turso::Connection; | 9 | +use sha2::{Digest, Sha256}; |
| 10 | 10 | ||
| 11 | use crate::{ | 11 | use crate::{ |
| 12 | - database::new_id, error::ServerError, hub::Hub, invite, server_ban, server_settings, user, | 12 | + db::{self, Connection}, |
| 13 | + error::{ServerError, ensure_with}, | ||
| 14 | + hub::{Client, Hub}, | ||
| 15 | + network::Shared, | ||
| 16 | + request::limit_logins, | ||
| 13 | }; | 17 | }; |
| 14 | 18 | ||
| 15 | const SALT_LENGTH: usize = 16; | 19 | const SALT_LENGTH: usize = 16; |
| @@ -23,6 +27,10 @@ pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N], ServerError> { | |||
| 23 | Ok(bytes) | 27 | Ok(bytes) |
| 24 | } | 28 | } |
| 25 | 29 | ||
| 30 | +pub fn token_hash(token: &str) -> Vec<u8> { | ||
| 31 | + Sha256::digest(token.as_bytes()).to_vec() | ||
| 32 | +} | ||
| 33 | + | ||
| 26 | fn hash(password: &str) -> Result<String, ServerError> { | 34 | fn hash(password: &str) -> Result<String, ServerError> { |
| 27 | let salt = random_bytes::<SALT_LENGTH>()?; | 35 | let salt = random_bytes::<SALT_LENGTH>()?; |
| 28 | let hash = Argon2::default() | 36 | let hash = Argon2::default() |
| @@ -38,209 +46,166 @@ fn verify(password: &str, password_hash: &str) -> Result<(), ServerError> { | |||
| 38 | .map_err(|_| ServerError::from(CommonError::WrongCredentials)) | 46 | .map_err(|_| ServerError::from(CommonError::WrongCredentials)) |
| 39 | } | 47 | } |
| 40 | 48 | ||
| 41 | -async fn open_session(user_id: &str, conn: &Connection) -> Result<String, ServerError> { | 49 | +async fn hash_blocking(password: String) -> Result<String, ServerError> { |
| 50 | + tokio::task::spawn_blocking(move || hash(&password)).await? | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +async fn verify_blocking(password: String, password_hash: String) -> Result<(), ServerError> { | ||
| 54 | + tokio::task::spawn_blocking(move || verify(&password, &password_hash)).await? | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +async fn open_session(user_id: Id, db: &Connection) -> Result<String, ServerError> { | ||
| 42 | let token: String = random_bytes::<TOKEN_LENGTH>()? | 58 | let token: String = random_bytes::<TOKEN_LENGTH>()? |
| 43 | .iter() | 59 | .iter() |
| 44 | .map(|byte| format!("{byte:02x}")) | 60 | .map(|byte| format!("{byte:02x}")) |
| 45 | .collect(); | 61 | .collect(); |
| 46 | - | 62 | + let session_id = db::session::insert(&token_hash(&token), user_id, db).await?; |
| 47 | - conn.execute( | 63 | + db::session::seen(session_id, db).await?; |
| 48 | - "INSERT INTO session (token, user_id, id) VALUES (?1, ?2, ?3)", | ||
| 49 | - (token.as_str(), user_id, new_id()), | ||
| 50 | - ) | ||
| 51 | - .await?; | ||
| 52 | - seen(user_id, &token, conn).await?; | ||
| 53 | 64 | ||
| 54 | Ok(token) | 65 | Ok(token) |
| 55 | } | 66 | } |
| 56 | 67 | ||
| 57 | -pub async fn seen(user_id: &str, token: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 58 | - if user::is_ghost(user_id, conn).await? { | ||
| 59 | - return Ok(()); | ||
| 60 | - } | ||
| 61 | - let now = time::now_ms() as i64; | ||
| 62 | - conn.execute( | ||
| 63 | - "UPDATE user SET last_seen = ?2 WHERE id = ?1", | ||
| 64 | - (user_id, now), | ||
| 65 | - ) | ||
| 66 | - .await?; | ||
| 67 | - conn.execute( | ||
| 68 | - "UPDATE session SET last_seen = ?2 WHERE token = ?1", | ||
| 69 | - (token, now), | ||
| 70 | - ) | ||
| 71 | - .await?; | ||
| 72 | - | ||
| 73 | - Ok(()) | ||
| 74 | -} | ||
| 75 | - | ||
| 76 | -pub async fn set_device(token: &str, name: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 77 | - validate_device(name)?; | ||
| 78 | - conn.execute( | ||
| 79 | - "UPDATE session SET device = ?2 WHERE token = ?1", | ||
| 80 | - (token, name), | ||
| 81 | - ) | ||
| 82 | - .await?; | ||
| 83 | - | ||
| 84 | - Ok(()) | ||
| 85 | -} | ||
| 86 | - | ||
| 87 | -pub async fn sessions(user_id: &str, conn: &Connection) -> Result<Vec<SessionInfo>, ServerError> { | ||
| 88 | - let mut rows = conn | ||
| 89 | - .query( | ||
| 90 | - "SELECT id, device, last_seen FROM session WHERE user_id = ?1 ORDER BY last_seen DESC", | ||
| 91 | - (user_id,), | ||
| 92 | - ) | ||
| 93 | - .await?; | ||
| 94 | - let mut sessions = Vec::new(); | ||
| 95 | - while let Some(row) = rows.next().await? { | ||
| 96 | - let last_seen: Option<i64> = row.get(2)?; | ||
| 97 | - sessions.push(SessionInfo { | ||
| 98 | - id: row.get(0)?, | ||
| 99 | - device: row.get(1)?, | ||
| 100 | - last_seen: last_seen.map(|millis| millis as u64), | ||
| 101 | - }); | ||
| 102 | - } | ||
| 103 | - | ||
| 104 | - Ok(sessions) | ||
| 105 | -} | ||
| 106 | - | ||
| 107 | -async fn revoke_session( | ||
| 108 | - user_id: &str, | ||
| 109 | - session_id: &str, | ||
| 110 | - conn: &Connection, | ||
| 111 | -) -> Result<String, ServerError> { | ||
| 112 | - let mut rows = conn | ||
| 113 | - .query( | ||
| 114 | - "DELETE FROM session WHERE id = ?1 AND user_id = ?2 RETURNING token", | ||
| 115 | - (session_id, user_id), | ||
| 116 | - ) | ||
| 117 | - .await?; | ||
| 118 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 119 | - | ||
| 120 | - Ok(row.get(0)?) | ||
| 121 | -} | ||
| 122 | - | ||
| 123 | pub async fn create_account( | 68 | pub async fn create_account( |
| 124 | username: &str, | 69 | username: &str, |
| 125 | password: &str, | 70 | password: &str, |
| 126 | - conn: &Connection, | 71 | + db: &Connection, |
| 127 | ) -> Result<User, ServerError> { | 72 | ) -> Result<User, ServerError> { |
| 128 | - validate_username(username)?; | 73 | + db::user::create(username, &hash(password)?, Role::User, db).await |
| 129 | - validate_password(password)?; | ||
| 130 | - | ||
| 131 | - if user::is_taken(username, None, conn).await? { | ||
| 132 | - return Err(CommonError::Taken.into()); | ||
| 133 | - } | ||
| 134 | - | ||
| 135 | - user::create(username, &hash(password)?, conn).await | ||
| 136 | } | 74 | } |
| 137 | 75 | ||
| 138 | -pub async fn register( | 76 | +pub(crate) async fn register( |
| 139 | - username: &str, | 77 | + call: Register, |
| 140 | - password: &str, | 78 | + client: &Client, |
| 141 | - invite_code: Option<&str>, | 79 | + shared: &Shared, |
| 142 | - conn: &mut Connection, | 80 | +) -> Result<Session, ServerError> { |
| 143 | -) -> Result<(User, String), ServerError> { | 81 | + call.validate()?; |
| 144 | - let tx = conn.transaction().await?; | 82 | + shared |
| 145 | - if server_ban::username_banned(username, &tx).await? { | 83 | + .db |
| 146 | - return Err(CommonError::Banned.into()); | 84 | + .run(async |db| limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await) |
| 147 | - } | 85 | + .await?; |
| 148 | - if !server_settings::read(&tx).await?.registration_open && user::any(&tx).await? { | 86 | + let password_hash = hash_blocking(call.password.clone()).await?; |
| 149 | - invite::consume(invite_code.ok_or(CommonError::RegistrationClosed)?, &tx).await?; | 87 | + |
| 150 | - } | 88 | + shared |
| 151 | - let user = create_account(username, password, &tx).await?; | 89 | + .db |
| 152 | - admit(&user, &tx).await?; | 90 | + .run(async |db| { |
| 153 | - let token = open_session(&user.id, &tx).await?; | 91 | + if db::server_ban::username_banned(&call.username, db).await? { |
| 154 | - tx.commit().await?; | 92 | + return Err(CommonError::Banned.into()); |
| 155 | - | 93 | + } |
| 156 | - Ok((user, token)) | 94 | + let settings = db::settings::read(db).await?; |
| 95 | + let first = !db::user::any(db).await?; | ||
| 96 | + if !settings.registration_open && !first { | ||
| 97 | + let code = call | ||
| 98 | + .invite | ||
| 99 | + .as_deref() | ||
| 100 | + .ok_or(CommonError::RegistrationClosed)?; | ||
| 101 | + db::registration_code::consume(code, db).await?; | ||
| 102 | + } | ||
| 103 | + let role = if first { Role::Builder } else { Role::User }; | ||
| 104 | + let user = db::user::create(&call.username, &password_hash, role, db).await?; | ||
| 105 | + admit(&user, &settings, db).await?; | ||
| 106 | + let token = open_session(user.id, db).await?; | ||
| 107 | + | ||
| 108 | + Ok(Session { user, token }) | ||
| 109 | + }) | ||
| 110 | + .await | ||
| 157 | } | 111 | } |
| 158 | 112 | ||
| 159 | -pub async fn login( | 113 | +pub(crate) async fn login( |
| 160 | - username: &str, | 114 | + call: Login, |
| 161 | - password: &str, | 115 | + client: &Client, |
| 162 | - conn: &Connection, | 116 | + shared: &Shared, |
| 163 | -) -> Result<(User, String), ServerError> { | 117 | +) -> Result<Session, ServerError> { |
| 164 | - let (user, password_hash) = user::credentials(username, conn) | 118 | + call.validate()?; |
| 165 | - .await? | 119 | + let (user, password_hash) = shared |
| 166 | - .ok_or(CommonError::WrongCredentials)?; | 120 | + .db |
| 167 | - verify(password, &password_hash)?; | 121 | + .run(async |db| { |
| 168 | - admit(&user, conn).await?; | 122 | + limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await?; |
| 169 | - let token = open_session(&user.id, conn).await?; | 123 | + db::user::password_hash_of(&call.username, db) |
| 170 | - | 124 | + .await? |
| 171 | - Ok((user, token)) | 125 | + .ok_or(CommonError::WrongCredentials.into()) |
| 126 | + }) | ||
| 127 | + .await?; | ||
| 128 | + verify_blocking(call.password, password_hash).await?; | ||
| 129 | + | ||
| 130 | + shared | ||
| 131 | + .db | ||
| 132 | + .run(async |db| { | ||
| 133 | + let settings = db::settings::read(db).await?; | ||
| 134 | + admit(&user, &settings, db).await?; | ||
| 135 | + let token = open_session(user.id, db).await?; | ||
| 136 | + | ||
| 137 | + Ok(Session { user, token }) | ||
| 138 | + }) | ||
| 139 | + .await | ||
| 172 | } | 140 | } |
| 173 | 141 | ||
| 174 | -async fn admit(user: &User, conn: &Connection) -> Result<(), ServerError> { | 142 | +async fn admit(user: &User, settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> { |
| 175 | - if server_ban::username_banned(&user.username, conn).await? { | 143 | + if db::server_ban::username_banned(&user.username, db).await? { |
| 176 | return Err(CommonError::Banned.into()); | 144 | return Err(CommonError::Banned.into()); |
| 177 | } | 145 | } |
| 178 | - if let Some(until_ms) = user::suspended(&user.id, conn).await? { | 146 | + if let Some(until_ms) = db::user::suspended(user.id, db).await? { |
| 179 | return Err(CommonError::Suspended { until_ms }.into()); | 147 | return Err(CommonError::Suspended { until_ms }.into()); |
| 180 | } | 148 | } |
| 181 | - if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance { | 149 | + if !permission::is_builder(user.role) && settings.maintenance { |
| 182 | return Err(CommonError::Maintenance.into()); | 150 | return Err(CommonError::Maintenance.into()); |
| 183 | } | 151 | } |
| 184 | 152 | ||
| 185 | Ok(()) | 153 | Ok(()) |
| 186 | } | 154 | } |
| 187 | 155 | ||
| 188 | -pub async fn resume(token: &str, conn: &Connection) -> Result<User, ServerError> { | 156 | +pub async fn resume(token: &str, db: &Connection) -> Result<(Id, User), ServerError> { |
| 189 | - let user = match user::by_session_token(token, conn).await { | 157 | + let (session_id, user) = db::session::find(&token_hash(token), db) |
| 190 | - Err(ServerError::Wire(CommonError::WrongCredentials)) => { | 158 | + .await? |
| 191 | - return Err(CommonError::Unauthenticated.into()); | 159 | + .ok_or(CommonError::Unauthenticated)?; |
| 192 | - } | 160 | + admit(&user, &db::settings::read(db).await?, db).await?; |
| 193 | - user => user?, | 161 | + db::session::seen(session_id, db).await?; |
| 194 | - }; | ||
| 195 | - admit(&user, conn).await?; | ||
| 196 | - seen(&user.id, token, conn).await?; | ||
| 197 | 162 | ||
| 198 | - Ok(user) | 163 | + Ok((session_id, user)) |
| 199 | } | 164 | } |
| 200 | 165 | ||
| 201 | -pub async fn logout(token: &str, conn: &Connection) -> Result<(), ServerError> { | 166 | +pub async fn recheck(session_id: Id, db: &Connection) -> Result<User, ServerError> { |
| 202 | - conn.execute("DELETE FROM session WHERE token = ?1", (token,)) | 167 | + let user = db::session::user_of(session_id, db) |
| 203 | - .await?; | 168 | + .await? |
| 169 | + .ok_or(CommonError::Unauthenticated)?; | ||
| 170 | + admit(&user, &db::settings::read(db).await?, db).await?; | ||
| 204 | 171 | ||
| 205 | - Ok(()) | 172 | + Ok(user) |
| 206 | } | 173 | } |
| 207 | 174 | ||
| 208 | -pub(crate) async fn revoke_sessions(user_id: &str, conn: &Connection) -> Result<(), ServerError> { | 175 | +pub async fn logout(session_id: Id, db: &Connection) -> Result<(), ServerError> { |
| 209 | - conn.execute("DELETE FROM session WHERE user_id = ?1", (user_id,)) | 176 | + db::session::delete(session_id, db).await |
| 210 | - .await?; | 177 | +} |
| 211 | 178 | ||
| 212 | - Ok(()) | 179 | +pub(crate) async fn revoke_sessions(user_id: Id, db: &Connection) -> Result<(), ServerError> { |
| 180 | + db::session::delete_all(user_id, db).await | ||
| 213 | } | 181 | } |
| 214 | 182 | ||
| 215 | pub async fn reset_password( | 183 | pub async fn reset_password( |
| 216 | - user_id: &str, | 184 | + user_id: Id, |
| 217 | password: &str, | 185 | password: &str, |
| 218 | - conn: &Connection, | 186 | + db: &Connection, |
| 219 | ) -> Result<(), ServerError> { | 187 | ) -> Result<(), ServerError> { |
| 220 | - validate_password(password)?; | 188 | + db::user::set_password_hash(user_id, &hash(password)?, db).await |
| 221 | - user::set_password_hash(user_id, &hash(password)?, conn).await | ||
| 222 | } | 189 | } |
| 223 | 190 | ||
| 224 | -pub enum Revoke<'a> { | 191 | +pub enum Revoke { |
| 225 | - User(&'a str), | 192 | + User(Id), |
| 226 | - Session { | 193 | + Session { user_id: Id, session_id: Id }, |
| 227 | - user_id: &'a str, | ||
| 228 | - session_id: &'a str, | ||
| 229 | - }, | ||
| 230 | } | 194 | } |
| 231 | 195 | ||
| 232 | -pub async fn revoke(hub: &Hub, target: Revoke<'_>, conn: &Connection) -> Result<(), ServerError> { | 196 | +pub async fn revoke(hub: &Hub, target: Revoke, db: &Connection) -> Result<(), ServerError> { |
| 233 | match target { | 197 | match target { |
| 234 | Revoke::User(user_id) => { | 198 | Revoke::User(user_id) => { |
| 235 | - revoke_sessions(user_id, conn).await?; | 199 | + revoke_sessions(user_id, db).await?; |
| 236 | hub.kick_user(user_id, Close::Revoked); | 200 | hub.kick_user(user_id, Close::Revoked); |
| 237 | } | 201 | } |
| 238 | Revoke::Session { | 202 | Revoke::Session { |
| 239 | user_id, | 203 | user_id, |
| 240 | session_id, | 204 | session_id, |
| 241 | } => { | 205 | } => { |
| 242 | - let token = revoke_session(user_id, session_id, conn).await?; | 206 | + let deleted = db::session::delete_of(user_id, session_id, db).await?; |
| 243 | - hub.kick_token(&token, Close::Revoked); | 207 | + ensure_with(deleted == 1, CommonError::NotFound)?; |
| 208 | + hub.kick_session(session_id, Close::Revoked); | ||
| 244 | } | 209 | } |
| 245 | } | 210 | } |
| 246 | 211 | ||
| @@ -249,25 +214,61 @@ pub async fn revoke(hub: &Hub, target: Revoke<'_>, conn: &Connection) -> Result< | |||
| 249 | 214 | ||
| 250 | #[cfg(test)] | 215 | #[cfg(test)] |
| 251 | mod tests { | 216 | mod tests { |
| 252 | - use common::error::Error as CommonError; | 217 | + use common::{ |
| 218 | + call::{Login, Register}, | ||
| 219 | + error::Error as CommonError, | ||
| 220 | + }; | ||
| 253 | 221 | ||
| 254 | - use crate::{authentication, database, error::ServerError, test}; | 222 | + use crate::{ |
| 223 | + authentication, | ||
| 224 | + error::ServerError, | ||
| 225 | + hub::Client, | ||
| 226 | + network::{Services, Shared}, | ||
| 227 | + test, | ||
| 228 | + }; | ||
| 255 | 229 | ||
| 256 | #[tokio::test] | 230 | #[tokio::test] |
| 257 | async fn register_and_login() { | 231 | async fn register_and_login() { |
| 258 | - let db = test::get_database().await; | 232 | + let shared = Shared { |
| 259 | - let mut conn = database::connect(&db).await.unwrap(); | 233 | + db: test::db().await, |
| 260 | - | 234 | + services: Services::default(), |
| 261 | - let (registered_user, _) = | 235 | + directory: test::directory(), |
| 262 | - authentication::register("Tahinli", "correct horse", None, &mut conn) | 236 | + backups: test::directory(), |
| 263 | - .await | 237 | + }; |
| 264 | - .unwrap(); | 238 | + let client = Client::detached(None); |
| 265 | - let (logged_in_user, _) = authentication::login("Tahinli", "correct horse", &conn) | 239 | + |
| 266 | - .await | 240 | + let registered = authentication::register( |
| 267 | - .unwrap(); | 241 | + Register { |
| 268 | - let wrong_password = authentication::login("Tahinli", "wrong password", &conn).await; | 242 | + username: "Tahinli".to_string(), |
| 269 | - | 243 | + password: "correct horse".to_string(), |
| 270 | - assert_eq!(registered_user, logged_in_user); | 244 | + invite: None, |
| 245 | + }, | ||
| 246 | + &client, | ||
| 247 | + &shared, | ||
| 248 | + ) | ||
| 249 | + .await | ||
| 250 | + .unwrap(); | ||
| 251 | + let logged_in = authentication::login( | ||
| 252 | + Login { | ||
| 253 | + username: "tahinli".to_string(), | ||
| 254 | + password: "correct horse".to_string(), | ||
| 255 | + }, | ||
| 256 | + &client, | ||
| 257 | + &shared, | ||
| 258 | + ) | ||
| 259 | + .await | ||
| 260 | + .unwrap(); | ||
| 261 | + let wrong_password = authentication::login( | ||
| 262 | + Login { | ||
| 263 | + username: "Tahinli".to_string(), | ||
| 264 | + password: "wrong password".to_string(), | ||
| 265 | + }, | ||
| 266 | + &client, | ||
| 267 | + &shared, | ||
| 268 | + ) | ||
| 269 | + .await; | ||
| 270 | + | ||
| 271 | + assert_eq!(registered.user, logged_in.user); | ||
| 271 | assert!(matches!( | 272 | assert!(matches!( |
| 272 | wrong_password, | 273 | wrong_password, |
| 273 | Err(ServerError::Wire(CommonError::WrongCredentials)) | 274 | Err(ServerError::Wire(CommonError::WrongCredentials)) |
crates/server/src/backup.rsmodified+27 -35
| @@ -6,14 +6,10 @@ use common::{ | |||
| 6 | permission, time, | 6 | permission, time, |
| 7 | validate::validate_backup_name, | 7 | validate::validate_backup_name, |
| 8 | }; | 8 | }; |
| 9 | -use turso::Connection; | ||
| 10 | 9 | ||
| 11 | use crate::{ | 10 | use crate::{ |
| 12 | - admin_log, | 11 | + db::{self, Db}, |
| 13 | - database::{self, DB}, | 12 | + error::{ServerError, ensure}, |
| 14 | - error::ServerError, | ||
| 15 | - request::ensure, | ||
| 16 | - user, | ||
| 17 | }; | 13 | }; |
| 18 | 14 | ||
| 19 | const PREFIX: &str = "yumush-"; | 15 | const PREFIX: &str = "yumush-"; |
| @@ -44,14 +40,9 @@ fn path_of(directory: &Path, name: &str) -> Result<PathBuf, ServerError> { | |||
| 44 | Ok(directory.join(name)) | 40 | Ok(directory.join(name)) |
| 45 | } | 41 | } |
| 46 | 42 | ||
| 47 | -pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, ServerError> { | 43 | +pub async fn create(db: &Db, directory: &Path) -> Result<BackupInfo, ServerError> { |
| 48 | let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); | 44 | let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); |
| 49 | - let path = directory.join(&name); | 45 | + db.backup(&directory.join(&name).to_string_lossy()).await?; |
| 50 | - let statement = format!( | ||
| 51 | - "VACUUM INTO '{}'", | ||
| 52 | - path.to_string_lossy().replace('\'', "''") | ||
| 53 | - ); | ||
| 54 | - conn.execute(&statement, ()).await?; | ||
| 55 | 46 | ||
| 56 | info(directory, &name) | 47 | info(directory, &name) |
| 57 | } | 48 | } |
| @@ -78,29 +69,30 @@ pub fn delete(name: &str, directory: &Path) -> Result<(), ServerError> { | |||
| 78 | pub async fn locate( | 69 | pub async fn locate( |
| 79 | user: Option<&User>, | 70 | user: Option<&User>, |
| 80 | name: &str, | 71 | name: &str, |
| 81 | - db: &DB, | 72 | + db: &Db, |
| 82 | directory: &Path, | 73 | directory: &Path, |
| 83 | ) -> Result<(PathBuf, u64), ServerError> { | 74 | ) -> Result<(PathBuf, u64), ServerError> { |
| 84 | let user = user.ok_or(CommonError::Unauthenticated)?; | 75 | let user = user.ok_or(CommonError::Unauthenticated)?; |
| 85 | - let conn = database::connect(db).await?; | 76 | + db.run(async |db| { |
| 86 | - let me = user::read(&user.id, &conn).await?; | 77 | + let me = db::user::read(user.id, db).await?; |
| 87 | - ensure(permission::is_builder(me.role))?; | 78 | + ensure(permission::is_builder(me.role))?; |
| 88 | - | 79 | + let path = path_of(directory, name)?; |
| 89 | - let path = path_of(directory, name)?; | 80 | + let length = tokio::fs::metadata(&path) |
| 90 | - let length = tokio::fs::metadata(&path) | 81 | + .await |
| 91 | - .await | 82 | + .map_err(|_| CommonError::NotFound)? |
| 92 | - .map_err(|_| CommonError::NotFound)? | 83 | + .len(); |
| 93 | - .len(); | 84 | + db::log::record_admin( |
| 94 | - admin_log::record( | 85 | + Some(me.id), |
| 95 | - Some(&me.id), | 86 | + None, |
| 96 | - None, | 87 | + None, |
| 97 | - None, | 88 | + &AdminAction::BackupDownloaded { |
| 98 | - &AdminAction::BackupDownloaded { | 89 | + name: name.to_string(), |
| 99 | - name: name.to_string(), | 90 | + }, |
| 100 | - }, | 91 | + db, |
| 101 | - &conn, | 92 | + ) |
| 102 | - ) | 93 | + .await?; |
| 103 | - .await?; | 94 | + |
| 104 | - | 95 | + Ok((path, length)) |
| 105 | - Ok((path, length)) | 96 | + }) |
| 97 | + .await | ||
| 106 | } | 98 | } |
crates/server/src/call/admin.rsmodified+218 -285
| @@ -1,14 +1,12 @@ | |||
| 1 | -use std::collections::BTreeMap; | ||
| 2 | - | ||
| 3 | use common::{ | 1 | use common::{ |
| 4 | call::{ | 2 | call::{ |
| 5 | BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment, | 3 | BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment, |
| 6 | DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage, | 4 | DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage, |
| 7 | ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes, | 5 | ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes, |
| 8 | - ListServerBans, ListUsers, Login, Logout, PurgeUser, Register, RemoveServerBan, RenameUser, | 6 | + ListServerBans, ListUsers, Logout, PurgeUser, RemoveServerBan, RenameUser, ResetPassword, |
| 9 | - ResetPassword, RevokeSessions, SearchCommunity, SearchMessages, Session, SetCommunityVoice, | 7 | + RevokeSessions, SearchCommunity, SearchMessages, SetCommunityVoice, SetGhost, SetRole, |
| 10 | - SetGhost, SetRole, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, | 8 | + StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, UpdateServerSettings, |
| 11 | - UpdateServerSettings, WatchCommunity, | 9 | + WatchCommunity, |
| 12 | }, | 10 | }, |
| 13 | error::Error, | 11 | error::Error, |
| 14 | event::Event, | 12 | event::Event, |
| @@ -23,52 +21,40 @@ use common::{ | |||
| 23 | }; | 21 | }; |
| 24 | 22 | ||
| 25 | use crate::{ | 23 | use crate::{ |
| 26 | - admin_log, attachment, | ||
| 27 | authentication::{self, Revoke}, | 24 | authentication::{self, Revoke}, |
| 28 | backup, | 25 | backup, |
| 29 | call::user::user_updated, | 26 | call::user::user_updated, |
| 30 | call::{Cx, Handle, Me}, | 27 | call::{Cx, Handle, Me}, |
| 31 | - community, | 28 | + db::{ |
| 32 | - error::ServerError, | 29 | + attachment, avatar, community, log, member, message, registration_code, server_ban, |
| 33 | - invite, log, message, overview, | 30 | + session, settings, stats, user, |
| 31 | + }, | ||
| 32 | + error::{ServerError, ensure}, | ||
| 34 | publish::{Broadcast, To}, | 33 | publish::{Broadcast, To}, |
| 35 | request::{ | 34 | request::{ |
| 36 | - allowed, call_ended, ensure, ensure_editable, is_outsider, leave_room_voice, | 35 | + allowed, call_ended, delete_community, ensure_editable, is_outsider, leave_room_voice, |
| 37 | - leave_user_voice, limit_logins, managed, message_event, record_ghost_voice, shares_ended, | 36 | + leave_user_voice, managed, message_event, messages_deleted, record_ghost_voice, |
| 38 | - voice_closed, voice_joined, voice_muted, | 37 | + shares_ended, voice_joined, voice_muted, |
| 39 | }, | 38 | }, |
| 40 | - server_ban, server_settings, stats, user, user_community, | ||
| 41 | }; | 39 | }; |
| 42 | 40 | ||
| 43 | -impl Handle for Register { | 41 | +const CODE_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| 44 | - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Session, ServerError> { | 42 | +const CODE_LENGTH: usize = 8; |
| 45 | - limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?; | ||
| 46 | - let (user, token) = authentication::register( | ||
| 47 | - &self.username, | ||
| 48 | - &self.password, | ||
| 49 | - self.invite.as_deref(), | ||
| 50 | - &mut cx.db, | ||
| 51 | - ) | ||
| 52 | - .await?; | ||
| 53 | - | ||
| 54 | - Ok(Session { user, token }) | ||
| 55 | - } | ||
| 56 | -} | ||
| 57 | 43 | ||
| 58 | -impl Handle for Login { | 44 | +fn generate_code() -> Result<String, ServerError> { |
| 59 | - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Session, ServerError> { | 45 | + let bytes = authentication::random_bytes::<CODE_LENGTH>()?; |
| 60 | - limit_logins(&cx.sh.services.rate_limit, cx.client.conn.as_ref(), &cx.db).await?; | ||
| 61 | - let (user, token) = authentication::login(&self.username, &self.password, &cx.db).await?; | ||
| 62 | 46 | ||
| 63 | - Ok(Session { user, token }) | 47 | + Ok(bytes |
| 64 | - } | 48 | + .iter() |
| 49 | + .map(|byte| char::from(CODE_ALPHABET[usize::from(*byte) % CODE_ALPHABET.len()])) | ||
| 50 | + .collect()) | ||
| 65 | } | 51 | } |
| 66 | 52 | ||
| 67 | impl Handle for Logout { | 53 | impl Handle for Logout { |
| 68 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 54 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 69 | me.user()?; | 55 | me.user()?; |
| 70 | let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?; | 56 | let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?; |
| 71 | - authentication::logout(&signed.token, &cx.db).await?; | 57 | + authentication::logout(signed.session_id, cx.db).await?; |
| 72 | 58 | ||
| 73 | Ok(()) | 59 | Ok(()) |
| 74 | } | 60 | } |
| @@ -78,17 +64,17 @@ impl Handle for UpdateServerSettings { | |||
| 78 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> { | 64 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> { |
| 79 | let me = me.user()?; | 65 | let me = me.user()?; |
| 80 | let settings = self.settings; | 66 | let settings = self.settings; |
| 81 | - server_settings::update(&settings, &cx.db).await?; | 67 | + settings::update(&settings, cx.db).await?; |
| 82 | - admin_log::record( | 68 | + log::record_admin( |
| 83 | - Some(&me.id), | 69 | + Some(me.id), |
| 84 | None, | 70 | None, |
| 85 | None, | 71 | None, |
| 86 | &AdminAction::SettingsChanged, | 72 | &AdminAction::SettingsChanged, |
| 87 | - &cx.db, | 73 | + cx.db, |
| 88 | ) | 74 | ) |
| 89 | .await?; | 75 | .await?; |
| 90 | if settings.maintenance { | 76 | if settings.maintenance { |
| 91 | - let builders = user::builder_ids(&cx.db).await?; | 77 | + let builders = user::builder_ids(cx.db).await?; |
| 92 | cx.sh | 78 | cx.sh |
| 93 | .services | 79 | .services |
| 94 | .hub | 80 | .hub |
| @@ -103,16 +89,16 @@ impl Handle for UpdateServerSettings { | |||
| 103 | impl Handle for RenameUser { | 89 | impl Handle for RenameUser { |
| 104 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 90 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 105 | let me = me.user()?; | 91 | let me = me.user()?; |
| 106 | - let target = managed(&me, &self.user_id, &cx.db).await?; | 92 | + let target = managed(&me, self.user_id, cx.db).await?; |
| 107 | - let user = user::update(&self.user_id, &self.username, &cx.db).await?; | 93 | + let user = user::update(self.user_id, &self.username, cx.db).await?; |
| 108 | - admin_log::record( | 94 | + log::record_admin( |
| 109 | - Some(&me.id), | 95 | + Some(me.id), |
| 110 | - Some(&self.user_id), | 96 | + Some(self.user_id), |
| 111 | None, | 97 | None, |
| 112 | &AdminAction::UserRenamed { | 98 | &AdminAction::UserRenamed { |
| 113 | from: target.username, | 99 | from: target.username, |
| 114 | }, | 100 | }, |
| 115 | - &cx.db, | 101 | + cx.db, |
| 116 | ) | 102 | ) |
| 117 | .await?; | 103 | .await?; |
| 118 | user_updated(&user, cx); | 104 | user_updated(&user, cx); |
| @@ -124,13 +110,13 @@ impl Handle for RenameUser { | |||
| 124 | impl Handle for CreateUser { | 110 | impl Handle for CreateUser { |
| 125 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 111 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 126 | let me = me.user()?; | 112 | let me = me.user()?; |
| 127 | - let user = authentication::create_account(&self.username, &self.password, &cx.db).await?; | 113 | + let user = authentication::create_account(&self.username, &self.password, cx.db).await?; |
| 128 | - admin_log::record( | 114 | + log::record_admin( |
| 129 | - Some(&me.id), | 115 | + Some(me.id), |
| 130 | - Some(&user.id), | 116 | + Some(user.id), |
| 131 | None, | 117 | None, |
| 132 | &AdminAction::UserCreated, | 118 | &AdminAction::UserCreated, |
| 133 | - &cx.db, | 119 | + cx.db, |
| 134 | ) | 120 | ) |
| 135 | .await?; | 121 | .await?; |
| 136 | 122 | ||
| @@ -140,19 +126,19 @@ impl Handle for CreateUser { | |||
| 140 | 126 | ||
| 141 | impl Handle for ListUsers { | 127 | impl Handle for ListUsers { |
| 142 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<Account>, ServerError> { | 128 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<Account>, ServerError> { |
| 143 | - user::all(&cx.db).await | 129 | + user::all_accounts(cx.db).await |
| 144 | } | 130 | } |
| 145 | } | 131 | } |
| 146 | 132 | ||
| 147 | impl Handle for ListAdminLogs { | 133 | impl Handle for ListAdminLogs { |
| 148 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<AdminLogEntry>, ServerError> { | 134 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<AdminLogEntry>, ServerError> { |
| 149 | - admin_log::list( | 135 | + log::list_admin( |
| 150 | - self.actor_id.as_deref(), | 136 | + self.actor_id, |
| 151 | - self.target_id.as_deref(), | 137 | + self.target_id, |
| 152 | - self.action.as_deref(), | 138 | + self.action, |
| 153 | self.after_ms, | 139 | self.after_ms, |
| 154 | self.before_ms, | 140 | self.before_ms, |
| 155 | - &cx.db, | 141 | + cx.db, |
| 156 | ) | 142 | ) |
| 157 | .await | 143 | .await |
| 158 | } | 144 | } |
| @@ -160,30 +146,38 @@ impl Handle for ListAdminLogs { | |||
| 160 | 146 | ||
| 161 | impl Handle for GetDailyStats { | 147 | impl Handle for GetDailyStats { |
| 162 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<DayStat>, ServerError> { | 148 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<DayStat>, ServerError> { |
| 163 | - stats::daily(self.days, &cx.db).await | 149 | + stats::daily(self.days, cx.db).await |
| 164 | } | 150 | } |
| 165 | } | 151 | } |
| 166 | 152 | ||
| 167 | impl Handle for GetOverview { | 153 | impl Handle for GetOverview { |
| 168 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Overview, ServerError> { | 154 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Overview, ServerError> { |
| 169 | - overview::read(&cx.sh.services.hub, &cx.sh.services.rooms, &cx.db).await | 155 | + let (users, builders, communities, storage_bytes) = stats::counts(cx.db).await?; |
| 156 | + | ||
| 157 | + Ok(Overview { | ||
| 158 | + users, | ||
| 159 | + builders, | ||
| 160 | + communities, | ||
| 161 | + online: cx.sh.services.hub.online() as u64, | ||
| 162 | + voice: cx.sh.services.rooms.count() as u64, | ||
| 163 | + storage_bytes, | ||
| 164 | + }) | ||
| 170 | } | 165 | } |
| 171 | } | 166 | } |
| 172 | 167 | ||
| 173 | impl Handle for SuspendUser { | 168 | impl Handle for SuspendUser { |
| 174 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 169 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 175 | let me = me.user()?; | 170 | let me = me.user()?; |
| 176 | - managed(&me, &self.user_id, &cx.db).await?; | 171 | + managed(&me, self.user_id, cx.db).await?; |
| 177 | - user::set_suspended(&self.user_id, self.suspended, &cx.db).await?; | 172 | + user::set_suspended(self.user_id, self.suspended, cx.db).await?; |
| 178 | let action = if self.suspended { | 173 | let action = if self.suspended { |
| 179 | AdminAction::UserSuspended | 174 | AdminAction::UserSuspended |
| 180 | } else { | 175 | } else { |
| 181 | AdminAction::UserUnsuspended | 176 | AdminAction::UserUnsuspended |
| 182 | }; | 177 | }; |
| 183 | - admin_log::record(Some(&me.id), Some(&self.user_id), None, &action, &cx.db).await?; | 178 | + log::record_admin(Some(me.id), Some(self.user_id), None, &action, cx.db).await?; |
| 184 | if self.suspended { | 179 | if self.suspended { |
| 185 | - authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db) | 180 | + authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; |
| 186 | - .await?; | ||
| 187 | } | 181 | } |
| 188 | 182 | ||
| 189 | Ok(()) | 183 | Ok(()) |
| @@ -193,14 +187,14 @@ impl Handle for SuspendUser { | |||
| 193 | impl Handle for RevokeSessions { | 187 | impl Handle for RevokeSessions { |
| 194 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 188 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 195 | let me = me.user()?; | 189 | let me = me.user()?; |
| 196 | - managed(&me, &self.user_id, &cx.db).await?; | 190 | + managed(&me, self.user_id, cx.db).await?; |
| 197 | - authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?; | 191 | + authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; |
| 198 | - admin_log::record( | 192 | + log::record_admin( |
| 199 | - Some(&me.id), | 193 | + Some(me.id), |
| 200 | - Some(&self.user_id), | 194 | + Some(self.user_id), |
| 201 | None, | 195 | None, |
| 202 | &AdminAction::SessionsRevoked, | 196 | &AdminAction::SessionsRevoked, |
| 203 | - &cx.db, | 197 | + cx.db, |
| 204 | ) | 198 | ) |
| 205 | .await?; | 199 | .await?; |
| 206 | 200 | ||
| @@ -211,15 +205,15 @@ impl Handle for RevokeSessions { | |||
| 211 | impl Handle for ResetPassword { | 205 | impl Handle for ResetPassword { |
| 212 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 206 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 213 | let me = me.user()?; | 207 | let me = me.user()?; |
| 214 | - managed(&me, &self.user_id, &cx.db).await?; | 208 | + managed(&me, self.user_id, cx.db).await?; |
| 215 | - authentication::reset_password(&self.user_id, &self.password, &cx.db).await?; | 209 | + authentication::reset_password(self.user_id, &self.password, cx.db).await?; |
| 216 | - authentication::revoke(&cx.sh.services.hub, Revoke::User(&self.user_id), &cx.db).await?; | 210 | + authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; |
| 217 | - admin_log::record( | 211 | + log::record_admin( |
| 218 | - Some(&me.id), | 212 | + Some(me.id), |
| 219 | - Some(&self.user_id), | 213 | + Some(self.user_id), |
| 220 | None, | 214 | None, |
| 221 | &AdminAction::PasswordReset, | 215 | &AdminAction::PasswordReset, |
| 222 | - &cx.db, | 216 | + cx.db, |
| 223 | ) | 217 | ) |
| 224 | .await?; | 218 | .await?; |
| 225 | 219 | ||
| @@ -230,15 +224,15 @@ impl Handle for ResetPassword { | |||
| 230 | impl Handle for ClearProfile { | 224 | impl Handle for ClearProfile { |
| 231 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 225 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 232 | let me = me.user()?; | 226 | let me = me.user()?; |
| 233 | - managed(&me, &self.user_id, &cx.db).await?; | 227 | + managed(&me, self.user_id, cx.db).await?; |
| 234 | - user::set_avatar(&self.user_id, None, &mut cx.db).await?; | 228 | + avatar::set_user(self.user_id, None, cx.db).await?; |
| 235 | - let user = user::update_status(&self.user_id, "", &cx.db).await?; | 229 | + let user = user::update_status(self.user_id, "", cx.db).await?; |
| 236 | - admin_log::record( | 230 | + log::record_admin( |
| 237 | - Some(&me.id), | 231 | + Some(me.id), |
| 238 | - Some(&self.user_id), | 232 | + Some(self.user_id), |
| 239 | None, | 233 | None, |
| 240 | &AdminAction::ProfileCleared, | 234 | &AdminAction::ProfileCleared, |
| 241 | - &cx.db, | 235 | + cx.db, |
| 242 | ) | 236 | ) |
| 243 | .await?; | 237 | .await?; |
| 244 | user_updated(&user, cx); | 238 | user_updated(&user, cx); |
| @@ -252,24 +246,24 @@ impl Handle for SetRole { | |||
| 252 | let me = me.user()?; | 246 | let me = me.user()?; |
| 253 | let Self { user_id, role } = self; | 247 | let Self { user_id, role } = self; |
| 254 | ensure(permission::can_set_role(me.role, me.id == user_id))?; | 248 | ensure(permission::can_set_role(me.role, me.id == user_id))?; |
| 255 | - let user = user::set_role_by_id(&user_id, role, &cx.db).await?; | 249 | + let user = user::set_role_by_id(user_id, role, cx.db).await?; |
| 256 | - admin_log::record( | 250 | + log::record_admin( |
| 257 | - Some(&me.id), | 251 | + Some(me.id), |
| 258 | - Some(&user_id), | 252 | + Some(user_id), |
| 259 | None, | 253 | None, |
| 260 | &AdminAction::RoleChanged { role }, | 254 | &AdminAction::RoleChanged { role }, |
| 261 | - &cx.db, | 255 | + cx.db, |
| 262 | ) | 256 | ) |
| 263 | .await?; | 257 | .await?; |
| 264 | user_updated(&user, cx); | 258 | user_updated(&user, cx); |
| 265 | if permission::is_builder(role) { | 259 | if permission::is_builder(role) { |
| 266 | - if let Some(community_id) = cx.sh.services.rooms.set_muted(&user_id, false) { | 260 | + if let Some(community_id) = cx.sh.services.rooms.set_muted(user_id, false) { |
| 267 | cx.out | 261 | cx.out |
| 268 | - .push(voice_muted(Some(community_id), &user_id, false, &cx.db).await?); | 262 | + .push(voice_muted(Some(community_id), user_id, false, cx.db).await?); |
| 269 | } | 263 | } |
| 270 | } else { | 264 | } else { |
| 271 | - user::set_ghost(&user_id, false, &cx.db).await?; | 265 | + user::set_ghost(user_id, false, cx.db).await?; |
| 272 | - cx.sh.services.hub.kick_user(&user_id, Close::Revoked); | 266 | + cx.sh.services.hub.kick_user(user_id, Close::Revoked); |
| 273 | } | 267 | } |
| 274 | 268 | ||
| 275 | Ok(user) | 269 | Ok(user) |
| @@ -280,49 +274,42 @@ impl Handle for DeleteUser { | |||
| 280 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 274 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 281 | let me = me.user()?; | 275 | let me = me.user()?; |
| 282 | let user_id = self.user_id; | 276 | let user_id = self.user_id; |
| 283 | - let rooms = &cx.sh.services.rooms; | 277 | + let target = user::read(user_id, cx.db).await?; |
| 284 | - let target = user::read(&user_id, &cx.db).await?; | ||
| 285 | ensure(permission::can_delete_user( | 278 | ensure(permission::can_delete_user( |
| 286 | me.role, | 279 | me.role, |
| 287 | me.id == user_id, | 280 | me.id == user_id, |
| 288 | target.role, | 281 | target.role, |
| 289 | ))?; | 282 | ))?; |
| 290 | - let tx = cx.db.transaction().await?; | ||
| 291 | - let mut broadcasts = Vec::new(); | ||
| 292 | if permission::is_builder(me.role) && me.id != user_id { | 283 | if permission::is_builder(me.role) && me.id != user_id { |
| 293 | - admin_log::record( | 284 | + log::record_admin( |
| 294 | - Some(&me.id), | 285 | + Some(me.id), |
| 295 | - Some(&user_id), | 286 | + Some(user_id), |
| 296 | None, | 287 | None, |
| 297 | &AdminAction::UserDeleted, | 288 | &AdminAction::UserDeleted, |
| 298 | - &tx, | 289 | + cx.db, |
| 299 | ) | 290 | ) |
| 300 | .await?; | 291 | .await?; |
| 301 | } | 292 | } |
| 302 | - for community_id in user_community::owned(&user_id, &tx).await? { | 293 | + let departed = leave_user_voice(&cx.sh.services.rooms, user_id, cx.db).await?; |
| 303 | - let member_ids = user_community::member_ids(&community_id, &tx).await?; | 294 | + cx.out.extend(departed); |
| 304 | - broadcasts.extend(voice_closed(rooms, &community_id, &tx).await?); | 295 | + for community_id in member::owned(user_id, cx.db).await? { |
| 305 | - community::delete(&community_id, &user_id, &tx).await?; | 296 | + let member_ids = member::member_ids(community_id, cx.db).await?; |
| 297 | + delete_community(community_id, cx).await?; | ||
| 306 | let event = Event::CommunityDeleted { community_id }; | 298 | let event = Event::CommunityDeleted { community_id }; |
| 307 | - broadcasts.push(Broadcast::new(To::Users(member_ids), event)); | 299 | + cx.out.push(Broadcast::new(To::Users(member_ids), event)); |
| 308 | } | 300 | } |
| 309 | - for community in community::communities_of(&user_id, &tx).await? { | 301 | + for community in community::communities_of(user_id, cx.db).await? { |
| 310 | - let member_ids = user_community::member_ids(&community.id, &tx).await?; | 302 | + let member_ids = member::member_ids(community.id, cx.db).await?; |
| 311 | if community.kind.is_direct() { | 303 | if community.kind.is_direct() { |
| 312 | - community::delete(&community.id, &user_id, &tx).await?; | 304 | + delete_community(community.id, cx).await?; |
| 313 | } | 305 | } |
| 314 | - let event = Event::UserDeleted { | 306 | + let event = Event::UserDeleted { user_id }; |
| 315 | - user_id: user_id.clone(), | 307 | + cx.out.push(Broadcast::new(To::Users(member_ids), event)); |
| 316 | - }; | ||
| 317 | - broadcasts.push(Broadcast::new(To::Users(member_ids), event)); | ||
| 318 | } | 308 | } |
| 319 | - broadcasts.extend(leave_user_voice(rooms, &user_id, &tx).await?); | 309 | + user::delete(user_id, cx.db).await?; |
| 320 | - user::delete(&user_id, &tx).await?; | ||
| 321 | - tx.commit().await?; | ||
| 322 | if me.id != user_id { | 310 | if me.id != user_id { |
| 323 | - cx.sh.services.hub.kick_user(&user_id, Close::Revoked); | 311 | + cx.sh.services.hub.kick_user(user_id, Close::Revoked); |
| 324 | } | 312 | } |
| 325 | - cx.out.extend(broadcasts); | ||
| 326 | 313 | ||
| 327 | Ok(()) | 314 | Ok(()) |
| 328 | } | 315 | } |
| @@ -335,19 +322,19 @@ impl Handle for WatchCommunity { | |||
| 335 | cx.client.watch(None); | 322 | cx.client.watch(None); |
| 336 | return Ok(()); | 323 | return Ok(()); |
| 337 | }; | 324 | }; |
| 338 | - allowed(&me, &community_id, &cx.db, permission::can_read).await?; | 325 | + allowed(&me, community_id, cx.db, permission::can_read).await?; |
| 339 | - let outsider = is_outsider(&me.id, &community_id, &cx.db).await?; | 326 | + let outsider = is_outsider(me.id, community_id, cx.db).await?; |
| 340 | - cx.client.watch(outsider.then_some(community_id.as_str())); | 327 | + cx.client.watch(outsider.then_some(community_id)); |
| 341 | let visit = | 328 | let visit = |
| 342 | - permission::is_builder(me.role) && outsider && user::is_ghost(&me.id, &cx.db).await?; | 329 | + permission::is_builder(me.role) && outsider && user::is_ghost(me.id, cx.db).await?; |
| 343 | - if visit && cx.client.first_visit(&community_id) { | 330 | + if visit && cx.client.first_visit(community_id) { |
| 344 | - let community = community::label(&community_id, &cx.db).await?; | 331 | + let community = community::label(community_id, cx.db).await?; |
| 345 | - admin_log::record( | 332 | + log::record_admin( |
| 346 | - Some(&me.id), | 333 | + Some(me.id), |
| 347 | None, | 334 | None, |
| 348 | Some(&community), | 335 | Some(&community), |
| 349 | &AdminAction::GhostVisit, | 336 | &AdminAction::GhostVisit, |
| 350 | - &cx.db, | 337 | + cx.db, |
| 351 | ) | 338 | ) |
| 352 | .await?; | 339 | .await?; |
| 353 | } | 340 | } |
| @@ -359,8 +346,8 @@ impl Handle for WatchCommunity { | |||
| 359 | impl Handle for ListAllCommunities { | 346 | impl Handle for ListAllCommunities { |
| 360 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<CommunitySummary>, ServerError> { | 347 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<CommunitySummary>, ServerError> { |
| 361 | let mut summaries = Vec::new(); | 348 | let mut summaries = Vec::new(); |
| 362 | - for community in community::groups(&cx.db).await? { | 349 | + for community in community::groups(cx.db).await? { |
| 363 | - let members = user_community::members(&community.id, &cx.db).await?; | 350 | + let members = member::members(community.id, cx.db).await?; |
| 364 | let owner = members | 351 | let owner = members |
| 365 | .iter() | 352 | .iter() |
| 366 | .find(|member| member.rank == Rank::Owner) | 353 | .find(|member| member.rank == Rank::Owner) |
| @@ -383,60 +370,52 @@ impl Handle for TransferOwnership { | |||
| 383 | community_id, | 370 | community_id, |
| 384 | user_id, | 371 | user_id, |
| 385 | } = self; | 372 | } = self; |
| 386 | - ensure_editable(&community_id, &cx.db).await?; | 373 | + ensure_editable(community_id, cx.db).await?; |
| 387 | - allowed( | 374 | + allowed(&me, community_id, cx.db, permission::can_transfer_ownership).await?; |
| 388 | - &me, | 375 | + let members = member::members(community_id, cx.db).await?; |
| 389 | - &community_id, | ||
| 390 | - &cx.db, | ||
| 391 | - permission::can_transfer_ownership, | ||
| 392 | - ) | ||
| 393 | - .await?; | ||
| 394 | - let tx = cx.db.transaction().await?; | ||
| 395 | - let members = user_community::members(&community_id, &tx).await?; | ||
| 396 | let target = members | 376 | let target = members |
| 397 | .iter() | 377 | .iter() |
| 398 | .find(|member| member.user.id == user_id) | 378 | .find(|member| member.user.id == user_id) |
| 399 | .ok_or(Error::NotFound)?; | 379 | .ok_or(Error::NotFound)?; |
| 400 | ensure(target.rank != Rank::Owner)?; | 380 | ensure(target.rank != Rank::Owner)?; |
| 401 | - let mut changes = vec![(user_id.clone(), Rank::Owner)]; | 381 | + let mut changes = vec![(user_id, Rank::Owner)]; |
| 402 | if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) { | 382 | if let Some(previous) = members.iter().find(|member| member.rank == Rank::Owner) { |
| 403 | - user_community::set_rank(&previous.user.id, &community_id, Rank::Admin, &tx).await?; | 383 | + member::set_rank(previous.user.id, community_id, Rank::Admin, cx.db).await?; |
| 404 | log::record( | 384 | log::record( |
| 405 | - &community_id, | 385 | + community_id, |
| 406 | - Some(&me.id), | 386 | + Some(me.id), |
| 407 | - Some(&previous.user.id), | 387 | + Some(previous.user.id), |
| 408 | &LogAction::RankChanged { rank: Rank::Admin }, | 388 | &LogAction::RankChanged { rank: Rank::Admin }, |
| 409 | - &tx, | 389 | + cx.db, |
| 410 | ) | 390 | ) |
| 411 | .await?; | 391 | .await?; |
| 412 | - changes.push((previous.user.id.clone(), Rank::Admin)); | 392 | + changes.push((previous.user.id, Rank::Admin)); |
| 413 | } | 393 | } |
| 414 | - user_community::set_rank(&user_id, &community_id, Rank::Owner, &tx).await?; | 394 | + member::set_rank(user_id, community_id, Rank::Owner, cx.db).await?; |
| 415 | log::record( | 395 | log::record( |
| 416 | - &community_id, | 396 | + community_id, |
| 417 | - Some(&me.id), | 397 | + Some(me.id), |
| 418 | - Some(&user_id), | 398 | + Some(user_id), |
| 419 | &LogAction::RankChanged { rank: Rank::Owner }, | 399 | &LogAction::RankChanged { rank: Rank::Owner }, |
| 420 | - &tx, | 400 | + cx.db, |
| 421 | ) | 401 | ) |
| 422 | .await?; | 402 | .await?; |
| 423 | if permission::is_builder(me.role) { | 403 | if permission::is_builder(me.role) { |
| 424 | - let community = community::read(&community_id, &me.id, &tx).await?; | 404 | + let community = community::read(community_id, me.id, cx.db).await?; |
| 425 | - admin_log::record( | 405 | + log::record_admin( |
| 426 | - Some(&me.id), | 406 | + Some(me.id), |
| 427 | - Some(&user_id), | 407 | + Some(user_id), |
| 428 | Some(&community.name), | 408 | Some(&community.name), |
| 429 | &AdminAction::OwnershipTransferred, | 409 | &AdminAction::OwnershipTransferred, |
| 430 | - &tx, | 410 | + cx.db, |
| 431 | ) | 411 | ) |
| 432 | .await?; | 412 | .await?; |
| 433 | } | 413 | } |
| 434 | - tx.commit().await?; | ||
| 435 | for (changed_id, rank) in changes { | 414 | for (changed_id, rank) in changes { |
| 436 | cx.emit( | 415 | cx.emit( |
| 437 | - To::Community(community_id.clone()), | 416 | + To::Community(community_id), |
| 438 | Event::RankChanged { | 417 | Event::RankChanged { |
| 439 | - community_id: community_id.clone(), | 418 | + community_id, |
| 440 | user_id: changed_id, | 419 | user_id: changed_id, |
| 441 | rank, | 420 | rank, |
| 442 | }, | 421 | }, |
| @@ -451,18 +430,18 @@ impl Handle for TimeoutUser { | |||
| 451 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 430 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 452 | let me = me.user()?; | 431 | let me = me.user()?; |
| 453 | let Self { user_id, minutes } = self; | 432 | let Self { user_id, minutes } = self; |
| 454 | - managed(&me, &user_id, &cx.db).await?; | 433 | + managed(&me, user_id, cx.db).await?; |
| 455 | let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); | 434 | let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); |
| 456 | - user::set_timeout(&user_id, until, &cx.db).await?; | 435 | + user::set_timeout(user_id, until, cx.db).await?; |
| 457 | if until.is_some() { | 436 | if until.is_some() { |
| 458 | - authentication::revoke(&cx.sh.services.hub, Revoke::User(&user_id), &cx.db).await?; | 437 | + authentication::revoke(&cx.sh.services.hub, Revoke::User(user_id), cx.db).await?; |
| 459 | } | 438 | } |
| 460 | - admin_log::record( | 439 | + log::record_admin( |
| 461 | - Some(&me.id), | 440 | + Some(me.id), |
| 462 | - Some(&user_id), | 441 | + Some(user_id), |
| 463 | None, | 442 | None, |
| 464 | &AdminAction::UserTimedOut { minutes }, | 443 | &AdminAction::UserTimedOut { minutes }, |
| 465 | - &cx.db, | 444 | + cx.db, |
| 466 | ) | 445 | ) |
| 467 | .await?; | 446 | .await?; |
| 468 | 447 | ||
| @@ -478,33 +457,30 @@ impl Handle for BanUser { | |||
| 478 | reason, | 457 | reason, |
| 479 | scope, | 458 | scope, |
| 480 | } = self; | 459 | } = self; |
| 481 | - let target = managed(&me, &user_id, &cx.db).await?; | 460 | + let target = managed(&me, user_id, cx.db).await?; |
| 482 | - let tx = cx.db.transaction().await?; | 461 | + user::set_suspended(user_id, true, cx.db).await?; |
| 483 | - user::set_suspended(&user_id, true, &tx).await?; | 462 | + session::delete_all(user_id, cx.db).await?; |
| 484 | - authentication::revoke_sessions(&user_id, &tx).await?; | ||
| 485 | server_ban::insert( | 463 | server_ban::insert( |
| 486 | ServerBanKind::Username, | 464 | ServerBanKind::Username, |
| 487 | - &target.username.to_ascii_lowercase(), | 465 | + &target.username, |
| 488 | reason.as_deref(), | 466 | reason.as_deref(), |
| 489 | - &me.id, | 467 | + cx.db, |
| 490 | - &tx, | ||
| 491 | ) | 468 | ) |
| 492 | .await?; | 469 | .await?; |
| 493 | if scope == BanScope::AccountAndIp | 470 | if scope == BanScope::AccountAndIp |
| 494 | - && let Some(address) = user::last_ip(&user_id, &tx).await? | 471 | + && let Some(address) = user::last_ip(user_id, cx.db).await? |
| 495 | { | 472 | { |
| 496 | - server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx).await?; | 473 | + server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), cx.db).await?; |
| 497 | } | 474 | } |
| 498 | - admin_log::record( | 475 | + log::record_admin( |
| 499 | - Some(&me.id), | 476 | + Some(me.id), |
| 500 | - Some(&user_id), | 477 | + Some(user_id), |
| 501 | None, | 478 | None, |
| 502 | &AdminAction::UserBanned { reason }, | 479 | &AdminAction::UserBanned { reason }, |
| 503 | - &tx, | 480 | + cx.db, |
| 504 | ) | 481 | ) |
| 505 | .await?; | 482 | .await?; |
| 506 | - tx.commit().await?; | 483 | + cx.sh.services.hub.kick_user(user_id, Close::Banned); |
| 507 | - cx.sh.services.hub.kick_user(&user_id, Close::Banned); | ||
| 508 | 484 | ||
| 509 | Ok(()) | 485 | Ok(()) |
| 510 | } | 486 | } |
| @@ -512,15 +488,15 @@ impl Handle for BanUser { | |||
| 512 | 488 | ||
| 513 | impl Handle for ListServerBans { | 489 | impl Handle for ListServerBans { |
| 514 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<ServerBan>, ServerError> { | 490 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<ServerBan>, ServerError> { |
| 515 | - server_ban::list(&cx.db).await | 491 | + server_ban::list(cx.db).await |
| 516 | } | 492 | } |
| 517 | } | 493 | } |
| 518 | 494 | ||
| 519 | impl Handle for RemoveServerBan { | 495 | impl Handle for RemoveServerBan { |
| 520 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 496 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 521 | let me = me.user()?; | 497 | let me = me.user()?; |
| 522 | - server_ban::remove(&self.id, &cx.db).await?; | 498 | + server_ban::remove(self.id, cx.db).await?; |
| 523 | - admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &cx.db).await?; | 499 | + log::record_admin(Some(me.id), None, None, &AdminAction::BanRemoved, cx.db).await?; |
| 524 | 500 | ||
| 525 | Ok(()) | 501 | Ok(()) |
| 526 | } | 502 | } |
| @@ -530,15 +506,9 @@ impl Handle for CreateInviteCode { | |||
| 530 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<InviteCode, ServerError> { | 506 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<InviteCode, ServerError> { |
| 531 | let me = me.user()?; | 507 | let me = me.user()?; |
| 532 | ensure(permission::is_builder(me.role) && self.uses > 0)?; | 508 | ensure(permission::is_builder(me.role) && self.uses > 0)?; |
| 533 | - let code = invite::create(self.uses, self.hours, &me, &cx.db).await?; | 509 | + let code = |
| 534 | - admin_log::record( | 510 | + registration_code::create(&generate_code()?, self.uses, self.hours, cx.db).await?; |
| 535 | - Some(&me.id), | 511 | + log::record_admin(Some(me.id), None, None, &AdminAction::InviteCreated, cx.db).await?; |
| 536 | - None, | ||
| 537 | - None, | ||
| 538 | - &AdminAction::InviteCreated, | ||
| 539 | - &cx.db, | ||
| 540 | - ) | ||
| 541 | - .await?; | ||
| 542 | 512 | ||
| 543 | Ok(code) | 513 | Ok(code) |
| 544 | } | 514 | } |
| @@ -546,22 +516,15 @@ impl Handle for CreateInviteCode { | |||
| 546 | 516 | ||
| 547 | impl Handle for ListInviteCodes { | 517 | impl Handle for ListInviteCodes { |
| 548 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<InviteCode>, ServerError> { | 518 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<InviteCode>, ServerError> { |
| 549 | - invite::list(&cx.db).await | 519 | + registration_code::list(cx.db).await |
| 550 | } | 520 | } |
| 551 | } | 521 | } |
| 552 | 522 | ||
| 553 | impl Handle for DeleteInviteCode { | 523 | impl Handle for DeleteInviteCode { |
| 554 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 524 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 555 | let me = me.user()?; | 525 | let me = me.user()?; |
| 556 | - invite::delete(&self.code, &cx.db).await?; | 526 | + registration_code::delete(&self.code, cx.db).await?; |
| 557 | - admin_log::record( | 527 | + log::record_admin(Some(me.id), None, None, &AdminAction::InviteDeleted, cx.db).await?; |
| 558 | - Some(&me.id), | ||
| 559 | - None, | ||
| 560 | - None, | ||
| 561 | - &AdminAction::InviteDeleted, | ||
| 562 | - &cx.db, | ||
| 563 | - ) | ||
| 564 | - .await?; | ||
| 565 | 528 | ||
| 566 | Ok(()) | 529 | Ok(()) |
| 567 | } | 530 | } |
| @@ -571,11 +534,11 @@ impl Handle for SearchMessages { | |||
| 571 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<MessageHit>, ServerError> { | 534 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<MessageHit>, ServerError> { |
| 572 | message::search( | 535 | message::search( |
| 573 | self.text.as_deref(), | 536 | self.text.as_deref(), |
| 574 | - self.user_id.as_deref(), | 537 | + self.user_id, |
| 575 | - self.community_id.as_deref(), | 538 | + self.community_id, |
| 576 | self.after_ms, | 539 | self.after_ms, |
| 577 | self.before_ms, | 540 | self.before_ms, |
| 578 | - &cx.db, | 541 | + cx.db, |
| 579 | ) | 542 | ) |
| 580 | .await | 543 | .await |
| 581 | } | 544 | } |
| @@ -584,15 +547,15 @@ impl Handle for SearchMessages { | |||
| 584 | impl Handle for SearchCommunity { | 547 | impl Handle for SearchCommunity { |
| 585 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<MessageHit>, ServerError> { | 548 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<MessageHit>, ServerError> { |
| 586 | let me = me.user()?; | 549 | let me = me.user()?; |
| 587 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 550 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 588 | 551 | ||
| 589 | message::search( | 552 | message::search( |
| 590 | Some(&self.text), | 553 | Some(&self.text), |
| 591 | None, | 554 | None, |
| 592 | - Some(&self.community_id), | 555 | + Some(self.community_id), |
| 593 | None, | 556 | None, |
| 594 | None, | 557 | None, |
| 595 | - &cx.db, | 558 | + cx.db, |
| 596 | ) | 559 | ) |
| 597 | .await | 560 | .await |
| 598 | } | 561 | } |
| @@ -602,37 +565,20 @@ impl Handle for PurgeUser { | |||
| 602 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 565 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 603 | let me = me.user()?; | 566 | let me = me.user()?; |
| 604 | let user_id = self.user_id; | 567 | let user_id = self.user_id; |
| 605 | - managed(&me, &user_id, &cx.db).await?; | 568 | + managed(&me, user_id, cx.db).await?; |
| 606 | - let tx = cx.db.transaction().await?; | 569 | + let deleted = message::delete_where_user(user_id, cx.db).await?; |
| 607 | - let upload_ids = attachment::uploads_of(&user_id, &tx).await?; | 570 | + attachment::delete_uploads(user_id, cx.db).await?; |
| 608 | - let message_ids = message::ids_of_user(&user_id, &tx).await?; | 571 | + log::record_admin( |
| 609 | - let mut deleted: BTreeMap<String, Vec<String>> = BTreeMap::new(); | 572 | + Some(me.id), |
| 610 | - for message_id in &message_ids { | 573 | + Some(user_id), |
| 611 | - let message = message::delete(message_id, &tx).await?; | ||
| 612 | - deleted | ||
| 613 | - .entry(message.community_id) | ||
| 614 | - .or_default() | ||
| 615 | - .push(message.id); | ||
| 616 | - } | ||
| 617 | - attachment::delete_uploads(&user_id, &tx).await?; | ||
| 618 | - admin_log::record( | ||
| 619 | - Some(&me.id), | ||
| 620 | - Some(&user_id), | ||
| 621 | None, | 574 | None, |
| 622 | &AdminAction::UserPurged { | 575 | &AdminAction::UserPurged { |
| 623 | - messages: message_ids.len() as u64, | 576 | + messages: deleted.len() as u64, |
| 624 | }, | 577 | }, |
| 625 | - &tx, | 578 | + cx.db, |
| 626 | ) | 579 | ) |
| 627 | .await?; | 580 | .await?; |
| 628 | - tx.commit().await?; | 581 | + cx.out.extend(messages_deleted(deleted)); |
| 629 | - attachment::remove_files(&upload_ids, &cx.sh.directory); | ||
| 630 | - for (community_id, ids) in deleted { | ||
| 631 | - cx.emit( | ||
| 632 | - To::Community(community_id.clone()), | ||
| 633 | - Event::MessagesDeleted { community_id, ids }, | ||
| 634 | - ); | ||
| 635 | - } | ||
| 636 | 582 | ||
| 637 | Ok(()) | 583 | Ok(()) |
| 638 | } | 584 | } |
| @@ -640,39 +586,28 @@ impl Handle for PurgeUser { | |||
| 640 | 586 | ||
| 641 | impl Handle for ListAttachments { | 587 | impl Handle for ListAttachments { |
| 642 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<AttachmentInfo>, ServerError> { | 588 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<AttachmentInfo>, ServerError> { |
| 643 | - attachment::all( | 589 | + attachment::all(self.user_id, self.community_id, cx.db).await |
| 644 | - self.user_id.as_deref(), | ||
| 645 | - self.community_id.as_deref(), | ||
| 646 | - &cx.db, | ||
| 647 | - ) | ||
| 648 | - .await | ||
| 649 | } | 590 | } |
| 650 | } | 591 | } |
| 651 | 592 | ||
| 652 | impl Handle for DeleteAttachment { | 593 | impl Handle for DeleteAttachment { |
| 653 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 594 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 654 | let me = me.user()?; | 595 | let me = me.user()?; |
| 655 | - let attachment_id = self.attachment_id; | 596 | + let stored = attachment::read(self.attachment_id, cx.db).await?; |
| 656 | - let stored = attachment::read(&attachment_id, &cx.db).await?; | 597 | + let community = community::label(stored.community_id, cx.db).await?; |
| 657 | - let community = community::label(&stored.community_id, &cx.db).await?; | 598 | + attachment::delete(self.attachment_id, cx.db).await?; |
| 658 | - let tx = cx.db.transaction().await?; | 599 | + log::record_admin( |
| 659 | - attachment::delete(&attachment_id, &tx).await?; | 600 | + Some(me.id), |
| 660 | - admin_log::record( | 601 | + Some(stored.uploader_id), |
| 661 | - Some(&me.id), | ||
| 662 | - Some(&stored.uploader_id), | ||
| 663 | Some(&community), | 602 | Some(&community), |
| 664 | &AdminAction::AttachmentDeleted, | 603 | &AdminAction::AttachmentDeleted, |
| 665 | - &tx, | 604 | + cx.db, |
| 666 | ) | 605 | ) |
| 667 | .await?; | 606 | .await?; |
| 668 | - let mut broadcast = None; | 607 | + if let Some(message_id) = stored.message_id { |
| 669 | - if let Some(message_id) = &stored.message_id { | 608 | + let updated = message::read(message_id, cx.db).await?; |
| 670 | - let updated = message::read(message_id, &tx).await?; | 609 | + cx.out.push(message_event(&updated, Event::MessageUpdated)); |
| 671 | - broadcast = Some(message_event(&updated, Event::MessageUpdated)); | ||
| 672 | } | 610 | } |
| 673 | - tx.commit().await?; | ||
| 674 | - attachment::remove_files(&[attachment_id], &cx.sh.directory); | ||
| 675 | - cx.out.extend(broadcast); | ||
| 676 | 611 | ||
| 677 | Ok(()) | 612 | Ok(()) |
| 678 | } | 613 | } |
| @@ -680,7 +615,7 @@ impl Handle for DeleteAttachment { | |||
| 680 | 615 | ||
| 681 | impl Handle for GetStorageUsage { | 616 | impl Handle for GetStorageUsage { |
| 682 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<StorageUsage, ServerError> { | 617 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<StorageUsage, ServerError> { |
| 683 | - let (users, communities) = attachment::usage(&cx.db).await?; | 618 | + let (users, communities) = attachment::usage(cx.db).await?; |
| 684 | 619 | ||
| 685 | Ok(StorageUsage { users, communities }) | 620 | Ok(StorageUsage { users, communities }) |
| 686 | } | 621 | } |
| @@ -689,11 +624,11 @@ impl Handle for GetStorageUsage { | |||
| 689 | impl Handle for CreateBackup { | 624 | impl Handle for CreateBackup { |
| 690 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<BackupInfo, ServerError> { | 625 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<BackupInfo, ServerError> { |
| 691 | let me = me.user()?; | 626 | let me = me.user()?; |
| 692 | - let backup = backup::create(&cx.db, &cx.sh.backups).await?; | 627 | + let backup = backup::create(&cx.sh.db, &cx.sh.backups).await?; |
| 693 | let action = AdminAction::BackupCreated { | 628 | let action = AdminAction::BackupCreated { |
| 694 | name: backup.name.clone(), | 629 | name: backup.name.clone(), |
| 695 | }; | 630 | }; |
| 696 | - admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; | 631 | + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; |
| 697 | 632 | ||
| 698 | Ok(backup) | 633 | Ok(backup) |
| 699 | } | 634 | } |
| @@ -710,7 +645,7 @@ impl Handle for DeleteBackup { | |||
| 710 | let me = me.user()?; | 645 | let me = me.user()?; |
| 711 | backup::delete(&self.name, &cx.sh.backups)?; | 646 | backup::delete(&self.name, &cx.sh.backups)?; |
| 712 | let action = AdminAction::BackupDeleted { name: self.name }; | 647 | let action = AdminAction::BackupDeleted { name: self.name }; |
| 713 | - admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; | 648 | + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; |
| 714 | 649 | ||
| 715 | Ok(()) | 650 | Ok(()) |
| 716 | } | 651 | } |
| @@ -723,27 +658,25 @@ impl Handle for SetCommunityVoice { | |||
| 723 | community_id, | 658 | community_id, |
| 724 | enabled, | 659 | enabled, |
| 725 | } = self; | 660 | } = self; |
| 726 | - allowed(&me, &community_id, &cx.db, permission::can_manage_voice).await?; | 661 | + allowed(&me, community_id, cx.db, permission::can_manage_voice).await?; |
| 727 | - let tx = cx.db.transaction().await?; | 662 | + community::set_voice_enabled(community_id, enabled, cx.db).await?; |
| 728 | - community::set_voice_enabled(&community_id, enabled, &tx).await?; | 663 | + let updated = community::read(community_id, me.id, cx.db).await?; |
| 729 | - let updated = community::read(&community_id, &me.id, &tx).await?; | ||
| 730 | if permission::is_builder(me.role) { | 664 | if permission::is_builder(me.role) { |
| 731 | - admin_log::record( | 665 | + log::record_admin( |
| 732 | - Some(&me.id), | 666 | + Some(me.id), |
| 733 | None, | 667 | None, |
| 734 | Some(&updated.name), | 668 | Some(&updated.name), |
| 735 | &AdminAction::CommunityVoiceSet { enabled }, | 669 | &AdminAction::CommunityVoiceSet { enabled }, |
| 736 | - &tx, | 670 | + cx.db, |
| 737 | ) | 671 | ) |
| 738 | .await?; | 672 | .await?; |
| 739 | } | 673 | } |
| 740 | - tx.commit().await?; | ||
| 741 | if !enabled { | 674 | if !enabled { |
| 742 | let rooms = &cx.sh.services.rooms; | 675 | let rooms = &cx.sh.services.rooms; |
| 743 | - for user_id in rooms.room_users(&community_id) { | 676 | + for user_id in rooms.room_users(community_id) { |
| 744 | - if !permission::is_builder(user::read(&user_id, &cx.db).await?.role) { | 677 | + if !permission::is_builder(user::read(user_id, cx.db).await?.role) { |
| 745 | cx.out | 678 | cx.out |
| 746 | - .extend(leave_room_voice(rooms, &community_id, &user_id, &cx.db).await?); | 679 | + .extend(leave_room_voice(rooms, community_id, user_id, cx.db).await?); |
| 747 | } | 680 | } |
| 748 | } | 681 | } |
| 749 | } | 682 | } |
| @@ -761,37 +694,37 @@ impl Handle for SetGhost { | |||
| 761 | let me = me.user()?; | 694 | let me = me.user()?; |
| 762 | let enabled = self.enabled; | 695 | let enabled = self.enabled; |
| 763 | let rooms = &cx.sh.services.rooms; | 696 | let rooms = &cx.sh.services.rooms; |
| 764 | - user::set_ghost(&me.id, enabled, &cx.db).await?; | 697 | + user::set_ghost(me.id, enabled, cx.db).await?; |
| 765 | let action = if enabled { | 698 | let action = if enabled { |
| 766 | AdminAction::GhostEnabled | 699 | AdminAction::GhostEnabled |
| 767 | } else { | 700 | } else { |
| 768 | AdminAction::GhostDisabled | 701 | AdminAction::GhostDisabled |
| 769 | }; | 702 | }; |
| 770 | - admin_log::record(Some(&me.id), None, None, &action, &cx.db).await?; | 703 | + log::record_admin(Some(me.id), None, None, &action, cx.db).await?; |
| 771 | let mut broadcasts = Vec::new(); | 704 | let mut broadcasts = Vec::new(); |
| 772 | - let outsider = match rooms.room_of(&me.id) { | 705 | + let outsider = match rooms.room_of(me.id) { |
| 773 | - Some(community_id) => is_outsider(&me.id, &community_id, &cx.db).await?, | 706 | + Some(community_id) => is_outsider(me.id, community_id, cx.db).await?, |
| 774 | None => false, | 707 | None => false, |
| 775 | }; | 708 | }; |
| 776 | - if !outsider && let Some(mut departure) = rooms.set_ghost(&me.id, enabled) { | 709 | + if !outsider && let Some(mut departure) = rooms.set_ghost(me.id, enabled) { |
| 777 | - let community_id = departure.community_id.clone(); | 710 | + let community_id = departure.community_id; |
| 778 | if enabled { | 711 | if enabled { |
| 779 | broadcasts.extend(shares_ended(&mut departure)); | 712 | broadcasts.extend(shares_ended(&mut departure)); |
| 780 | broadcasts | 713 | broadcasts |
| 781 | - .extend(call_ended(&community_id, &me.id, departure.call_log, &cx.db).await?); | 714 | + .extend(call_ended(community_id, me.id, departure.call_log, cx.db).await?); |
| 782 | let event = Event::VoiceLeft { | 715 | let event = Event::VoiceLeft { |
| 783 | - community_id: community_id.clone(), | 716 | + community_id, |
| 784 | - user_id: me.id.clone(), | 717 | + user_id: me.id, |
| 785 | }; | 718 | }; |
| 786 | broadcasts.push(Broadcast::new( | 719 | broadcasts.push(Broadcast::new( |
| 787 | - To::CommunityExcept(community_id, me.id.clone()), | 720 | + To::CommunityExcept(community_id, me.id), |
| 788 | event, | 721 | event, |
| 789 | )); | 722 | )); |
| 790 | } else { | 723 | } else { |
| 791 | - let muted = user::voice_muted(&me.id, &cx.db).await?; | 724 | + let muted = user::voice_muted(me.id, cx.db).await?; |
| 792 | - broadcasts.extend(voice_joined(&community_id, &me.id, muted)); | 725 | + broadcasts.extend(voice_joined(community_id, me.id, muted)); |
| 793 | if let Some(seconds) = departure.ghost_seconds { | 726 | if let Some(seconds) = departure.ghost_seconds { |
| 794 | - record_ghost_voice(&me.id, &community_id, seconds, &cx.db).await?; | 727 | + record_ghost_voice(me.id, community_id, seconds, cx.db).await?; |
| 795 | } | 728 | } |
| 796 | } | 729 | } |
| 797 | } | 730 | } |
crates/server/src/call/community.rsmodified+101 -132
| @@ -6,67 +6,65 @@ use common::{ | |||
| 6 | }, | 6 | }, |
| 7 | error::Error, | 7 | error::Error, |
| 8 | event::Event, | 8 | event::Event, |
| 9 | - model::{AdminAction, Ban, Community, LogAction, LogEntry, Member, Rank, Sanction, User}, | 9 | + model::{AdminAction, Ban, Community, Id, LogAction, LogEntry, Member, Rank, Sanction, User}, |
| 10 | permission, | 10 | permission, |
| 11 | validate::validate_avatar_size, | 11 | validate::validate_avatar_size, |
| 12 | }; | 12 | }; |
| 13 | 13 | ||
| 14 | use crate::{ | 14 | use crate::{ |
| 15 | - admin_log, | ||
| 16 | call::{Cx, Handle, Me}, | 15 | call::{Cx, Handle, Me}, |
| 17 | - community, | 16 | + db::{self, community::Kind}, |
| 18 | - error::ServerError, | 17 | + error::{ServerError, ensure, ensure_with}, |
| 19 | - log, | 18 | + files, |
| 20 | publish::To, | 19 | publish::To, |
| 21 | - request::{ | 20 | + request::{actor_rank, allowed, delete_community, ensure_editable, leave_room_voice}, |
| 22 | - actor_rank, allowed, ensure, ensure_editable, ensure_with, leave_room_voice, voice_closed, | ||
| 23 | - }, | ||
| 24 | - server_settings, user, user_community, | ||
| 25 | }; | 21 | }; |
| 26 | 22 | ||
| 27 | async fn remove_member( | 23 | async fn remove_member( |
| 28 | me: &User, | 24 | me: &User, |
| 29 | - community_id: String, | 25 | + community_id: Id, |
| 30 | - user_id: String, | 26 | + user_id: Id, |
| 31 | reason: Option<String>, | 27 | reason: Option<String>, |
| 32 | sanction: Sanction, | 28 | sanction: Sanction, |
| 33 | cx: &mut Cx<'_>, | 29 | cx: &mut Cx<'_>, |
| 34 | ) -> Result<(), ServerError> { | 30 | ) -> Result<(), ServerError> { |
| 35 | - ensure_editable(&community_id, &cx.db).await?; | 31 | + let db = cx.db; |
| 36 | - let target = user::read(&user_id, &cx.db).await?; | 32 | + ensure_editable(community_id, db).await?; |
| 33 | + let target = db::user::read(user_id, db).await?; | ||
| 37 | ensure(permission::can_moderate( | 34 | ensure(permission::can_moderate( |
| 38 | - actor_rank(me, &community_id, &cx.db).await?, | 35 | + actor_rank(me, community_id, db).await?, |
| 39 | - actor_rank(&target, &community_id, &cx.db).await?, | 36 | + actor_rank(&target, community_id, db).await?, |
| 40 | ))?; | 37 | ))?; |
| 41 | - let community = community::read(&community_id, &me.id, &cx.db).await?; | 38 | + let community = db::community::read(community_id, me.id, db).await?; |
| 42 | - let tx = cx.db.transaction().await?; | 39 | + let left = db::member::leave(user_id, community_id, db).await?; |
| 43 | - user_community::leave(&user_id, &community_id, &tx).await?; | ||
| 44 | let action = match sanction { | 40 | let action = match sanction { |
| 45 | Sanction::Ban => { | 41 | Sanction::Ban => { |
| 46 | - user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?; | 42 | + db::member::ban(user_id, community_id, reason.as_deref(), db).await?; |
| 47 | LogAction::Banned { | 43 | LogAction::Banned { |
| 48 | reason: reason.clone(), | 44 | reason: reason.clone(), |
| 49 | } | 45 | } |
| 50 | } | 46 | } |
| 51 | - Sanction::Kick => LogAction::Kicked { | 47 | + Sanction::Kick => { |
| 52 | - reason: reason.clone(), | 48 | + ensure_with(left == 1, Error::NotFound)?; |
| 53 | - }, | 49 | + LogAction::Kicked { |
| 50 | + reason: reason.clone(), | ||
| 51 | + } | ||
| 52 | + } | ||
| 54 | }; | 53 | }; |
| 55 | - log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; | 54 | + db::log::record(community_id, Some(me.id), Some(user_id), &action, db).await?; |
| 56 | - tx.commit().await?; | ||
| 57 | cx.out | 55 | cx.out |
| 58 | - .extend(leave_room_voice(&cx.sh.services.rooms, &community_id, &user_id, &cx.db).await?); | 56 | + .extend(leave_room_voice(&cx.sh.services.rooms, community_id, user_id, db).await?); |
| 59 | cx.emit( | 57 | cx.emit( |
| 60 | - To::User(user_id.clone()), | 58 | + To::User(user_id), |
| 61 | Event::Removed { | 59 | Event::Removed { |
| 62 | - community_id: community_id.clone(), | 60 | + community_id, |
| 63 | community_name: community.name, | 61 | community_name: community.name, |
| 64 | sanction, | 62 | sanction, |
| 65 | reason, | 63 | reason, |
| 66 | }, | 64 | }, |
| 67 | ); | 65 | ); |
| 68 | cx.emit( | 66 | cx.emit( |
| 69 | - To::Community(community_id.clone()), | 67 | + To::Community(community_id), |
| 70 | Event::MemberLeft { | 68 | Event::MemberLeft { |
| 71 | community_id, | 69 | community_id, |
| 72 | user_id, | 70 | user_id, |
| @@ -79,46 +77,38 @@ async fn remove_member( | |||
| 79 | impl Handle for CreateCommunity { | 77 | impl Handle for CreateCommunity { |
| 80 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 78 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 81 | let me = me.user()?; | 79 | let me = me.user()?; |
| 82 | - let limit = server_settings::read(&cx.db) | 80 | + let db = cx.db; |
| 83 | - .await? | 81 | + let limit = db::settings::read(db).await?.max_communities_per_user; |
| 84 | - .max_communities_per_user; | 82 | + let owned = db::member::owned_groups(me.id, db).await?; |
| 85 | - let owned = user_community::owned_groups(&me.id, &cx.db).await?; | 83 | + ensure_with(limit == 0 || owned < limit, Error::LimitReached)?; |
| 86 | - ensure_with(limit == 0 || owned < limit as usize, Error::LimitReached)?; | 84 | + let community_id = db::community::create(Kind::Group, &self.name, db).await?; |
| 87 | - let tx = cx.db.transaction().await?; | 85 | + db::member::join(me.id, community_id, Rank::Owner, db).await?; |
| 88 | - let community = community::create(&self.name, &tx).await?; | 86 | + db::log::record(community_id, Some(me.id), None, &LogAction::Created, db).await?; |
| 89 | - user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?; | ||
| 90 | - log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?; | ||
| 91 | - tx.commit().await?; | ||
| 92 | 87 | ||
| 93 | - Ok(community) | 88 | + db::community::read(community_id, me.id, db).await |
| 94 | } | 89 | } |
| 95 | } | 90 | } |
| 96 | 91 | ||
| 97 | impl Handle for GetCommunity { | 92 | impl Handle for GetCommunity { |
| 98 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 93 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 99 | let me = me.user()?; | 94 | let me = me.user()?; |
| 100 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 95 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 101 | 96 | ||
| 102 | - community::read(&self.community_id, &me.id, &cx.db).await | 97 | + db::community::read(self.community_id, me.id, cx.db).await |
| 103 | } | 98 | } |
| 104 | } | 99 | } |
| 105 | 100 | ||
| 106 | impl Handle for UpdateCommunity { | 101 | impl Handle for UpdateCommunity { |
| 107 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 102 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 108 | let me = me.user()?; | 103 | let me = me.user()?; |
| 109 | - ensure_editable(&self.community_id, &cx.db).await?; | 104 | + let db = cx.db; |
| 110 | - allowed( | 105 | + ensure_editable(self.community_id, db).await?; |
| 111 | - &me, | 106 | + allowed(&me, self.community_id, db, permission::can_rename_community).await?; |
| 112 | - &self.community_id, | 107 | + let updated = db::community::update(self.community_id, &self.name, me.id, db).await?; |
| 113 | - &cx.db, | ||
| 114 | - permission::can_rename_community, | ||
| 115 | - ) | ||
| 116 | - .await?; | ||
| 117 | - let updated = community::update(&self.community_id, &self.name, &me.id, &cx.db).await?; | ||
| 118 | let action = LogAction::Renamed { | 108 | let action = LogAction::Renamed { |
| 119 | name: updated.name.clone(), | 109 | name: updated.name.clone(), |
| 120 | }; | 110 | }; |
| 121 | - log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?; | 111 | + db::log::record(self.community_id, Some(me.id), None, &action, db).await?; |
| 122 | cx.emit( | 112 | cx.emit( |
| 123 | To::Community(self.community_id), | 113 | To::Community(self.community_id), |
| 124 | Event::CommunityUpdated(updated.clone()), | 114 | Event::CommunityUpdated(updated.clone()), |
| @@ -131,30 +121,21 @@ impl Handle for UpdateCommunity { | |||
| 131 | impl Handle for UpdateCommunityAvatar { | 121 | impl Handle for UpdateCommunityAvatar { |
| 132 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 122 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 133 | let me = me.user()?; | 123 | let me = me.user()?; |
| 134 | - ensure_editable(&self.community_id, &cx.db).await?; | 124 | + let db = cx.db; |
| 135 | - allowed( | 125 | + ensure_editable(self.community_id, db).await?; |
| 136 | - &me, | 126 | + allowed(&me, self.community_id, db, permission::can_rename_community).await?; |
| 137 | - &self.community_id, | ||
| 138 | - &cx.db, | ||
| 139 | - permission::can_rename_community, | ||
| 140 | - ) | ||
| 141 | - .await?; | ||
| 142 | if let Some(bytes) = &self.image { | 127 | if let Some(bytes) = &self.image { |
| 143 | - validate_avatar_size(bytes, server_settings::read(&cx.db).await?.max_avatar_bytes)?; | 128 | + validate_avatar_size(bytes, db::settings::read(db).await?.max_avatar_bytes)?; |
| 129 | + files::check_avatar(bytes)?; | ||
| 144 | } | 130 | } |
| 145 | - let updated = community::set_avatar( | 131 | + db::avatar::set_community(self.community_id, self.image.as_deref(), db).await?; |
| 146 | - &self.community_id, | 132 | + let updated = db::community::read(self.community_id, me.id, db).await?; |
| 147 | - self.image.as_deref(), | ||
| 148 | - &me.id, | ||
| 149 | - &mut cx.db, | ||
| 150 | - ) | ||
| 151 | - .await?; | ||
| 152 | let action = if self.image.is_some() { | 133 | let action = if self.image.is_some() { |
| 153 | LogAction::AvatarChanged | 134 | LogAction::AvatarChanged |
| 154 | } else { | 135 | } else { |
| 155 | LogAction::AvatarRemoved | 136 | LogAction::AvatarRemoved |
| 156 | }; | 137 | }; |
| 157 | - log::record(&self.community_id, Some(&me.id), None, &action, &cx.db).await?; | 138 | + db::log::record(self.community_id, Some(me.id), None, &action, db).await?; |
| 158 | cx.emit( | 139 | cx.emit( |
| 159 | To::Community(self.community_id), | 140 | To::Community(self.community_id), |
| 160 | Event::CommunityUpdated(updated.clone()), | 141 | Event::CommunityUpdated(updated.clone()), |
| @@ -167,36 +148,27 @@ impl Handle for UpdateCommunityAvatar { | |||
| 167 | impl Handle for DeleteCommunity { | 148 | impl Handle for DeleteCommunity { |
| 168 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 149 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 169 | let me = me.user()?; | 150 | let me = me.user()?; |
| 170 | - ensure_editable(&self.community_id, &cx.db).await?; | 151 | + let db = cx.db; |
| 171 | - allowed( | 152 | + ensure_editable(self.community_id, db).await?; |
| 172 | - &me, | 153 | + allowed(&me, self.community_id, db, permission::can_delete_community).await?; |
| 173 | - &self.community_id, | 154 | + let member_ids = db::member::member_ids(self.community_id, db).await?; |
| 174 | - &cx.db, | 155 | + let owned = db::member::rank(me.id, self.community_id, db).await? == Some(Rank::Owner); |
| 175 | - permission::can_delete_community, | 156 | + let deleted = db::community::read(self.community_id, me.id, db).await?; |
| 176 | - ) | ||
| 177 | - .await?; | ||
| 178 | - let tx = cx.db.transaction().await?; | ||
| 179 | - let member_ids = user_community::member_ids(&self.community_id, &tx).await?; | ||
| 180 | - let owned = | ||
| 181 | - user_community::rank(&me.id, &self.community_id, &tx).await? == Some(Rank::Owner); | ||
| 182 | - let deleted = community::delete(&self.community_id, &me.id, &tx).await?; | ||
| 183 | if permission::is_builder(me.role) && !owned { | 157 | if permission::is_builder(me.role) && !owned { |
| 184 | - admin_log::record( | 158 | + db::log::record_admin( |
| 185 | - Some(&me.id), | 159 | + Some(me.id), |
| 186 | None, | 160 | None, |
| 187 | Some(&deleted.name), | 161 | Some(&deleted.name), |
| 188 | &AdminAction::CommunityDeleted, | 162 | &AdminAction::CommunityDeleted, |
| 189 | - &tx, | 163 | + db, |
| 190 | ) | 164 | ) |
| 191 | .await?; | 165 | .await?; |
| 192 | } | 166 | } |
| 193 | - tx.commit().await?; | 167 | + delete_community(self.community_id, cx).await?; |
| 194 | - cx.out | ||
| 195 | - .extend(voice_closed(&cx.sh.services.rooms, &self.community_id, &cx.db).await?); | ||
| 196 | cx.emit( | 168 | cx.emit( |
| 197 | To::Users(member_ids), | 169 | To::Users(member_ids), |
| 198 | Event::CommunityDeleted { | 170 | Event::CommunityDeleted { |
| 199 | - community_id: deleted.id.clone(), | 171 | + community_id: deleted.id, |
| 200 | }, | 172 | }, |
| 201 | ); | 173 | ); |
| 202 | 174 | ||
| @@ -207,30 +179,25 @@ impl Handle for DeleteCommunity { | |||
| 207 | impl Handle for LeaveCommunity { | 179 | impl Handle for LeaveCommunity { |
| 208 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 180 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 209 | let me = me.user()?; | 181 | let me = me.user()?; |
| 210 | - ensure_editable(&self.community_id, &cx.db).await?; | 182 | + let db = cx.db; |
| 211 | - allowed(&me, &self.community_id, &cx.db, permission::can_leave).await?; | 183 | + ensure_editable(self.community_id, db).await?; |
| 212 | - let tx = cx.db.transaction().await?; | 184 | + let rank = db::member::rank(me.id, self.community_id, db).await?; |
| 213 | - user_community::leave(&me.id, &self.community_id, &tx).await?; | 185 | + ensure(permission::can_leave(rank))?; |
| 214 | - log::record( | 186 | + let left = db::member::leave(me.id, self.community_id, db).await?; |
| 215 | - &self.community_id, | 187 | + ensure_with(left == 1, Error::NotFound)?; |
| 216 | - Some(&me.id), | 188 | + db::log::record(self.community_id, Some(me.id), None, &LogAction::Left, db).await?; |
| 217 | - None, | 189 | + if db::member::member_ids(self.community_id, db) |
| 218 | - &LogAction::Left, | ||
| 219 | - &tx, | ||
| 220 | - ) | ||
| 221 | - .await?; | ||
| 222 | - if user_community::member_ids(&self.community_id, &tx) | ||
| 223 | .await? | 190 | .await? |
| 224 | .is_empty() | 191 | .is_empty() |
| 225 | { | 192 | { |
| 226 | - community::delete(&self.community_id, &me.id, &tx).await?; | 193 | + delete_community(self.community_id, cx).await?; |
| 194 | + } else { | ||
| 195 | + let broadcasts = | ||
| 196 | + leave_room_voice(&cx.sh.services.rooms, self.community_id, me.id, db).await?; | ||
| 197 | + cx.out.extend(broadcasts); | ||
| 227 | } | 198 | } |
| 228 | - tx.commit().await?; | ||
| 229 | - let broadcasts = | ||
| 230 | - leave_room_voice(&cx.sh.services.rooms, &self.community_id, &me.id, &cx.db).await?; | ||
| 231 | - cx.out.extend(broadcasts); | ||
| 232 | cx.emit( | 199 | cx.emit( |
| 233 | - To::Community(self.community_id.clone()), | 200 | + To::Community(self.community_id), |
| 234 | Event::MemberLeft { | 201 | Event::MemberLeft { |
| 235 | community_id: self.community_id, | 202 | community_id: self.community_id, |
| 236 | user_id: me.id, | 203 | user_id: me.id, |
| @@ -245,16 +212,16 @@ impl Handle for ListCommunities { | |||
| 245 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Community>, ServerError> { | 212 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Community>, ServerError> { |
| 246 | let me = me.user()?; | 213 | let me = me.user()?; |
| 247 | 214 | ||
| 248 | - community::communities_of(&me.id, &cx.db).await | 215 | + db::community::communities_of(me.id, cx.db).await |
| 249 | } | 216 | } |
| 250 | } | 217 | } |
| 251 | 218 | ||
| 252 | impl Handle for ListMembers { | 219 | impl Handle for ListMembers { |
| 253 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Member>, ServerError> { | 220 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Member>, ServerError> { |
| 254 | let me = me.user()?; | 221 | let me = me.user()?; |
| 255 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 222 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 256 | 223 | ||
| 257 | - user_community::members(&self.community_id, &cx.db).await | 224 | + db::member::members(self.community_id, cx.db).await |
| 258 | } | 225 | } |
| 259 | } | 226 | } |
| 260 | 227 | ||
| @@ -291,14 +258,15 @@ impl Handle for BanMember { | |||
| 291 | impl Handle for Unban { | 258 | impl Handle for Unban { |
| 292 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 259 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 293 | let me = me.user()?; | 260 | let me = me.user()?; |
| 294 | - allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?; | 261 | + let db = cx.db; |
| 295 | - user_community::unban(&self.user_id, &self.community_id, &cx.db).await?; | 262 | + allowed(&me, self.community_id, db, permission::can_unban).await?; |
| 296 | - log::record( | 263 | + db::member::unban(self.user_id, self.community_id, db).await?; |
| 297 | - &self.community_id, | 264 | + db::log::record( |
| 298 | - Some(&me.id), | 265 | + self.community_id, |
| 299 | - Some(&self.user_id), | 266 | + Some(me.id), |
| 267 | + Some(self.user_id), | ||
| 300 | &LogAction::Unbanned, | 268 | &LogAction::Unbanned, |
| 301 | - &cx.db, | 269 | + db, |
| 302 | ) | 270 | ) |
| 303 | .await?; | 271 | .await?; |
| 304 | 272 | ||
| @@ -309,33 +277,34 @@ impl Handle for Unban { | |||
| 309 | impl Handle for ListBans { | 277 | impl Handle for ListBans { |
| 310 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Ban>, ServerError> { | 278 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Ban>, ServerError> { |
| 311 | let me = me.user()?; | 279 | let me = me.user()?; |
| 312 | - allowed(&me, &self.community_id, &cx.db, permission::can_unban).await?; | 280 | + allowed(&me, self.community_id, cx.db, permission::can_unban).await?; |
| 313 | 281 | ||
| 314 | - user_community::bans(&self.community_id, &cx.db).await | 282 | + db::member::bans(self.community_id, cx.db).await |
| 315 | } | 283 | } |
| 316 | } | 284 | } |
| 317 | 285 | ||
| 318 | impl Handle for SetRank { | 286 | impl Handle for SetRank { |
| 319 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 287 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 320 | let me = me.user()?; | 288 | let me = me.user()?; |
| 321 | - ensure_editable(&self.community_id, &cx.db).await?; | 289 | + let db = cx.db; |
| 322 | - let target = user::read(&self.user_id, &cx.db).await?; | 290 | + ensure_editable(self.community_id, db).await?; |
| 291 | + let target = db::user::read(self.user_id, db).await?; | ||
| 323 | ensure(permission::can_set_rank( | 292 | ensure(permission::can_set_rank( |
| 324 | - actor_rank(&me, &self.community_id, &cx.db).await?, | 293 | + actor_rank(&me, self.community_id, db).await?, |
| 325 | - actor_rank(&target, &self.community_id, &cx.db).await?, | 294 | + actor_rank(&target, self.community_id, db).await?, |
| 326 | self.rank, | 295 | self.rank, |
| 327 | ))?; | 296 | ))?; |
| 328 | - user_community::set_rank(&self.user_id, &self.community_id, self.rank, &cx.db).await?; | 297 | + db::member::set_rank(self.user_id, self.community_id, self.rank, db).await?; |
| 329 | - log::record( | 298 | + db::log::record( |
| 330 | - &self.community_id, | 299 | + self.community_id, |
| 331 | - Some(&me.id), | 300 | + Some(me.id), |
| 332 | - Some(&self.user_id), | 301 | + Some(self.user_id), |
| 333 | &LogAction::RankChanged { rank: self.rank }, | 302 | &LogAction::RankChanged { rank: self.rank }, |
| 334 | - &cx.db, | 303 | + db, |
| 335 | ) | 304 | ) |
| 336 | .await?; | 305 | .await?; |
| 337 | cx.emit( | 306 | cx.emit( |
| 338 | - To::Community(self.community_id.clone()), | 307 | + To::Community(self.community_id), |
| 339 | Event::RankChanged { | 308 | Event::RankChanged { |
| 340 | community_id: self.community_id, | 309 | community_id: self.community_id, |
| 341 | user_id: self.user_id, | 310 | user_id: self.user_id, |
| @@ -350,8 +319,8 @@ impl Handle for SetRank { | |||
| 350 | impl Handle for ListLogs { | 319 | impl Handle for ListLogs { |
| 351 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<LogEntry>, ServerError> { | 320 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<LogEntry>, ServerError> { |
| 352 | let me = me.user()?; | 321 | let me = me.user()?; |
| 353 | - allowed(&me, &self.community_id, &cx.db, permission::can_read_logs).await?; | 322 | + allowed(&me, self.community_id, cx.db, permission::can_read_logs).await?; |
| 354 | 323 | ||
| 355 | - log::list(&self.community_id, &cx.db).await | 324 | + db::log::list(self.community_id, cx.db).await |
| 356 | } | 325 | } |
| 357 | } | 326 | } |
crates/server/src/call/message.rsmodified+83 -90
| @@ -5,20 +5,17 @@ use common::{ | |||
| 5 | }, | 5 | }, |
| 6 | error::Error, | 6 | error::Error, |
| 7 | event::Event, | 7 | event::Event, |
| 8 | - model::{AdminAction, LogAction, Message, ServerSettings, Unread, User}, | 8 | + model::{AdminAction, Id, LogAction, Message, ServerSettings, Unread, User}, |
| 9 | permission, | 9 | permission, |
| 10 | validate::{validate_new_message, validate_vote}, | 10 | validate::{validate_new_message, validate_vote}, |
| 11 | }; | 11 | }; |
| 12 | 12 | ||
| 13 | use crate::{ | 13 | use crate::{ |
| 14 | - admin_log, | ||
| 15 | call::{Cx, Handle, Me}, | 14 | call::{Cx, Handle, Me}, |
| 16 | - community, | 15 | + db::{self, community::Kind, message::ForwardMode}, |
| 17 | - error::ServerError, | 16 | + error::{ServerError, ensure, ensure_with}, |
| 18 | - log, message, | ||
| 19 | publish::To, | 17 | publish::To, |
| 20 | - request::{actor_rank, allowed, ensure, is_outsider, message_event}, | 18 | + request::{actor_rank, allowed, is_outsider, message_event}, |
| 21 | - server_settings, stats, user, user_community, | ||
| 22 | }; | 19 | }; |
| 23 | 20 | ||
| 24 | fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(), ServerError> { | 21 | 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<( | |||
| 30 | .sh | 27 | .sh |
| 31 | .services | 28 | .services |
| 32 | .rate_limit | 29 | .rate_limit |
| 33 | - .allow(&me.id, settings.messages_per_minute)?) | 30 | + .allow(&me.id.to_string(), settings.messages_per_minute)?) |
| 34 | } | 31 | } |
| 35 | 32 | ||
| 36 | impl Handle for CreateMessage { | 33 | impl Handle for CreateMessage { |
| 37 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> { | 34 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> { |
| 38 | let me = me.user()?; | 35 | let me = me.user()?; |
| 39 | - let settings = server_settings::read(&cx.db).await?; | 36 | + let settings = db::settings::read(cx.db).await?; |
| 40 | limit_messages(&me, &settings, cx)?; | 37 | limit_messages(&me, &settings, cx)?; |
| 41 | validate_new_message( | 38 | validate_new_message( |
| 42 | &self.body, | 39 | &self.body, |
| 43 | self.attachments.len(), | 40 | self.attachments.len(), |
| 44 | settings.max_message_length as usize, | 41 | settings.max_message_length as usize, |
| 45 | )?; | 42 | )?; |
| 46 | - allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; | 43 | + allowed(&me, self.community_id, cx.db, permission::can_post).await?; |
| 47 | - let tx = cx.db.transaction().await?; | 44 | + if let Some(reply_to) = self.reply_to { |
| 48 | - let created = message::create( | 45 | + ensure_with( |
| 49 | - &me.id, | 46 | + db::message::community_of(reply_to, cx.db).await? == self.community_id, |
| 50 | - &self.community_id, | 47 | + Error::NotFound, |
| 48 | + )?; | ||
| 49 | + } | ||
| 50 | + let created = db::message::create( | ||
| 51 | + me.id, | ||
| 52 | + self.community_id, | ||
| 51 | &self.body, | 53 | &self.body, |
| 52 | &self.attachments, | 54 | &self.attachments, |
| 53 | - self.reply_to.as_deref(), | 55 | + self.reply_to, |
| 54 | - &tx, | 56 | + cx.db, |
| 55 | ) | 57 | ) |
| 56 | .await?; | 58 | .await?; |
| 57 | - stats::mark_active(&me.id, &tx).await?; | 59 | + db::stats::mark_active(me.id, cx.db).await?; |
| 58 | - tx.commit().await?; | ||
| 59 | cx.out.push(message_event(&created, Event::MessageCreated)); | 60 | cx.out.push(message_event(&created, Event::MessageCreated)); |
| 60 | 61 | ||
| 61 | Ok(created) | 62 | Ok(created) |
| @@ -65,34 +66,24 @@ impl Handle for CreateMessage { | |||
| 65 | impl Handle for ForwardMessages { | 66 | impl Handle for ForwardMessages { |
| 66 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> { | 67 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> { |
| 67 | let me = me.user()?; | 68 | let me = me.user()?; |
| 68 | - limit_messages(&me, &server_settings::read(&cx.db).await?, cx)?; | 69 | + limit_messages(&me, &db::settings::read(cx.db).await?, cx)?; |
| 69 | ensure(permission::can_post( | 70 | ensure(permission::can_post( |
| 70 | - actor_rank(&me, &self.community_id, &cx.db).await?, | 71 | + actor_rank(&me, self.community_id, cx.db).await?, |
| 71 | ))?; | 72 | ))?; |
| 72 | - let tx = cx.db.transaction().await?; | ||
| 73 | let mut sources = Vec::new(); | 73 | let mut sources = Vec::new(); |
| 74 | for message_id in &self.message_ids { | 74 | for message_id in &self.message_ids { |
| 75 | - let source = message::read(message_id, &tx).await?; | 75 | + let source = db::message::read(*message_id, cx.db).await?; |
| 76 | ensure(permission::can_read( | 76 | ensure(permission::can_read( |
| 77 | - actor_rank(&me, &source.community_id, &tx).await?, | 77 | + actor_rank(&me, source.community_id, cx.db).await?, |
| 78 | ))?; | 78 | ))?; |
| 79 | sources.push(source); | 79 | sources.push(source); |
| 80 | } | 80 | } |
| 81 | let mode = if self.snippet { | 81 | let mode = if self.snippet { |
| 82 | - message::ForwardMode::Snippet | 82 | + ForwardMode::Snippet |
| 83 | } else { | 83 | } else { |
| 84 | - message::ForwardMode::Copy | 84 | + ForwardMode::Copy |
| 85 | }; | 85 | }; |
| 86 | - let created = message::forward( | 86 | + let created = db::message::forward(me.id, self.community_id, &sources, mode, cx.db).await?; |
| 87 | - &me, | ||
| 88 | - &self.community_id, | ||
| 89 | - &sources, | ||
| 90 | - mode, | ||
| 91 | - &cx.sh.directory, | ||
| 92 | - &tx, | ||
| 93 | - ) | ||
| 94 | - .await?; | ||
| 95 | - tx.commit().await?; | ||
| 96 | for message in &created { | 87 | for message in &created { |
| 97 | cx.out.push(message_event(message, Event::MessageCreated)); | 88 | cx.out.push(message_event(message, Event::MessageCreated)); |
| 98 | } | 89 | } |
| @@ -104,15 +95,15 @@ impl Handle for ForwardMessages { | |||
| 104 | impl Handle for UpdateMessage { | 95 | impl Handle for UpdateMessage { |
| 105 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> { | 96 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> { |
| 106 | let me = me.user()?; | 97 | let me = me.user()?; |
| 107 | - let existing = message::read(&self.message_id, &cx.db).await?; | 98 | + let existing = db::message::read(self.message_id, cx.db).await?; |
| 108 | - allowed(&me, &existing.community_id, &cx.db, permission::can_post).await?; | 99 | + allowed(&me, existing.community_id, cx.db, permission::can_post).await?; |
| 109 | ensure(existing.user_id == me.id)?; | 100 | ensure(existing.user_id == me.id)?; |
| 110 | validate_new_message( | 101 | validate_new_message( |
| 111 | &self.body, | 102 | &self.body, |
| 112 | 0, | 103 | 0, |
| 113 | - server_settings::read(&cx.db).await?.max_message_length as usize, | 104 | + db::settings::read(cx.db).await?.max_message_length as usize, |
| 114 | )?; | 105 | )?; |
| 115 | - let updated = message::update(&self.message_id, &self.body, &cx.db).await?; | 106 | + let updated = db::message::update(self.message_id, &self.body, cx.db).await?; |
| 116 | cx.out.push(message_event(&updated, Event::MessageUpdated)); | 107 | cx.out.push(message_event(&updated, Event::MessageUpdated)); |
| 117 | 108 | ||
| 118 | Ok(updated) | 109 | Ok(updated) |
| @@ -122,40 +113,40 @@ impl Handle for UpdateMessage { | |||
| 122 | impl Handle for DeleteMessage { | 113 | impl Handle for DeleteMessage { |
| 123 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 114 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 124 | let me = me.user()?; | 115 | let me = me.user()?; |
| 125 | - let existing = message::read(&self.message_id, &cx.db).await?; | 116 | + let existing = db::message::read(self.message_id, cx.db).await?; |
| 126 | - let author = user::read(&existing.user_id, &cx.db).await?; | 117 | + let author = db::user::read(existing.user_id, cx.db).await?; |
| 127 | ensure(permission::can_delete_message( | 118 | ensure(permission::can_delete_message( |
| 128 | - actor_rank(&me, &existing.community_id, &cx.db).await?, | 119 | + actor_rank(&me, existing.community_id, cx.db).await?, |
| 129 | - actor_rank(&author, &existing.community_id, &cx.db).await?, | 120 | + actor_rank(&author, existing.community_id, cx.db).await?, |
| 130 | existing.user_id == me.id, | 121 | existing.user_id == me.id, |
| 131 | ))?; | 122 | ))?; |
| 132 | - let deleted = message::delete(&self.message_id, &cx.db).await?; | 123 | + db::message::delete(existing.id, cx.db).await?; |
| 133 | if existing.user_id != me.id { | 124 | if existing.user_id != me.id { |
| 134 | - log::record( | 125 | + db::log::record( |
| 135 | - &deleted.community_id, | 126 | + existing.community_id, |
| 136 | - Some(&me.id), | 127 | + Some(me.id), |
| 137 | - Some(&existing.user_id), | 128 | + Some(existing.user_id), |
| 138 | &LogAction::MessageDeleted, | 129 | &LogAction::MessageDeleted, |
| 139 | - &cx.db, | 130 | + cx.db, |
| 140 | ) | 131 | ) |
| 141 | .await?; | 132 | .await?; |
| 142 | } | 133 | } |
| 143 | if permission::is_builder(me.role) && existing.user_id != me.id { | 134 | if permission::is_builder(me.role) && existing.user_id != me.id { |
| 144 | - let community = community::label(&deleted.community_id, &cx.db).await?; | 135 | + let community = db::community::label(existing.community_id, cx.db).await?; |
| 145 | - admin_log::record( | 136 | + db::log::record_admin( |
| 146 | - Some(&me.id), | 137 | + Some(me.id), |
| 147 | - Some(&existing.user_id), | 138 | + Some(existing.user_id), |
| 148 | Some(&community), | 139 | Some(&community), |
| 149 | &AdminAction::MessageDeleted, | 140 | &AdminAction::MessageDeleted, |
| 150 | - &cx.db, | 141 | + cx.db, |
| 151 | ) | 142 | ) |
| 152 | .await?; | 143 | .await?; |
| 153 | } | 144 | } |
| 154 | cx.emit( | 145 | cx.emit( |
| 155 | - To::Community(deleted.community_id.clone()), | 146 | + To::Community(existing.community_id), |
| 156 | Event::MessagesDeleted { | 147 | Event::MessagesDeleted { |
| 157 | - community_id: deleted.community_id, | 148 | + community_id: existing.community_id, |
| 158 | - ids: vec![deleted.id], | 149 | + ids: vec![existing.id], |
| 159 | }, | 150 | }, |
| 160 | ); | 151 | ); |
| 161 | 152 | ||
| @@ -166,21 +157,19 @@ impl Handle for DeleteMessage { | |||
| 166 | impl Handle for CreatePoll { | 157 | impl Handle for CreatePoll { |
| 167 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> { | 158 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Message, ServerError> { |
| 168 | let me = me.user()?; | 159 | let me = me.user()?; |
| 169 | - let settings = server_settings::read(&cx.db).await?; | 160 | + let settings = db::settings::read(cx.db).await?; |
| 170 | limit_messages(&me, &settings, cx)?; | 161 | limit_messages(&me, &settings, cx)?; |
| 171 | - allowed(&me, &self.community_id, &cx.db, permission::can_post).await?; | 162 | + allowed(&me, self.community_id, cx.db, permission::can_post).await?; |
| 172 | - let tx = cx.db.transaction().await?; | 163 | + let created = db::message::create_poll( |
| 173 | - let created = message::create_poll( | 164 | + me.id, |
| 174 | - &me.id, | 165 | + self.community_id, |
| 175 | - &self.community_id, | ||
| 176 | &self.question, | 166 | &self.question, |
| 177 | &self.options, | 167 | &self.options, |
| 178 | self.multiple, | 168 | self.multiple, |
| 179 | - &tx, | 169 | + cx.db, |
| 180 | ) | 170 | ) |
| 181 | .await?; | 171 | .await?; |
| 182 | - stats::mark_active(&me.id, &tx).await?; | 172 | + db::stats::mark_active(me.id, cx.db).await?; |
| 183 | - tx.commit().await?; | ||
| 184 | cx.out.push(message_event(&created, Event::MessageCreated)); | 173 | cx.out.push(message_event(&created, Event::MessageCreated)); |
| 185 | 174 | ||
| 186 | Ok(created) | 175 | Ok(created) |
| @@ -190,13 +179,13 @@ impl Handle for CreatePoll { | |||
| 190 | impl Handle for Vote { | 179 | impl Handle for Vote { |
| 191 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 180 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 192 | let me = me.user()?; | 181 | let me = me.user()?; |
| 193 | - let existing = message::read(&self.message_id, &cx.db).await?; | 182 | + let existing = db::message::read(self.message_id, cx.db).await?; |
| 194 | ensure(permission::can_read( | 183 | ensure(permission::can_read( |
| 195 | - actor_rank(&me, &existing.community_id, &cx.db).await?, | 184 | + actor_rank(&me, existing.community_id, cx.db).await?, |
| 196 | ))?; | 185 | ))?; |
| 197 | let poll = existing.poll.as_ref().ok_or(Error::NotFound)?; | 186 | let poll = existing.poll.as_ref().ok_or(Error::NotFound)?; |
| 198 | validate_vote(poll, &self.positions)?; | 187 | validate_vote(poll, &self.positions)?; |
| 199 | - let updated = message::vote(&self.message_id, &me.id, &self.positions, &cx.db).await?; | 188 | + let updated = db::message::vote(self.message_id, me.id, &self.positions, cx.db).await?; |
| 200 | cx.out.push(message_event(&updated, Event::MessageUpdated)); | 189 | cx.out.push(message_event(&updated, Event::MessageUpdated)); |
| 201 | 190 | ||
| 202 | Ok(()) | 191 | Ok(()) |
| @@ -206,12 +195,12 @@ impl Handle for Vote { | |||
| 206 | impl Handle for ClosePoll { | 195 | impl Handle for ClosePoll { |
| 207 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 196 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 208 | let me = me.user()?; | 197 | let me = me.user()?; |
| 209 | - let existing = message::read(&self.message_id, &cx.db).await?; | 198 | + let existing = db::message::read(self.message_id, cx.db).await?; |
| 210 | ensure(permission::can_close_poll( | 199 | ensure(permission::can_close_poll( |
| 211 | - actor_rank(&me, &existing.community_id, &cx.db).await?, | 200 | + actor_rank(&me, existing.community_id, cx.db).await?, |
| 212 | existing.user_id == me.id, | 201 | existing.user_id == me.id, |
| 213 | ))?; | 202 | ))?; |
| 214 | - let updated = message::close_poll(&self.message_id, &cx.db).await?; | 203 | + let updated = db::message::close_poll(self.message_id, cx.db).await?; |
| 215 | cx.out.push(message_event(&updated, Event::MessageUpdated)); | 204 | cx.out.push(message_event(&updated, Event::MessageUpdated)); |
| 216 | 205 | ||
| 217 | Ok(()) | 206 | Ok(()) |
| @@ -221,11 +210,11 @@ impl Handle for ClosePoll { | |||
| 221 | impl Handle for React { | 210 | impl Handle for React { |
| 222 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 211 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 223 | let me = me.user()?; | 212 | let me = me.user()?; |
| 224 | - let existing = message::read(&self.message_id, &cx.db).await?; | 213 | + let existing = db::message::read(self.message_id, cx.db).await?; |
| 225 | ensure(permission::can_read( | 214 | ensure(permission::can_read( |
| 226 | - actor_rank(&me, &existing.community_id, &cx.db).await?, | 215 | + actor_rank(&me, existing.community_id, cx.db).await?, |
| 227 | ))?; | 216 | ))?; |
| 228 | - let updated = message::react(&self.message_id, &me.id, &self.emoji, &cx.db).await?; | 217 | + let updated = db::message::react(self.message_id, me.id, &self.emoji, cx.db).await?; |
| 229 | cx.out.push(message_event(&updated, Event::MessageUpdated)); | 218 | cx.out.push(message_event(&updated, Event::MessageUpdated)); |
| 230 | 219 | ||
| 231 | Ok(()) | 220 | Ok(()) |
| @@ -235,13 +224,14 @@ impl Handle for React { | |||
| 235 | impl Handle for Pin { | 224 | impl Handle for Pin { |
| 236 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 225 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 237 | let me = me.user()?; | 226 | let me = me.user()?; |
| 238 | - let existing = message::read(&self.message_id, &cx.db).await?; | 227 | + let existing = db::message::read(self.message_id, cx.db).await?; |
| 239 | - let direct = community::is_direct(&existing.community_id, &cx.db).await?; | 228 | + let direct = |
| 229 | + db::community::kind_of(existing.community_id, cx.db).await? == Some(Kind::Direct); | ||
| 240 | ensure(permission::can_pin( | 230 | ensure(permission::can_pin( |
| 241 | - actor_rank(&me, &existing.community_id, &cx.db).await?, | 231 | + actor_rank(&me, existing.community_id, cx.db).await?, |
| 242 | direct, | 232 | direct, |
| 243 | ))?; | 233 | ))?; |
| 244 | - let updated = message::pin(&self.message_id, self.pinned, &cx.db).await?; | 234 | + let updated = db::message::pin(self.message_id, self.pinned, cx.db).await?; |
| 245 | cx.out.push(message_event(&updated, Event::MessageUpdated)); | 235 | cx.out.push(message_event(&updated, Event::MessageUpdated)); |
| 246 | 236 | ||
| 247 | Ok(()) | 237 | Ok(()) |
| @@ -251,18 +241,18 @@ impl Handle for Pin { | |||
| 251 | impl Handle for ListPins { | 241 | impl Handle for ListPins { |
| 252 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> { | 242 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> { |
| 253 | let me = me.user()?; | 243 | let me = me.user()?; |
| 254 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 244 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 255 | 245 | ||
| 256 | - message::pinned(&self.community_id, &cx.db).await | 246 | + db::message::pinned(self.community_id, cx.db).await |
| 257 | } | 247 | } |
| 258 | } | 248 | } |
| 259 | 249 | ||
| 260 | impl Handle for ListMessages { | 250 | impl Handle for ListMessages { |
| 261 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> { | 251 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Message>, ServerError> { |
| 262 | let me = me.user()?; | 252 | let me = me.user()?; |
| 263 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 253 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 264 | 254 | ||
| 265 | - message::read_page(&self.community_id, self.before.as_deref(), &cx.db).await | 255 | + db::message::read_page(self.community_id, self.before, cx.db).await |
| 266 | } | 256 | } |
| 267 | } | 257 | } |
| 268 | 258 | ||
| @@ -270,16 +260,19 @@ impl Handle for ListUnreads { | |||
| 270 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Unread>, ServerError> { | 260 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Unread>, ServerError> { |
| 271 | let me = me.user()?; | 261 | let me = me.user()?; |
| 272 | 262 | ||
| 273 | - user_community::unreads(&me.id, &me.username, &cx.db).await | 263 | + db::member::unreads(me.id, &me.username, cx.db).await |
| 274 | } | 264 | } |
| 275 | } | 265 | } |
| 276 | 266 | ||
| 277 | impl Handle for MarkRead { | 267 | impl Handle for MarkRead { |
| 278 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 268 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 279 | let me = me.user()?; | 269 | let me = me.user()?; |
| 280 | - ensure(!is_outsider(&me.id, &self.community_id, &cx.db).await?)?; | 270 | + ensure(!is_outsider(me.id, self.community_id, cx.db).await?)?; |
| 281 | - message::ensure_in_community(&self.message_id, &self.community_id, &cx.db).await?; | 271 | + ensure_with( |
| 282 | - user_community::mark_read(&me.id, &self.community_id, &self.message_id, &cx.db).await?; | 272 | + db::message::community_of(self.message_id, cx.db).await? == self.community_id, |
| 273 | + Error::NotFound, | ||
| 274 | + )?; | ||
| 275 | + db::member::mark_read(me.id, self.community_id, self.message_id, cx.db).await?; | ||
| 283 | 276 | ||
| 284 | Ok(()) | 277 | Ok(()) |
| 285 | } | 278 | } |
| @@ -288,11 +281,11 @@ impl Handle for MarkRead { | |||
| 288 | impl Handle for Typing { | 281 | impl Handle for Typing { |
| 289 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 282 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 290 | let me = me.user()?; | 283 | let me = me.user()?; |
| 291 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 284 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 292 | - if user::is_ghost(&me.id, &cx.db).await? { | 285 | + if db::user::is_ghost(me.id, cx.db).await? { |
| 293 | return Ok(()); | 286 | return Ok(()); |
| 294 | } | 287 | } |
| 295 | - let others: Vec<String> = user_community::member_ids(&self.community_id, &cx.db) | 288 | + let others: Vec<Id> = db::member::member_ids(self.community_id, cx.db) |
| 296 | .await? | 289 | .await? |
| 297 | .into_iter() | 290 | .into_iter() |
| 298 | .filter(|user_id| *user_id != me.id) | 291 | .filter(|user_id| *user_id != me.id) |
crates/server/src/call/mod.rsmodified+21 -14
| @@ -8,32 +8,32 @@ mod voice; | |||
| 8 | use std::{future::Future, sync::Arc}; | 8 | use std::{future::Future, sync::Arc}; |
| 9 | 9 | ||
| 10 | use common::{ | 10 | use common::{ |
| 11 | - call::{Call, Gate, Request}, | 11 | + call::{Call, Gate, Login, Register, Request}, |
| 12 | error::Error, | 12 | error::Error, |
| 13 | event::Event, | 13 | event::Event, |
| 14 | frame::{self, DOWN_MAX}, | 14 | frame::{self, DOWN_MAX}, |
| 15 | model::User, | 15 | model::User, |
| 16 | permission, | 16 | permission, |
| 17 | }; | 17 | }; |
| 18 | -use turso::Connection; | ||
| 19 | 18 | ||
| 20 | use crate::{ | 19 | use crate::{ |
| 21 | - error::ServerError, | 20 | + db::{self, Connection}, |
| 21 | + error::{ServerError, ensure}, | ||
| 22 | hub::Client, | 22 | hub::Client, |
| 23 | network::Shared, | 23 | network::Shared, |
| 24 | - publish::{Broadcast, To, publish}, | 24 | + publish::{Broadcast, To}, |
| 25 | request, | 25 | request, |
| 26 | }; | 26 | }; |
| 27 | 27 | ||
| 28 | pub(crate) struct Cx<'a> { | 28 | pub(crate) struct Cx<'a> { |
| 29 | pub client: &'a Arc<Client>, | 29 | pub client: &'a Arc<Client>, |
| 30 | pub sh: &'a Shared, | 30 | pub sh: &'a Shared, |
| 31 | - pub db: Connection, | 31 | + pub db: &'a Connection, |
| 32 | pub out: Vec<Broadcast>, | 32 | pub out: Vec<Broadcast>, |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | impl<'a> Cx<'a> { | 35 | impl<'a> Cx<'a> { |
| 36 | - pub(crate) fn new(client: &'a Arc<Client>, sh: &'a Shared, db: Connection) -> Self { | 36 | + pub(crate) fn new(client: &'a Arc<Client>, sh: &'a Shared, db: &'a Connection) -> Self { |
| 37 | Self { | 37 | Self { |
| 38 | client, | 38 | client, |
| 39 | sh, | 39 | sh, |
| @@ -72,10 +72,10 @@ pub(crate) trait Handle: Call { | |||
| 72 | async fn gate(gate: Gate, cx: &Cx<'_>) -> Result<Me, ServerError> { | 72 | async fn gate(gate: Gate, cx: &Cx<'_>) -> Result<Me, ServerError> { |
| 73 | match gate { | 73 | match gate { |
| 74 | Gate::Guest => Ok(Me::Guest), | 74 | Gate::Guest => Ok(Me::Guest), |
| 75 | - Gate::User => Ok(Me::User(request::authenticated(cx.client, &cx.db).await?)), | 75 | + Gate::User => Ok(Me::User(request::authenticated(cx.client, cx.db).await?)), |
| 76 | Gate::Builder => { | 76 | Gate::Builder => { |
| 77 | - let user = request::authenticated(cx.client, &cx.db).await?; | 77 | + let user = request::authenticated(cx.client, cx.db).await?; |
| 78 | - request::ensure(permission::is_builder(user.role))?; | 78 | + ensure(permission::is_builder(user.role))?; |
| 79 | 79 | ||
| 80 | Ok(Me::User(user)) | 80 | Ok(Me::User(user)) |
| 81 | } | 81 | } |
| @@ -83,14 +83,21 @@ async fn gate(gate: Gate, cx: &Cx<'_>) -> Result<Me, ServerError> { | |||
| 83 | } | 83 | } |
| 84 | 84 | ||
| 85 | async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> { | 85 | async fn serve<C: Handle>(call: C, cx: &mut Cx<'_>) -> Vec<u8> { |
| 86 | - let reply = async { | 86 | + let db = cx.db; |
| 87 | + let reply = db::atomic(db, async { | ||
| 87 | call.validate()?; | 88 | call.validate()?; |
| 88 | let me = gate(C::GATE, cx).await?; | 89 | let me = gate(C::GATE, cx).await?; |
| 89 | call.handle(me, cx).await | 90 | call.handle(me, cx).await |
| 90 | - } | 91 | + }) |
| 91 | .await; | 92 | .await; |
| 92 | - publish(cx.sh, std::mem::take(&mut cx.out)).await; | 93 | + if reply.is_err() { |
| 94 | + cx.out.clear(); | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + encode::<C>(reply) | ||
| 98 | +} | ||
| 93 | 99 | ||
| 100 | +pub(crate) fn encode<C: Call>(reply: Result<C::Reply, ServerError>) -> Vec<u8> { | ||
| 94 | let reply = reply.map_err(Error::from); | 101 | let reply = reply.map_err(Error::from); |
| 95 | frame::encode(&reply, DOWN_MAX).unwrap_or_else(|_| { | 102 | frame::encode(&reply, DOWN_MAX).unwrap_or_else(|_| { |
| 96 | frame::encode(&Err::<C::Reply, Error>(Error::Server), DOWN_MAX).expect("small") | 103 | frame::encode(&Err::<C::Reply, Error>(Error::Server), DOWN_MAX).expect("small") |
| @@ -166,8 +173,8 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec<u8> { | |||
| 166 | Request::ListVoiceRooms(call) => serve(call, cx).await, | 173 | Request::ListVoiceRooms(call) => serve(call, cx).await, |
| 167 | Request::KickFromVoice(call) => serve(call, cx).await, | 174 | Request::KickFromVoice(call) => serve(call, cx).await, |
| 168 | Request::ServerMute(call) => serve(call, cx).await, | 175 | Request::ServerMute(call) => serve(call, cx).await, |
| 169 | - Request::Register(call) => serve(call, cx).await, | 176 | + Request::Register(_) => encode::<Register>(Err(Error::Server.into())), |
| 170 | - Request::Login(call) => serve(call, cx).await, | 177 | + Request::Login(_) => encode::<Login>(Err(Error::Server.into())), |
| 171 | Request::Logout(call) => serve(call, cx).await, | 178 | Request::Logout(call) => serve(call, cx).await, |
| 172 | Request::DeleteUser(call) => serve(call, cx).await, | 179 | Request::DeleteUser(call) => serve(call, cx).await, |
| 173 | Request::WatchCommunity(call) => serve(call, cx).await, | 180 | Request::WatchCommunity(call) => serve(call, cx).await, |
crates/server/src/call/social.rsmodified+82 -88
| @@ -7,36 +7,32 @@ use common::{ | |||
| 7 | error::Error, | 7 | error::Error, |
| 8 | event::Event, | 8 | event::Event, |
| 9 | model::{ | 9 | model::{ |
| 10 | - AdminAction, Community, Friends, Invitation, LogAction, Member, Rank, Report, ReportStatus, | 10 | + AdminAction, Community, Friends, Id, Invitation, LogAction, Member, Rank, Report, |
| 11 | - User, | 11 | + ReportStatus, User, |
| 12 | }, | 12 | }, |
| 13 | permission, | 13 | permission, |
| 14 | }; | 14 | }; |
| 15 | 15 | ||
| 16 | use crate::{ | 16 | use crate::{ |
| 17 | - admin_log, | ||
| 18 | call::{Cx, Handle, Me}, | 17 | call::{Cx, Handle, Me}, |
| 19 | - community, direct, | 18 | + db::{self, direct::Opening, friend::FriendState}, |
| 20 | - error::ServerError, | 19 | + error::{ServerError, ensure, ensure_with}, |
| 21 | - friend, invitation, log, message, notes, | ||
| 22 | publish::To, | 20 | publish::To, |
| 23 | - report, | 21 | + request::{actor_rank, allowed, ensure_editable}, |
| 24 | - request::{actor_rank, allowed, ensure, ensure_editable, ensure_with}, | ||
| 25 | - user, user_community, | ||
| 26 | }; | 22 | }; |
| 27 | 23 | ||
| 28 | -async fn friends_updated(user_ids: [&str; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> { | 24 | +async fn friends_updated(user_ids: [Id; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 29 | for user_id in user_ids { | 25 | for user_id in user_ids { |
| 30 | - let event = Event::FriendsUpdated(friend::state(user_id, &cx.db).await?); | 26 | + let event = Event::FriendsUpdated(db::friend::state(user_id, cx.db).await?); |
| 31 | - cx.emit(To::User(user_id.to_string()), event); | 27 | + cx.emit(To::User(user_id), event); |
| 32 | } | 28 | } |
| 33 | 29 | ||
| 34 | Ok(()) | 30 | Ok(()) |
| 35 | } | 31 | } |
| 36 | 32 | ||
| 37 | -async fn invitations_updated(user_id: &str, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 33 | +async fn invitations_updated(user_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 38 | - let event = Event::InvitationsUpdated(invitation::of(user_id, &cx.db).await?); | 34 | + let event = Event::InvitationsUpdated(db::invitation::of(user_id, cx.db).await?); |
| 39 | - cx.emit(To::User(user_id.to_string()), event); | 35 | + cx.emit(To::User(user_id), event); |
| 40 | 36 | ||
| 41 | Ok(()) | 37 | Ok(()) |
| 42 | } | 38 | } |
| @@ -45,7 +41,7 @@ impl Handle for FindUser { | |||
| 45 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 41 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 46 | let me = me.user()?; | 42 | let me = me.user()?; |
| 47 | 43 | ||
| 48 | - user::by_username(&self.username, &cx.db) | 44 | + db::user::by_username(&self.username, cx.db) |
| 49 | .await? | 45 | .await? |
| 50 | .filter(|found| found.id != me.id) | 46 | .filter(|found| found.id != me.id) |
| 51 | .ok_or(Error::NotFound.into()) | 47 | .ok_or(Error::NotFound.into()) |
| @@ -55,14 +51,15 @@ impl Handle for FindUser { | |||
| 55 | impl Handle for OpenDirect { | 51 | impl Handle for OpenDirect { |
| 56 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 52 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 57 | let me = me.user()?; | 53 | let me = me.user()?; |
| 58 | - match direct::open(&me.id, &self.user_id, &mut cx.db).await? { | 54 | + ensure(me.id != self.user_id)?; |
| 59 | - direct::Opening::Created(community) => { | 55 | + match db::direct::open(me.id, self.user_id, cx.db).await? { |
| 60 | - let peer_view = community::read(&community.id, &self.user_id, &cx.db).await?; | 56 | + Opening::Created(community) => { |
| 57 | + let peer_view = db::community::read(community.id, self.user_id, cx.db).await?; | ||
| 61 | cx.emit(To::User(self.user_id), Event::CommunityAdded(peer_view)); | 58 | cx.emit(To::User(self.user_id), Event::CommunityAdded(peer_view)); |
| 62 | 59 | ||
| 63 | Ok(community) | 60 | Ok(community) |
| 64 | } | 61 | } |
| 65 | - direct::Opening::Existing(community) => Ok(community), | 62 | + Opening::Existing(community) => Ok(community), |
| 66 | } | 63 | } |
| 67 | } | 64 | } |
| 68 | } | 65 | } |
| @@ -70,8 +67,9 @@ impl Handle for OpenDirect { | |||
| 70 | impl Handle for OpenNotes { | 67 | impl Handle for OpenNotes { |
| 71 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 68 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 72 | let me = me.user()?; | 69 | let me = me.user()?; |
| 73 | - | 70 | + match db::direct::open(me.id, me.id, cx.db).await? { |
| 74 | - notes::open(&me.id, &mut cx.db).await | 71 | + Opening::Created(community) | Opening::Existing(community) => Ok(community), |
| 72 | + } | ||
| 75 | } | 73 | } |
| 76 | } | 74 | } |
| 77 | 75 | ||
| @@ -79,65 +77,75 @@ impl Handle for ListFriends { | |||
| 79 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Friends, ServerError> { | 77 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Friends, ServerError> { |
| 80 | let me = me.user()?; | 78 | let me = me.user()?; |
| 81 | 79 | ||
| 82 | - friend::state(&me.id, &cx.db).await | 80 | + db::friend::state(me.id, cx.db).await |
| 83 | } | 81 | } |
| 84 | } | 82 | } |
| 85 | 83 | ||
| 86 | impl Handle for AddFriend { | 84 | impl Handle for AddFriend { |
| 87 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 85 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 88 | let me = me.user()?; | 86 | let me = me.user()?; |
| 89 | - friend::add(&me.id, &self.user_id, &mut cx.db).await?; | 87 | + let db = cx.db; |
| 88 | + ensure_with(me.id != self.user_id, Error::Forbidden)?; | ||
| 89 | + ensure_with( | ||
| 90 | + db::friend::pair(me.id, self.user_id, db).await?.is_none(), | ||
| 91 | + Error::Taken, | ||
| 92 | + )?; | ||
| 93 | + match db::friend::pair(self.user_id, me.id, db).await? { | ||
| 94 | + Some(FriendState::Requested) => db::friend::accept(me.id, self.user_id, db).await?, | ||
| 95 | + _ => db::friend::request(me.id, self.user_id, db).await?, | ||
| 96 | + } | ||
| 90 | 97 | ||
| 91 | - friends_updated([&me.id, &self.user_id], cx).await | 98 | + friends_updated([me.id, self.user_id], cx).await |
| 92 | } | 99 | } |
| 93 | } | 100 | } |
| 94 | 101 | ||
| 95 | impl Handle for AcceptFriend { | 102 | impl Handle for AcceptFriend { |
| 96 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 103 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 97 | let me = me.user()?; | 104 | let me = me.user()?; |
| 98 | - friend::accept(&me.id, &self.user_id, &mut cx.db).await?; | 105 | + db::friend::accept(me.id, self.user_id, cx.db).await?; |
| 99 | 106 | ||
| 100 | - friends_updated([&me.id, &self.user_id], cx).await | 107 | + friends_updated([me.id, self.user_id], cx).await |
| 101 | } | 108 | } |
| 102 | } | 109 | } |
| 103 | 110 | ||
| 104 | impl Handle for RemoveFriend { | 111 | impl Handle for RemoveFriend { |
| 105 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 112 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 106 | let me = me.user()?; | 113 | let me = me.user()?; |
| 107 | - friend::remove(&me.id, &self.user_id, &mut cx.db).await?; | 114 | + db::friend::remove(me.id, self.user_id, cx.db).await?; |
| 108 | 115 | ||
| 109 | - friends_updated([&me.id, &self.user_id], cx).await | 116 | + friends_updated([me.id, self.user_id], cx).await |
| 110 | } | 117 | } |
| 111 | } | 118 | } |
| 112 | 119 | ||
| 113 | impl Handle for Invite { | 120 | impl Handle for Invite { |
| 114 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 121 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 115 | let me = me.user()?; | 122 | let me = me.user()?; |
| 116 | - ensure_editable(&self.community_id, &cx.db).await?; | 123 | + let db = cx.db; |
| 117 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 124 | + ensure_editable(self.community_id, db).await?; |
| 118 | - let target = user::read(&self.user_id, &cx.db).await?; | 125 | + allowed(&me, self.community_id, db, permission::can_read).await?; |
| 119 | - if user_community::rank(&self.user_id, &self.community_id, &cx.db) | 126 | + let target = db::user::read(self.user_id, db).await?; |
| 127 | + if db::member::rank(self.user_id, self.community_id, db) | ||
| 120 | .await? | 128 | .await? |
| 121 | .is_some() | 129 | .is_some() |
| 122 | { | 130 | { |
| 123 | return Err(Error::AlreadyMember.into()); | 131 | return Err(Error::AlreadyMember.into()); |
| 124 | } | 132 | } |
| 125 | - let banned = user_community::is_banned(&self.user_id, &self.community_id, &cx.db).await?; | 133 | + let banned = db::member::is_banned(self.user_id, self.community_id, db).await?; |
| 126 | ensure(permission::can_join(target.role, banned))?; | 134 | ensure(permission::can_join(target.role, banned))?; |
| 127 | - if invitation::exists(&self.community_id, &self.user_id, &cx.db).await? { | 135 | + if db::invitation::exists(self.community_id, self.user_id, db).await? { |
| 128 | return Err(Error::AlreadyInvited.into()); | 136 | return Err(Error::AlreadyInvited.into()); |
| 129 | } | 137 | } |
| 130 | - invitation::insert(&self.community_id, &self.user_id, &me.id, &cx.db).await?; | 138 | + db::invitation::insert(self.community_id, self.user_id, me.id, db).await?; |
| 131 | - log::record( | 139 | + db::log::record( |
| 132 | - &self.community_id, | 140 | + self.community_id, |
| 133 | - Some(&me.id), | 141 | + Some(me.id), |
| 134 | - Some(&self.user_id), | 142 | + Some(self.user_id), |
| 135 | &LogAction::Invited, | 143 | &LogAction::Invited, |
| 136 | - &cx.db, | 144 | + db, |
| 137 | ) | 145 | ) |
| 138 | .await?; | 146 | .await?; |
| 139 | 147 | ||
| 140 | - invitations_updated(&self.user_id, cx).await | 148 | + invitations_updated(self.user_id, cx).await |
| 141 | } | 149 | } |
| 142 | } | 150 | } |
| 143 | 151 | ||
| @@ -145,37 +153,29 @@ impl Handle for ListInvitations { | |||
| 145 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Invitation>, ServerError> { | 153 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Invitation>, ServerError> { |
| 146 | let me = me.user()?; | 154 | let me = me.user()?; |
| 147 | 155 | ||
| 148 | - invitation::of(&me.id, &cx.db).await | 156 | + db::invitation::of(me.id, cx.db).await |
| 149 | } | 157 | } |
| 150 | } | 158 | } |
| 151 | 159 | ||
| 152 | impl Handle for AcceptInvitation { | 160 | impl Handle for AcceptInvitation { |
| 153 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { | 161 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Community, ServerError> { |
| 154 | let me = me.user()?; | 162 | let me = me.user()?; |
| 155 | - let tx = cx.db.transaction().await?; | 163 | + let db = cx.db; |
| 156 | - invitation::take(&self.community_id, &me.id, &tx).await?; | 164 | + db::invitation::take(self.community_id, me.id, db).await?; |
| 157 | - let banned = user_community::is_banned(&me.id, &self.community_id, &tx).await?; | 165 | + let banned = db::member::is_banned(me.id, self.community_id, db).await?; |
| 158 | ensure(permission::can_join(me.role, banned))?; | 166 | ensure(permission::can_join(me.role, banned))?; |
| 159 | - user_community::join(&me.id, &self.community_id, Rank::Member, &tx).await?; | 167 | + db::member::join(me.id, self.community_id, Rank::Member, db).await?; |
| 160 | - log::record( | 168 | + db::log::record(self.community_id, Some(me.id), None, &LogAction::Joined, db).await?; |
| 161 | - &self.community_id, | 169 | + let community = db::community::read(self.community_id, me.id, db).await?; |
| 162 | - Some(&me.id), | ||
| 163 | - None, | ||
| 164 | - &LogAction::Joined, | ||
| 165 | - &tx, | ||
| 166 | - ) | ||
| 167 | - .await?; | ||
| 168 | - let community = community::read(&self.community_id, &me.id, &tx).await?; | ||
| 169 | - tx.commit().await?; | ||
| 170 | let event = Event::MemberJoined { | 170 | let event = Event::MemberJoined { |
| 171 | - community_id: self.community_id.clone(), | 171 | + community_id: self.community_id, |
| 172 | member: Member { | 172 | member: Member { |
| 173 | user: me.clone(), | 173 | user: me.clone(), |
| 174 | rank: Rank::Member, | 174 | rank: Rank::Member, |
| 175 | }, | 175 | }, |
| 176 | }; | 176 | }; |
| 177 | cx.emit(To::Community(self.community_id), event); | 177 | cx.emit(To::Community(self.community_id), event); |
| 178 | - invitations_updated(&me.id, cx).await?; | 178 | + invitations_updated(me.id, cx).await?; |
| 179 | 179 | ||
| 180 | Ok(community) | 180 | Ok(community) |
| 181 | } | 181 | } |
| @@ -184,30 +184,31 @@ impl Handle for AcceptInvitation { | |||
| 184 | impl Handle for DeclineInvitation { | 184 | impl Handle for DeclineInvitation { |
| 185 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 185 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 186 | let me = me.user()?; | 186 | let me = me.user()?; |
| 187 | - invitation::take(&self.community_id, &me.id, &cx.db).await?; | 187 | + db::invitation::take(self.community_id, me.id, cx.db).await?; |
| 188 | 188 | ||
| 189 | - invitations_updated(&me.id, cx).await | 189 | + invitations_updated(me.id, cx).await |
| 190 | } | 190 | } |
| 191 | } | 191 | } |
| 192 | 192 | ||
| 193 | impl Handle for ReportMessage { | 193 | impl Handle for ReportMessage { |
| 194 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 194 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 195 | let me = me.user()?; | 195 | let me = me.user()?; |
| 196 | - let message = message::read(&self.message_id, &cx.db).await?; | 196 | + let db = cx.db; |
| 197 | - let actor = actor_rank(&me, &message.community_id, &cx.db).await?; | 197 | + let message = db::message::read(self.message_id, db).await?; |
| 198 | + let actor = actor_rank(&me, message.community_id, db).await?; | ||
| 198 | ensure(permission::can_read(actor) && me.id != message.user_id)?; | 199 | ensure(permission::can_read(actor) && me.id != message.user_id)?; |
| 199 | ensure_with( | 200 | ensure_with( |
| 200 | - !report::is_open(&me.id, &message.user_id, Some(&self.message_id), &cx.db).await?, | 201 | + !db::report::is_open(me.id, message.user_id, Some(self.message_id), db).await?, |
| 201 | Error::Taken, | 202 | Error::Taken, |
| 202 | )?; | 203 | )?; |
| 203 | - report::insert( | 204 | + db::report::insert( |
| 204 | - &me.id, | 205 | + me.id, |
| 205 | - &message.user_id, | 206 | + message.user_id, |
| 206 | - Some(&self.message_id), | 207 | + Some(self.message_id), |
| 207 | - Some(&message.community_id), | 208 | + Some(message.community_id), |
| 208 | Some(&message.body), | 209 | Some(&message.body), |
| 209 | &self.reason, | 210 | &self.reason, |
| 210 | - &cx.db, | 211 | + db, |
| 211 | ) | 212 | ) |
| 212 | .await?; | 213 | .await?; |
| 213 | cx.emit(To::Builders, Event::ReportCreated); | 214 | cx.emit(To::Builders, Event::ReportCreated); |
| @@ -219,22 +220,14 @@ impl Handle for ReportMessage { | |||
| 219 | impl Handle for ReportUser { | 220 | impl Handle for ReportUser { |
| 220 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 221 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 221 | let me = me.user()?; | 222 | let me = me.user()?; |
| 222 | - user::read(&self.user_id, &cx.db).await?; | 223 | + let db = cx.db; |
| 224 | + db::user::read(self.user_id, db).await?; | ||
| 223 | ensure(me.id != self.user_id)?; | 225 | ensure(me.id != self.user_id)?; |
| 224 | ensure_with( | 226 | ensure_with( |
| 225 | - !report::is_open(&me.id, &self.user_id, None, &cx.db).await?, | 227 | + !db::report::is_open(me.id, self.user_id, None, db).await?, |
| 226 | Error::Taken, | 228 | Error::Taken, |
| 227 | )?; | 229 | )?; |
| 228 | - report::insert( | 230 | + db::report::insert(me.id, self.user_id, None, None, None, &self.reason, db).await?; |
| 229 | - &me.id, | ||
| 230 | - &self.user_id, | ||
| 231 | - None, | ||
| 232 | - None, | ||
| 233 | - None, | ||
| 234 | - &self.reason, | ||
| 235 | - &cx.db, | ||
| 236 | - ) | ||
| 237 | - .await?; | ||
| 238 | cx.emit(To::Builders, Event::ReportCreated); | 231 | cx.emit(To::Builders, Event::ReportCreated); |
| 239 | 232 | ||
| 240 | Ok(()) | 233 | Ok(()) |
| @@ -243,23 +236,24 @@ impl Handle for ReportUser { | |||
| 243 | 236 | ||
| 244 | impl Handle for ListReports { | 237 | impl Handle for ListReports { |
| 245 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<Report>, ServerError> { | 238 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<Report>, ServerError> { |
| 246 | - report::list(self.status, &cx.db).await | 239 | + db::report::list(self.status, cx.db).await |
| 247 | } | 240 | } |
| 248 | } | 241 | } |
| 249 | 242 | ||
| 250 | impl Handle for HandleReport { | 243 | impl Handle for HandleReport { |
| 251 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 244 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 252 | let me = me.user()?; | 245 | let me = me.user()?; |
| 246 | + let db = cx.db; | ||
| 253 | ensure(permission::is_builder(me.role) && self.status != ReportStatus::Open)?; | 247 | ensure(permission::is_builder(me.role) && self.status != ReportStatus::Open)?; |
| 254 | - let target = report::handle(&self.report_id, self.status, &me.id, &cx.db).await?; | 248 | + let target = db::report::handle(self.report_id, self.status, me.id, db).await?; |
| 255 | - admin_log::record( | 249 | + db::log::record_admin( |
| 256 | - Some(&me.id), | 250 | + Some(me.id), |
| 257 | - target.as_deref(), | 251 | + target, |
| 258 | None, | 252 | None, |
| 259 | &AdminAction::ReportHandled { | 253 | &AdminAction::ReportHandled { |
| 260 | status: self.status, | 254 | status: self.status, |
| 261 | }, | 255 | }, |
| 262 | - &cx.db, | 256 | + db, |
| 263 | ) | 257 | ) |
| 264 | .await?; | 258 | .await?; |
| 265 | 259 | ||
crates/server/src/call/user.rsmodified+31 -30
| @@ -4,42 +4,40 @@ use common::{ | |||
| 4 | UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser, | 4 | UpdateAvatar, UpdatePresence, UpdateStatus, UpdateUser, |
| 5 | }, | 5 | }, |
| 6 | event::Event, | 6 | event::Event, |
| 7 | - model::{AdminAction, Presence, ServerSettings, SessionInfo, User}, | 7 | + model::{AdminAction, Id, Presence, ServerSettings, SessionInfo, User}, |
| 8 | validate::validate_avatar_size, | 8 | validate::validate_avatar_size, |
| 9 | }; | 9 | }; |
| 10 | 10 | ||
| 11 | use crate::{ | 11 | use crate::{ |
| 12 | - admin_log, authentication, | 12 | + authentication, |
| 13 | call::{Cx, Handle, Me}, | 13 | call::{Cx, Handle, Me}, |
| 14 | + db, | ||
| 14 | error::ServerError, | 15 | error::ServerError, |
| 16 | + files, | ||
| 15 | publish::{To, related_user_ids}, | 17 | publish::{To, related_user_ids}, |
| 16 | request::{effective_presence, managed, presence_changed}, | 18 | request::{effective_presence, managed, presence_changed}, |
| 17 | - server_settings, user, | ||
| 18 | }; | 19 | }; |
| 19 | 20 | ||
| 20 | pub(super) fn user_updated(user: &User, cx: &mut Cx<'_>) { | 21 | pub(super) fn user_updated(user: &User, cx: &mut Cx<'_>) { |
| 21 | - cx.emit( | 22 | + cx.emit(To::Related(user.id), Event::UserUpdated(user.clone())); |
| 22 | - To::Related(user.id.clone()), | ||
| 23 | - Event::UserUpdated(user.clone()), | ||
| 24 | - ); | ||
| 25 | } | 23 | } |
| 26 | 24 | ||
| 27 | impl Handle for GetSettings { | 25 | impl Handle for GetSettings { |
| 28 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> { | 26 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<ServerSettings, ServerError> { |
| 29 | - server_settings::read(&cx.db).await | 27 | + db::settings::read(cx.db).await |
| 30 | } | 28 | } |
| 31 | } | 29 | } |
| 32 | 30 | ||
| 33 | impl Handle for GetUser { | 31 | impl Handle for GetUser { |
| 34 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 32 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 35 | - user::read(&self.user_id, &cx.db).await | 33 | + db::user::read(self.user_id, cx.db).await |
| 36 | } | 34 | } |
| 37 | } | 35 | } |
| 38 | 36 | ||
| 39 | impl Handle for UpdateUser { | 37 | impl Handle for UpdateUser { |
| 40 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 38 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 41 | let me = me.user()?; | 39 | let me = me.user()?; |
| 42 | - let user = user::update(&me.id, &self.username, &cx.db).await?; | 40 | + let user = db::user::update(me.id, &self.username, cx.db).await?; |
| 43 | user_updated(&user, cx); | 41 | user_updated(&user, cx); |
| 44 | 42 | ||
| 45 | Ok(user) | 43 | Ok(user) |
| @@ -49,7 +47,7 @@ impl Handle for UpdateUser { | |||
| 49 | impl Handle for UpdateStatus { | 47 | impl Handle for UpdateStatus { |
| 50 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 48 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 51 | let me = me.user()?; | 49 | let me = me.user()?; |
| 52 | - let user = user::update_status(&me.id, &self.status, &cx.db).await?; | 50 | + let user = db::user::update_status(me.id, &self.status, cx.db).await?; |
| 53 | user_updated(&user, cx); | 51 | user_updated(&user, cx); |
| 54 | 52 | ||
| 55 | Ok(user) | 53 | Ok(user) |
| @@ -59,21 +57,21 @@ impl Handle for UpdateStatus { | |||
| 59 | impl Handle for UpdatePresence { | 57 | impl Handle for UpdatePresence { |
| 60 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 58 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 61 | let me = me.user()?; | 59 | let me = me.user()?; |
| 62 | - user::update_presence(&me.id, self.presence, &cx.db).await?; | 60 | + db::user::update_presence(me.id, self.presence, cx.db).await?; |
| 63 | cx.out | 61 | cx.out |
| 64 | - .extend(presence_changed(&cx.sh.services.hub, &me.id, &cx.db).await?); | 62 | + .extend(presence_changed(&cx.sh.services.hub, me.id, cx.db).await?); |
| 65 | 63 | ||
| 66 | Ok(()) | 64 | Ok(()) |
| 67 | } | 65 | } |
| 68 | } | 66 | } |
| 69 | 67 | ||
| 70 | impl Handle for ListPresences { | 68 | impl Handle for ListPresences { |
| 71 | - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<(String, Presence)>, ServerError> { | 69 | + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<(Id, Presence)>, ServerError> { |
| 72 | let me = me.user()?; | 70 | let me = me.user()?; |
| 73 | let hub = &cx.sh.services.hub; | 71 | let hub = &cx.sh.services.hub; |
| 74 | let mut presences = Vec::new(); | 72 | let mut presences = Vec::new(); |
| 75 | - for user_id in related_user_ids(&me.id, &cx.db).await? { | 73 | + for user_id in related_user_ids(me.id, cx.db).await? { |
| 76 | - let effective = effective_presence(hub, &user_id, &cx.db).await?; | 74 | + let effective = effective_presence(hub, user_id, cx.db).await?; |
| 77 | if effective != Presence::Offline || user_id == me.id { | 75 | if effective != Presence::Offline || user_id == me.id { |
| 78 | presences.push((user_id, effective)); | 76 | presences.push((user_id, effective)); |
| 79 | } | 77 | } |
| @@ -86,9 +84,11 @@ impl Handle for ListPresences { | |||
| 86 | impl Handle for UpdateAvatar { | 84 | impl Handle for UpdateAvatar { |
| 87 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 85 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 88 | let me = me.user()?; | 86 | let me = me.user()?; |
| 89 | - let maximum = server_settings::read(&cx.db).await?.max_avatar_bytes; | 87 | + let maximum = db::settings::read(cx.db).await?.max_avatar_bytes; |
| 90 | validate_avatar_size(&self.image, maximum)?; | 88 | validate_avatar_size(&self.image, maximum)?; |
| 91 | - let user = user::set_avatar(&me.id, Some(&self.image), &mut cx.db).await?; | 89 | + files::check_avatar(&self.image)?; |
| 90 | + db::avatar::set_user(me.id, Some(&self.image), cx.db).await?; | ||
| 91 | + let user = db::user::read(me.id, cx.db).await?; | ||
| 92 | user_updated(&user, cx); | 92 | user_updated(&user, cx); |
| 93 | 93 | ||
| 94 | Ok(user) | 94 | Ok(user) |
| @@ -98,7 +98,8 @@ impl Handle for UpdateAvatar { | |||
| 98 | impl Handle for RemoveAvatar { | 98 | impl Handle for RemoveAvatar { |
| 99 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { | 99 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<User, ServerError> { |
| 100 | let me = me.user()?; | 100 | let me = me.user()?; |
| 101 | - let user = user::set_avatar(&me.id, None, &mut cx.db).await?; | 101 | + db::avatar::set_user(me.id, None, cx.db).await?; |
| 102 | + let user = db::user::read(me.id, cx.db).await?; | ||
| 102 | user_updated(&user, cx); | 103 | user_updated(&user, cx); |
| 103 | 104 | ||
| 104 | Ok(user) | 105 | Ok(user) |
| @@ -107,38 +108,38 @@ impl Handle for RemoveAvatar { | |||
| 107 | 108 | ||
| 108 | impl Handle for GetAvatar { | 109 | impl Handle for GetAvatar { |
| 109 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<u8>, ServerError> { | 110 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<u8>, ServerError> { |
| 110 | - user::avatar(&self.avatar_id, &cx.db).await | 111 | + db::avatar::read(self.avatar_id, cx.db).await |
| 111 | } | 112 | } |
| 112 | } | 113 | } |
| 113 | 114 | ||
| 114 | impl Handle for ListSessions { | 115 | impl Handle for ListSessions { |
| 115 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<SessionInfo>, ServerError> { | 116 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<SessionInfo>, ServerError> { |
| 116 | let me = me.user()?; | 117 | let me = me.user()?; |
| 117 | - managed(&me, &self.user_id, &cx.db).await?; | 118 | + managed(&me, self.user_id, cx.db).await?; |
| 118 | 119 | ||
| 119 | - authentication::sessions(&self.user_id, &cx.db).await | 120 | + db::session::list(self.user_id, cx.db).await |
| 120 | } | 121 | } |
| 121 | } | 122 | } |
| 122 | 123 | ||
| 123 | impl Handle for RevokeSession { | 124 | impl Handle for RevokeSession { |
| 124 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 125 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 125 | let me = me.user()?; | 126 | let me = me.user()?; |
| 126 | - managed(&me, &self.user_id, &cx.db).await?; | 127 | + managed(&me, self.user_id, cx.db).await?; |
| 127 | authentication::revoke( | 128 | authentication::revoke( |
| 128 | &cx.sh.services.hub, | 129 | &cx.sh.services.hub, |
| 129 | authentication::Revoke::Session { | 130 | authentication::Revoke::Session { |
| 130 | - user_id: &self.user_id, | 131 | + user_id: self.user_id, |
| 131 | - session_id: &self.session_id, | 132 | + session_id: self.session_id, |
| 132 | }, | 133 | }, |
| 133 | - &cx.db, | 134 | + cx.db, |
| 134 | ) | 135 | ) |
| 135 | .await?; | 136 | .await?; |
| 136 | - admin_log::record( | 137 | + db::log::record_admin( |
| 137 | - Some(&me.id), | 138 | + Some(me.id), |
| 138 | - Some(&self.user_id), | 139 | + Some(self.user_id), |
| 139 | None, | 140 | None, |
| 140 | &AdminAction::SessionsRevoked, | 141 | &AdminAction::SessionsRevoked, |
| 141 | - &cx.db, | 142 | + cx.db, |
| 142 | ) | 143 | ) |
| 143 | .await?; | 144 | .await?; |
| 144 | 145 | ||
crates/server/src/call/voice.rsmodified+61 -59
| @@ -6,58 +6,57 @@ use common::{ | |||
| 6 | }, | 6 | }, |
| 7 | error::Error, | 7 | error::Error, |
| 8 | event::Event, | 8 | event::Event, |
| 9 | - model::{AdminAction, CallLog, VoiceRoom}, | 9 | + model::{AdminAction, CallLog, Id, VoiceRoom}, |
| 10 | permission, | 10 | permission, |
| 11 | share::Share, | 11 | share::Share, |
| 12 | }; | 12 | }; |
| 13 | 13 | ||
| 14 | use crate::{ | 14 | use crate::{ |
| 15 | - admin_log, | ||
| 16 | call::{Cx, Handle, Me}, | 15 | call::{Cx, Handle, Me}, |
| 17 | - community, | 16 | + db::{self, community::Kind}, |
| 18 | - error::ServerError, | 17 | + error::{ServerError, ensure}, |
| 19 | - message, | ||
| 20 | publish::To, | 18 | publish::To, |
| 21 | request::{ | 19 | request::{ |
| 22 | - allowed, departed, ensure, is_outsider, leave_user_voice, managed, message_event, | 20 | + allowed, departed, is_outsider, leave_user_voice, managed, message_event, share_ended, |
| 23 | - share_ended, voice_joined, voice_muted, | 21 | + voice_joined, voice_muted, |
| 24 | }, | 22 | }, |
| 25 | - user, | ||
| 26 | }; | 23 | }; |
| 27 | 24 | ||
| 28 | impl Handle for JoinVoice { | 25 | impl Handle for JoinVoice { |
| 29 | - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<String>, ServerError> { | 26 | + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Id>, ServerError> { |
| 30 | let me = me.user()?; | 27 | let me = me.user()?; |
| 31 | let community_id = self.community_id; | 28 | let community_id = self.community_id; |
| 32 | let rooms = &cx.sh.services.rooms; | 29 | let rooms = &cx.sh.services.rooms; |
| 33 | - allowed(&me, &community_id, &cx.db, permission::can_join_voice).await?; | 30 | + allowed(&me, community_id, cx.db, permission::can_join_voice).await?; |
| 34 | - ensure(community::kind(&community_id, &cx.db).await? != community::Kind::Notes)?; | 31 | + let kind = db::community::kind_of(community_id, cx.db) |
| 32 | + .await? | ||
| 33 | + .ok_or(Error::NotFound)?; | ||
| 34 | + ensure(kind != Kind::Notes)?; | ||
| 35 | ensure( | 35 | ensure( |
| 36 | permission::is_builder(me.role) | 36 | permission::is_builder(me.role) |
| 37 | - || community::voice_enabled(&community_id, &cx.db).await?, | 37 | + || db::community::voice_enabled(community_id, cx.db).await?, |
| 38 | )?; | 38 | )?; |
| 39 | - let muted = user::voice_muted(&me.id, &cx.db).await?; | 39 | + let muted = db::user::voice_muted(me.id, cx.db).await?; |
| 40 | - let outsider = is_outsider(&me.id, &community_id, &cx.db).await?; | 40 | + let outsider = is_outsider(me.id, community_id, cx.db).await?; |
| 41 | - let ghost = outsider || user::is_ghost(&me.id, &cx.db).await?; | 41 | + let ghost = outsider || db::user::is_ghost(me.id, cx.db).await?; |
| 42 | - let starts_call = !ghost | 42 | + let starts_call = |
| 43 | - && community::is_direct(&community_id, &cx.db).await? | 43 | + !ghost && kind == Kind::Direct && rooms.participants(community_id).is_empty(); |
| 44 | - && rooms.participants(&community_id).is_empty(); | 44 | + let joined = rooms.join(cx.client, community_id, muted, ghost)?; |
| 45 | - let joined = rooms.join(cx.client, &community_id, muted, ghost)?; | ||
| 46 | let mut broadcasts = match joined.departure { | 45 | let mut broadcasts = match joined.departure { |
| 47 | - Some(departure) => departed(departure, &cx.db).await?, | 46 | + Some(departure) => departed(departure, cx.db).await?, |
| 48 | None => Vec::new(), | 47 | None => Vec::new(), |
| 49 | }; | 48 | }; |
| 50 | if starts_call { | 49 | if starts_call { |
| 51 | let created = | 50 | let created = |
| 52 | - message::create_call_log(&community_id, &me.id, CallLog::Started, &cx.db).await?; | 51 | + db::message::create_call_log(community_id, me.id, CallLog::Started, cx.db).await?; |
| 53 | broadcasts.push(message_event(&created, Event::MessageCreated)); | 52 | broadcasts.push(message_event(&created, Event::MessageCreated)); |
| 54 | } | 53 | } |
| 55 | if !ghost && !joined.transferred { | 54 | if !ghost && !joined.transferred { |
| 56 | - broadcasts.extend(voice_joined(&community_id, &me.id, muted)); | 55 | + broadcasts.extend(voice_joined(community_id, me.id, muted)); |
| 57 | } | 56 | } |
| 58 | cx.out.extend(broadcasts); | 57 | cx.out.extend(broadcasts); |
| 59 | 58 | ||
| 60 | - Ok(rooms.participants(&community_id)) | 59 | + Ok(rooms.participants(community_id)) |
| 61 | } | 60 | } |
| 62 | } | 61 | } |
| 63 | 62 | ||
| @@ -65,7 +64,7 @@ impl Handle for LeaveVoice { | |||
| 65 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 64 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 66 | me.user()?; | 65 | me.user()?; |
| 67 | if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) { | 66 | if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) { |
| 68 | - cx.out.extend(departed(departure, &cx.db).await?); | 67 | + cx.out.extend(departed(departure, cx.db).await?); |
| 69 | } | 68 | } |
| 70 | 69 | ||
| 71 | Ok(()) | 70 | Ok(()) |
| @@ -79,13 +78,13 @@ impl Handle for StartShare { | |||
| 79 | let Some(community_id) = rooms.room_of_conn(cx.client.id) else { | 78 | let Some(community_id) = rooms.room_of_conn(cx.client.id) else { |
| 80 | return Err(Error::NotFound.into()); | 79 | return Err(Error::NotFound.into()); |
| 81 | }; | 80 | }; |
| 82 | - allowed(&me, &community_id, &cx.db, permission::can_share).await?; | 81 | + allowed(&me, community_id, cx.db, permission::can_share).await?; |
| 83 | ensure(!self.source.encode.is_empty())?; | 82 | ensure(!self.source.encode.is_empty())?; |
| 84 | - ensure(!user::is_ghost(&me.id, &cx.db).await?)?; | 83 | + ensure(!db::user::is_ghost(me.id, cx.db).await?)?; |
| 85 | let event = Event::ShareStarted { | 84 | let event = Event::ShareStarted { |
| 86 | - community_id: community_id.clone(), | 85 | + community_id, |
| 87 | share: Share { | 86 | share: Share { |
| 88 | - user_id: me.id.clone(), | 87 | + user_id: me.id, |
| 89 | kind: self.kind, | 88 | kind: self.kind, |
| 90 | source: self.source.clone(), | 89 | source: self.source.clone(), |
| 91 | }, | 90 | }, |
| @@ -104,7 +103,7 @@ impl Handle for StopShare { | |||
| 104 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 103 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 105 | let me = me.user()?; | 104 | let me = me.user()?; |
| 106 | if let Some(community_id) = cx.sh.services.rooms.stop_share(cx.client.id, self.kind) { | 105 | if let Some(community_id) = cx.sh.services.rooms.stop_share(cx.client.id, self.kind) { |
| 107 | - cx.out.push(share_ended(&community_id, &me.id, self.kind)); | 106 | + cx.out.push(share_ended(community_id, me.id, self.kind)); |
| 108 | } | 107 | } |
| 109 | 108 | ||
| 110 | Ok(()) | 109 | Ok(()) |
| @@ -114,9 +113,9 @@ impl Handle for StopShare { | |||
| 114 | impl Handle for ListShares { | 113 | impl Handle for ListShares { |
| 115 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Share>, ServerError> { | 114 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Share>, ServerError> { |
| 116 | let me = me.user()?; | 115 | let me = me.user()?; |
| 117 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 116 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 118 | 117 | ||
| 119 | - Ok(cx.sh.services.rooms.shares(&self.community_id)) | 118 | + Ok(cx.sh.services.rooms.shares(self.community_id)) |
| 120 | } | 119 | } |
| 121 | } | 120 | } |
| 122 | 121 | ||
| @@ -129,7 +128,7 @@ impl Handle for WatchShare { | |||
| 129 | .rooms | 128 | .rooms |
| 130 | .watch( | 129 | .watch( |
| 131 | cx.client.id, | 130 | cx.client.id, |
| 132 | - &self.user_id, | 131 | + self.user_id, |
| 133 | self.kind, | 132 | self.kind, |
| 134 | self.quality, | 133 | self.quality, |
| 135 | &self.decode, | 134 | &self.decode, |
| @@ -148,7 +147,7 @@ impl Handle for UnwatchShare { | |||
| 148 | cx.sh | 147 | cx.sh |
| 149 | .services | 148 | .services |
| 150 | .rooms | 149 | .rooms |
| 151 | - .unwatch(cx.client.id, &self.user_id, self.kind), | 150 | + .unwatch(cx.client.id, self.user_id, self.kind), |
| 152 | ); | 151 | ); |
| 153 | 152 | ||
| 154 | Ok(()) | 153 | Ok(()) |
| @@ -162,7 +161,7 @@ impl Handle for RequestKeyframe { | |||
| 162 | .sh | 161 | .sh |
| 163 | .services | 162 | .services |
| 164 | .rooms | 163 | .rooms |
| 165 | - .keyframe(cx.client.id, &self.user_id, self.kind) | 164 | + .keyframe(cx.client.id, self.user_id, self.kind) |
| 166 | .ok_or(Error::NotFound)?; | 165 | .ok_or(Error::NotFound)?; |
| 167 | cx.out.push(keyframe); | 166 | cx.out.push(keyframe); |
| 168 | 167 | ||
| @@ -175,13 +174,16 @@ impl Handle for DeclineCall { | |||
| 175 | let me = me.user()?; | 174 | let me = me.user()?; |
| 176 | let community_id = self.community_id; | 175 | let community_id = self.community_id; |
| 177 | let rooms = &cx.sh.services.rooms; | 176 | let rooms = &cx.sh.services.rooms; |
| 178 | - ensure(community::is_direct(&community_id, &cx.db).await?)?; | 177 | + let kind = db::community::kind_of(community_id, cx.db) |
| 179 | - allowed(&me, &community_id, &cx.db, permission::can_read).await?; | 178 | + .await? |
| 180 | - let participants = rooms.participants(&community_id); | 179 | + .ok_or(Error::NotFound)?; |
| 180 | + ensure(kind == Kind::Direct)?; | ||
| 181 | + allowed(&me, community_id, cx.db, permission::can_read).await?; | ||
| 182 | + let participants = rooms.participants(community_id); | ||
| 181 | ensure(!participants.is_empty() && !participants.contains(&me.id))?; | 183 | ensure(!participants.is_empty() && !participants.contains(&me.id))?; |
| 182 | - rooms.decline(&community_id); | 184 | + rooms.decline(community_id); |
| 183 | let created = | 185 | let created = |
| 184 | - message::create_call_log(&community_id, &me.id, CallLog::Declined, &cx.db).await?; | 186 | + db::message::create_call_log(community_id, me.id, CallLog::Declined, cx.db).await?; |
| 185 | cx.out.push(message_event(&created, Event::MessageCreated)); | 187 | cx.out.push(message_event(&created, Event::MessageCreated)); |
| 186 | 188 | ||
| 187 | Ok(()) | 189 | Ok(()) |
| @@ -189,11 +191,11 @@ impl Handle for DeclineCall { | |||
| 189 | } | 191 | } |
| 190 | 192 | ||
| 191 | impl Handle for ListVoiceParticipants { | 193 | impl Handle for ListVoiceParticipants { |
| 192 | - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<String>, ServerError> { | 194 | + async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<Vec<Id>, ServerError> { |
| 193 | let me = me.user()?; | 195 | let me = me.user()?; |
| 194 | - allowed(&me, &self.community_id, &cx.db, permission::can_read).await?; | 196 | + allowed(&me, self.community_id, cx.db, permission::can_read).await?; |
| 195 | 197 | ||
| 196 | - Ok(cx.sh.services.rooms.participants(&self.community_id)) | 198 | + Ok(cx.sh.services.rooms.participants(self.community_id)) |
| 197 | } | 199 | } |
| 198 | } | 200 | } |
| 199 | 201 | ||
| @@ -201,12 +203,12 @@ impl Handle for ListVoiceRooms { | |||
| 201 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<VoiceRoom>, ServerError> { | 203 | async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result<Vec<VoiceRoom>, ServerError> { |
| 202 | let mut rooms = Vec::new(); | 204 | let mut rooms = Vec::new(); |
| 203 | for (community_id, user_ids, ghosts) in cx.sh.services.rooms.list() { | 205 | for (community_id, user_ids, ghosts) in cx.sh.services.rooms.list() { |
| 204 | - let community = community::label(&community_id, &cx.db).await?; | 206 | + let community = db::community::label(community_id, cx.db).await?; |
| 205 | let mut users = Vec::new(); | 207 | let mut users = Vec::new(); |
| 206 | let mut muted = Vec::new(); | 208 | let mut muted = Vec::new(); |
| 207 | for user_id in user_ids { | 209 | for user_id in user_ids { |
| 208 | - let user = user::read(&user_id, &cx.db).await?; | 210 | + let user = db::user::read(user_id, cx.db).await?; |
| 209 | - if user::voice_muted(&user_id, &cx.db).await? { | 211 | + if db::user::voice_muted(user_id, cx.db).await? { |
| 210 | muted.push(user_id); | 212 | muted.push(user_id); |
| 211 | } | 213 | } |
| 212 | users.push(user); | 214 | users.push(user); |
| @@ -228,15 +230,15 @@ impl Handle for ListVoiceRooms { | |||
| 228 | impl Handle for KickFromVoice { | 230 | impl Handle for KickFromVoice { |
| 229 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 231 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 230 | let me = me.user()?; | 232 | let me = me.user()?; |
| 231 | - managed(&me, &self.user_id, &cx.db).await?; | 233 | + managed(&me, self.user_id, cx.db).await?; |
| 232 | - let broadcasts = leave_user_voice(&cx.sh.services.rooms, &self.user_id, &cx.db).await?; | 234 | + let broadcasts = leave_user_voice(&cx.sh.services.rooms, self.user_id, cx.db).await?; |
| 233 | if !broadcasts.is_empty() { | 235 | if !broadcasts.is_empty() { |
| 234 | - admin_log::record( | 236 | + db::log::record_admin( |
| 235 | - Some(&me.id), | 237 | + Some(me.id), |
| 236 | - Some(&self.user_id), | 238 | + Some(self.user_id), |
| 237 | None, | 239 | None, |
| 238 | &AdminAction::VoiceKicked, | 240 | &AdminAction::VoiceKicked, |
| 239 | - &cx.db, | 241 | + cx.db, |
| 240 | ) | 242 | ) |
| 241 | .await?; | 243 | .await?; |
| 242 | } | 244 | } |
| @@ -249,18 +251,18 @@ impl Handle for KickFromVoice { | |||
| 249 | impl Handle for ServerMute { | 251 | impl Handle for ServerMute { |
| 250 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { | 252 | async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { |
| 251 | let me = me.user()?; | 253 | let me = me.user()?; |
| 252 | - managed(&me, &self.user_id, &cx.db).await?; | 254 | + managed(&me, self.user_id, cx.db).await?; |
| 253 | - user::set_voice_muted(&self.user_id, self.muted, &cx.db).await?; | 255 | + db::user::set_voice_muted(self.user_id, self.muted, cx.db).await?; |
| 254 | - admin_log::record( | 256 | + db::log::record_admin( |
| 255 | - Some(&me.id), | 257 | + Some(me.id), |
| 256 | - Some(&self.user_id), | 258 | + Some(self.user_id), |
| 257 | None, | 259 | None, |
| 258 | &AdminAction::VoiceMuted { muted: self.muted }, | 260 | &AdminAction::VoiceMuted { muted: self.muted }, |
| 259 | - &cx.db, | 261 | + cx.db, |
| 260 | ) | 262 | ) |
| 261 | .await?; | 263 | .await?; |
| 262 | - let community_id = cx.sh.services.rooms.set_muted(&self.user_id, self.muted); | 264 | + let community_id = cx.sh.services.rooms.set_muted(self.user_id, self.muted); |
| 263 | - let broadcast = voice_muted(community_id, &self.user_id, self.muted, &cx.db).await?; | 265 | + let broadcast = voice_muted(community_id, self.user_id, self.muted, cx.db).await?; |
| 264 | cx.out.push(broadcast); | 266 | cx.out.push(broadcast); |
| 265 | 267 | ||
| 266 | Ok(()) | 268 | Ok(()) |
crates/server/src/community.rsdeleted+0 -405
| @@ -1,405 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - error::Error as CommonError, | ||
| 3 | - model::{Community, CommunityKind, User}, | ||
| 4 | - string_enum, | ||
| 5 | - validate::validate_community_name, | ||
| 6 | -}; | ||
| 7 | -use turso::{Connection, Row}; | ||
| 8 | - | ||
| 9 | -use crate::{database::new_id, error::ServerError, user}; | ||
| 10 | - | ||
| 11 | -string_enum! { | ||
| 12 | - #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 13 | - Kind { | ||
| 14 | - Group => "group", | ||
| 15 | - Direct => "direct", | ||
| 16 | - Notes => "notes", | ||
| 17 | - } | ||
| 18 | -} | ||
| 19 | - | ||
| 20 | -type Raw = (String, String, Kind, Option<String>, bool); | ||
| 21 | - | ||
| 22 | -fn raw_of(row: &Row) -> Result<Raw, ServerError> { | ||
| 23 | - let text: String = row.get(2)?; | ||
| 24 | - let kind = Kind::parse(&text).ok_or(CommonError::Server)?; | ||
| 25 | - | ||
| 26 | - Ok(( | ||
| 27 | - row.get(0)?, | ||
| 28 | - row.get(1)?, | ||
| 29 | - kind, | ||
| 30 | - row.get(3)?, | ||
| 31 | - user::bool_at(row, 4)?, | ||
| 32 | - )) | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result<User, ServerError> { | ||
| 36 | - let mut rows = conn | ||
| 37 | - .query( | ||
| 38 | - &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")), | ||
| 39 | - (community_id, viewer_id), | ||
| 40 | - ) | ||
| 41 | - .await?; | ||
| 42 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 43 | - | ||
| 44 | - user::from_row(&row) | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -async fn outsider_name( | ||
| 48 | - community_id: &str, | ||
| 49 | - viewer_id: &str, | ||
| 50 | - conn: &Connection, | ||
| 51 | -) -> Result<Option<String>, ServerError> { | ||
| 52 | - let mut rows = conn | ||
| 53 | - .query( | ||
| 54 | - "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", | ||
| 55 | - (community_id, viewer_id), | ||
| 56 | - ) | ||
| 57 | - .await?; | ||
| 58 | - let Some(row) = rows.next().await? else { | ||
| 59 | - return Ok(None); | ||
| 60 | - }; | ||
| 61 | - let first: String = row.get(0)?; | ||
| 62 | - let second: String = row.get(1)?; | ||
| 63 | - | ||
| 64 | - Ok(Some(format!("{first} & {second}"))) | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community, ServerError> { | ||
| 68 | - let (id, mut name, kind, avatar_id, voice_enabled) = raw; | ||
| 69 | - let kind = match kind { | ||
| 70 | - Kind::Group => CommunityKind::Group, | ||
| 71 | - Kind::Direct => { | ||
| 72 | - if let Some(outsider) = outsider_name(&id, viewer_id, conn).await? { | ||
| 73 | - name = outsider; | ||
| 74 | - } | ||
| 75 | - CommunityKind::Direct { | ||
| 76 | - peer: peer(&id, viewer_id, conn).await?, | ||
| 77 | - } | ||
| 78 | - } | ||
| 79 | - Kind::Notes => CommunityKind::Notes, | ||
| 80 | - }; | ||
| 81 | - | ||
| 82 | - Ok(Community { | ||
| 83 | - id, | ||
| 84 | - name, | ||
| 85 | - kind, | ||
| 86 | - avatar_id, | ||
| 87 | - voice_enabled, | ||
| 88 | - }) | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -pub async fn create(name: &str, conn: &Connection) -> Result<Community, ServerError> { | ||
| 92 | - validate_community_name(name)?; | ||
| 93 | - | ||
| 94 | - let id = new_id(); | ||
| 95 | - conn.execute( | ||
| 96 | - "INSERT INTO community (id, name, kind) VALUES (?1, ?2, ?3)", | ||
| 97 | - (id.as_str(), name, Kind::Group.as_str()), | ||
| 98 | - ) | ||
| 99 | - .await?; | ||
| 100 | - | ||
| 101 | - Ok(Community { | ||
| 102 | - id, | ||
| 103 | - name: name.to_string(), | ||
| 104 | - kind: CommunityKind::Group, | ||
| 105 | - avatar_id: None, | ||
| 106 | - voice_enabled: true, | ||
| 107 | - }) | ||
| 108 | -} | ||
| 109 | - | ||
| 110 | -pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result<String, ServerError> { | ||
| 111 | - let id = new_id(); | ||
| 112 | - conn.execute( | ||
| 113 | - "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", | ||
| 114 | - (id.as_str(), kind.as_str()), | ||
| 115 | - ) | ||
| 116 | - .await?; | ||
| 117 | - | ||
| 118 | - Ok(id) | ||
| 119 | -} | ||
| 120 | - | ||
| 121 | -pub async fn read( | ||
| 122 | - community_id: &str, | ||
| 123 | - viewer_id: &str, | ||
| 124 | - conn: &Connection, | ||
| 125 | -) -> Result<Community, ServerError> { | ||
| 126 | - let raw = { | ||
| 127 | - let mut rows = conn | ||
| 128 | - .query( | ||
| 129 | - "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE id = ?1", | ||
| 130 | - (community_id,), | ||
| 131 | - ) | ||
| 132 | - .await?; | ||
| 133 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 134 | - | ||
| 135 | - raw_of(&row)? | ||
| 136 | - }; | ||
| 137 | - | ||
| 138 | - build(raw, viewer_id, conn).await | ||
| 139 | -} | ||
| 140 | - | ||
| 141 | -pub async fn communities_of( | ||
| 142 | - user_id: &str, | ||
| 143 | - conn: &Connection, | ||
| 144 | -) -> Result<Vec<Community>, ServerError> { | ||
| 145 | - let raws = { | ||
| 146 | - let mut rows = conn | ||
| 147 | - .query( | ||
| 148 | - "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", | ||
| 149 | - (user_id,), | ||
| 150 | - ) | ||
| 151 | - .await?; | ||
| 152 | - | ||
| 153 | - let mut raws = Vec::new(); | ||
| 154 | - while let Some(row) = rows.next().await? { | ||
| 155 | - raws.push(raw_of(&row)?); | ||
| 156 | - } | ||
| 157 | - | ||
| 158 | - raws | ||
| 159 | - }; | ||
| 160 | - | ||
| 161 | - let mut communities = Vec::new(); | ||
| 162 | - for raw in raws { | ||
| 163 | - communities.push(build(raw, user_id, conn).await?); | ||
| 164 | - } | ||
| 165 | - | ||
| 166 | - Ok(communities) | ||
| 167 | -} | ||
| 168 | - | ||
| 169 | -pub async fn groups(conn: &Connection) -> Result<Vec<Community>, ServerError> { | ||
| 170 | - let mut rows = conn | ||
| 171 | - .query( | ||
| 172 | - "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE", | ||
| 173 | - (Kind::Group.as_str(),), | ||
| 174 | - ) | ||
| 175 | - .await?; | ||
| 176 | - | ||
| 177 | - let mut communities = Vec::new(); | ||
| 178 | - while let Some(row) = rows.next().await? { | ||
| 179 | - let (id, name, _, avatar_id, voice_enabled) = raw_of(&row)?; | ||
| 180 | - communities.push(Community { | ||
| 181 | - id, | ||
| 182 | - name, | ||
| 183 | - kind: CommunityKind::Group, | ||
| 184 | - avatar_id, | ||
| 185 | - voice_enabled, | ||
| 186 | - }); | ||
| 187 | - } | ||
| 188 | - | ||
| 189 | - Ok(communities) | ||
| 190 | -} | ||
| 191 | - | ||
| 192 | -pub async fn update( | ||
| 193 | - community_id: &str, | ||
| 194 | - name: &str, | ||
| 195 | - viewer_id: &str, | ||
| 196 | - conn: &Connection, | ||
| 197 | -) -> Result<Community, ServerError> { | ||
| 198 | - validate_community_name(name)?; | ||
| 199 | - | ||
| 200 | - conn.execute( | ||
| 201 | - "UPDATE community SET name = ?2 WHERE id = ?1", | ||
| 202 | - (community_id, name), | ||
| 203 | - ) | ||
| 204 | - .await?; | ||
| 205 | - | ||
| 206 | - read(community_id, viewer_id, conn).await | ||
| 207 | -} | ||
| 208 | - | ||
| 209 | -pub async fn set_avatar( | ||
| 210 | - community_id: &str, | ||
| 211 | - image: Option<&[u8]>, | ||
| 212 | - viewer_id: &str, | ||
| 213 | - conn: &mut Connection, | ||
| 214 | -) -> Result<Community, ServerError> { | ||
| 215 | - if let Some(bytes) = image { | ||
| 216 | - user::check_avatar(bytes)?; | ||
| 217 | - } | ||
| 218 | - let avatar_id = image.map(|_| new_id()); | ||
| 219 | - | ||
| 220 | - let tx = conn.transaction().await?; | ||
| 221 | - tx.execute( | ||
| 222 | - "DELETE FROM community_avatar WHERE community_id = ?1", | ||
| 223 | - (community_id,), | ||
| 224 | - ) | ||
| 225 | - .await?; | ||
| 226 | - if let (Some(avatar_id), Some(bytes)) = (&avatar_id, image) { | ||
| 227 | - tx.execute( | ||
| 228 | - "INSERT INTO community_avatar (id, community_id, data) VALUES (?1, ?2, ?3)", | ||
| 229 | - (avatar_id.as_str(), community_id, bytes), | ||
| 230 | - ) | ||
| 231 | - .await?; | ||
| 232 | - } | ||
| 233 | - tx.execute( | ||
| 234 | - "UPDATE community SET avatar_id = ?2 WHERE id = ?1", | ||
| 235 | - (community_id, avatar_id.as_deref()), | ||
| 236 | - ) | ||
| 237 | - .await?; | ||
| 238 | - let community = read(community_id, viewer_id, &tx).await?; | ||
| 239 | - tx.commit().await?; | ||
| 240 | - | ||
| 241 | - Ok(community) | ||
| 242 | -} | ||
| 243 | - | ||
| 244 | -pub async fn delete( | ||
| 245 | - community_id: &str, | ||
| 246 | - viewer_id: &str, | ||
| 247 | - conn: &Connection, | ||
| 248 | -) -> Result<Community, ServerError> { | ||
| 249 | - let deleted = read(community_id, viewer_id, conn).await?; | ||
| 250 | - conn.execute("DELETE FROM community WHERE id = ?1", (community_id,)) | ||
| 251 | - .await?; | ||
| 252 | - | ||
| 253 | - Ok(deleted) | ||
| 254 | -} | ||
| 255 | - | ||
| 256 | -pub async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, ServerError> { | ||
| 257 | - let mut rows = conn | ||
| 258 | - .query("SELECT kind FROM community WHERE id = ?1", (community_id,)) | ||
| 259 | - .await?; | ||
| 260 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 261 | - let text: String = row.get(0)?; | ||
| 262 | - | ||
| 263 | - Ok(Kind::parse(&text).ok_or(CommonError::Server)?) | ||
| 264 | -} | ||
| 265 | - | ||
| 266 | -pub async fn is_direct(community_id: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 267 | - Ok(kind(community_id, conn).await? == Kind::Direct) | ||
| 268 | -} | ||
| 269 | - | ||
| 270 | -pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 271 | - Ok(kind(community_id, conn).await? != Kind::Group) | ||
| 272 | -} | ||
| 273 | - | ||
| 274 | -pub async fn set_voice_enabled( | ||
| 275 | - community_id: &str, | ||
| 276 | - enabled: bool, | ||
| 277 | - conn: &Connection, | ||
| 278 | -) -> Result<(), ServerError> { | ||
| 279 | - conn.execute( | ||
| 280 | - "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", | ||
| 281 | - (community_id, i64::from(enabled)), | ||
| 282 | - ) | ||
| 283 | - .await?; | ||
| 284 | - | ||
| 285 | - Ok(()) | ||
| 286 | -} | ||
| 287 | - | ||
| 288 | -pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 289 | - let mut rows = conn | ||
| 290 | - .query( | ||
| 291 | - "SELECT voice_enabled FROM community WHERE id = ?1", | ||
| 292 | - (community_id,), | ||
| 293 | - ) | ||
| 294 | - .await?; | ||
| 295 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 296 | - | ||
| 297 | - user::bool_at(&row, 0) | ||
| 298 | -} | ||
| 299 | - | ||
| 300 | -pub async fn label(community_id: &str, conn: &Connection) -> Result<String, ServerError> { | ||
| 301 | - let prefix = match kind(community_id, conn).await? { | ||
| 302 | - Kind::Group => { | ||
| 303 | - let mut rows = conn | ||
| 304 | - .query("SELECT name FROM community WHERE id = ?1", (community_id,)) | ||
| 305 | - .await?; | ||
| 306 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 307 | - return Ok(row.get(0)?); | ||
| 308 | - } | ||
| 309 | - Kind::Direct => "DM", | ||
| 310 | - Kind::Notes => "Notes", | ||
| 311 | - }; | ||
| 312 | - | ||
| 313 | - let mut rows = conn | ||
| 314 | - .query( | ||
| 315 | - "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", | ||
| 316 | - (community_id,), | ||
| 317 | - ) | ||
| 318 | - .await?; | ||
| 319 | - let mut usernames = Vec::new(); | ||
| 320 | - while let Some(row) = rows.next().await? { | ||
| 321 | - usernames.push(row.get::<String>(0)?); | ||
| 322 | - } | ||
| 323 | - | ||
| 324 | - Ok(format!("{prefix} · {}", usernames.join(" & "))) | ||
| 325 | -} | ||
| 326 | - | ||
| 327 | -#[cfg(test)] | ||
| 328 | -mod tests { | ||
| 329 | - use common::error::Error as CommonError; | ||
| 330 | - | ||
| 331 | - use crate::{community, database, error::ServerError, test, user}; | ||
| 332 | - | ||
| 333 | - #[tokio::test] | ||
| 334 | - async fn create() { | ||
| 335 | - let db = test::get_database().await; | ||
| 336 | - let conn = database::connect(&db).await.unwrap(); | ||
| 337 | - | ||
| 338 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 339 | - | ||
| 340 | - assert_eq!("Tahinli", community.name); | ||
| 341 | - } | ||
| 342 | - | ||
| 343 | - #[tokio::test] | ||
| 344 | - async fn read() { | ||
| 345 | - let db = test::get_database().await; | ||
| 346 | - let conn = database::connect(&db).await.unwrap(); | ||
| 347 | - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 348 | - | ||
| 349 | - let created_community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 350 | - let searched_community = community::read(&created_community.id, &viewer.id, &conn) | ||
| 351 | - .await | ||
| 352 | - .unwrap(); | ||
| 353 | - | ||
| 354 | - assert_eq!(created_community, searched_community); | ||
| 355 | - } | ||
| 356 | - | ||
| 357 | - #[tokio::test] | ||
| 358 | - async fn update() { | ||
| 359 | - let db = test::get_database().await; | ||
| 360 | - let conn = database::connect(&db).await.unwrap(); | ||
| 361 | - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 362 | - | ||
| 363 | - let created_community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 364 | - let updated_community = | ||
| 365 | - community::update(&created_community.id, "Not Tahinli", &viewer.id, &conn) | ||
| 366 | - .await | ||
| 367 | - .unwrap(); | ||
| 368 | - let searched_community = community::read(&created_community.id, &viewer.id, &conn) | ||
| 369 | - .await | ||
| 370 | - .unwrap(); | ||
| 371 | - | ||
| 372 | - assert_eq!(created_community.id, searched_community.id); | ||
| 373 | - assert_eq!(updated_community, searched_community); | ||
| 374 | - assert_eq!("Not Tahinli", searched_community.name); | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - #[tokio::test] | ||
| 378 | - async fn update_on_missing_community() { | ||
| 379 | - let db = test::get_database().await; | ||
| 380 | - let conn = database::connect(&db).await.unwrap(); | ||
| 381 | - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 382 | - | ||
| 383 | - let updated_community = | ||
| 384 | - community::update("missing", "Not Tahinli", &viewer.id, &conn).await; | ||
| 385 | - | ||
| 386 | - assert!(matches!( | ||
| 387 | - updated_community, | ||
| 388 | - Err(ServerError::Wire(CommonError::NotFound)) | ||
| 389 | - )); | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | - #[tokio::test] | ||
| 393 | - async fn delete() { | ||
| 394 | - let db = test::get_database().await; | ||
| 395 | - let conn = database::connect(&db).await.unwrap(); | ||
| 396 | - let viewer = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 397 | - | ||
| 398 | - let created_community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 399 | - let deleted_community = community::delete(&created_community.id, &viewer.id, &conn) | ||
| 400 | - .await | ||
| 401 | - .unwrap(); | ||
| 402 | - | ||
| 403 | - assert_eq!(created_community, deleted_community); | ||
| 404 | - } | ||
| 405 | -} | ||
crates/server/src/database.rsdeleted+0 -375
| @@ -1,375 +0,0 @@ | |||
| 1 | -use std::time::Duration; | ||
| 2 | - | ||
| 3 | -use common::error::Error as CommonError; | ||
| 4 | -use turso::Connection; | ||
| 5 | - | ||
| 6 | -use crate::error::ServerError; | ||
| 7 | - | ||
| 8 | -pub type DB = turso::Database; | ||
| 9 | - | ||
| 10 | -const BUSY_TIMEOUT: Duration = Duration::from_secs(5); | ||
| 11 | - | ||
| 12 | -const MIGRATIONS: &[&str] = &[ | ||
| 13 | - " | ||
| 14 | - CREATE TABLE user ( | ||
| 15 | - id TEXT PRIMARY KEY, | ||
| 16 | - username TEXT NOT NULL UNIQUE, | ||
| 17 | - password_hash TEXT NOT NULL, | ||
| 18 | - role TEXT NOT NULL DEFAULT 'user', | ||
| 19 | - status TEXT NOT NULL DEFAULT '', | ||
| 20 | - avatar_id TEXT | ||
| 21 | - ); | ||
| 22 | - | ||
| 23 | - CREATE TABLE avatar ( | ||
| 24 | - id TEXT PRIMARY KEY, | ||
| 25 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 26 | - data BLOB NOT NULL | ||
| 27 | - ); | ||
| 28 | - | ||
| 29 | - CREATE TABLE session ( | ||
| 30 | - token TEXT PRIMARY KEY, | ||
| 31 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE | ||
| 32 | - ); | ||
| 33 | - | ||
| 34 | - CREATE TABLE community ( | ||
| 35 | - id TEXT PRIMARY KEY, | ||
| 36 | - name TEXT NOT NULL | ||
| 37 | - ); | ||
| 38 | - | ||
| 39 | - CREATE TABLE message ( | ||
| 40 | - id TEXT PRIMARY KEY, | ||
| 41 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 42 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 43 | - body TEXT NOT NULL | ||
| 44 | - ); | ||
| 45 | - | ||
| 46 | - CREATE INDEX message_community_id_id ON message (community_id, id); | ||
| 47 | - | ||
| 48 | - CREATE TABLE user_community ( | ||
| 49 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 50 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 51 | - rank TEXT NOT NULL DEFAULT 'member', | ||
| 52 | - PRIMARY KEY (user_id, community_id) | ||
| 53 | - ); | ||
| 54 | - | ||
| 55 | - CREATE TABLE ban ( | ||
| 56 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 57 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 58 | - PRIMARY KEY (user_id, community_id) | ||
| 59 | - ); | ||
| 60 | - | ||
| 61 | - CREATE TABLE attachment ( | ||
| 62 | - id TEXT PRIMARY KEY, | ||
| 63 | - uploader_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 64 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 65 | - message_id TEXT REFERENCES message (id) ON DELETE CASCADE, | ||
| 66 | - name TEXT NOT NULL, | ||
| 67 | - size INTEGER NOT NULL, | ||
| 68 | - kind TEXT NOT NULL, | ||
| 69 | - width INTEGER, | ||
| 70 | - height INTEGER | ||
| 71 | - ); | ||
| 72 | - | ||
| 73 | - CREATE INDEX attachment_message_id ON attachment (message_id); | ||
| 74 | -", | ||
| 75 | - " | ||
| 76 | - ALTER TABLE community ADD COLUMN kind TEXT NOT NULL DEFAULT 'group'; | ||
| 77 | - ALTER TABLE message ADD COLUMN reply_to TEXT; | ||
| 78 | - ALTER TABLE message ADD COLUMN edited INTEGER NOT NULL DEFAULT 0; | ||
| 79 | - ALTER TABLE attachment ADD COLUMN snippet_position INTEGER; | ||
| 80 | - ALTER TABLE ban ADD COLUMN reason TEXT; | ||
| 81 | - ALTER TABLE community ADD COLUMN avatar_id TEXT; | ||
| 82 | - | ||
| 83 | - CREATE TABLE community_avatar ( | ||
| 84 | - id TEXT PRIMARY KEY, | ||
| 85 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 86 | - data BLOB NOT NULL | ||
| 87 | - ); | ||
| 88 | - | ||
| 89 | - CREATE TABLE direct ( | ||
| 90 | - user_a TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 91 | - user_b TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 92 | - community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE, | ||
| 93 | - PRIMARY KEY (user_a, user_b) | ||
| 94 | - ); | ||
| 95 | - | ||
| 96 | - CREATE TABLE snippet ( | ||
| 97 | - message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, | ||
| 98 | - origin TEXT | ||
| 99 | - ); | ||
| 100 | - | ||
| 101 | - CREATE TABLE snippet_message ( | ||
| 102 | - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, | ||
| 103 | - position INTEGER NOT NULL, | ||
| 104 | - original_id TEXT NOT NULL, | ||
| 105 | - user_id TEXT NOT NULL, | ||
| 106 | - username TEXT NOT NULL, | ||
| 107 | - avatar_id TEXT, | ||
| 108 | - body TEXT NOT NULL, | ||
| 109 | - PRIMARY KEY (message_id, position) | ||
| 110 | - ); | ||
| 111 | - | ||
| 112 | - CREATE TABLE friend_request ( | ||
| 113 | - from_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 114 | - to_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 115 | - PRIMARY KEY (from_id, to_id) | ||
| 116 | - ); | ||
| 117 | - | ||
| 118 | - CREATE TABLE friend ( | ||
| 119 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 120 | - friend_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 121 | - PRIMARY KEY (user_id, friend_id) | ||
| 122 | - ); | ||
| 123 | - | ||
| 124 | - CREATE TABLE invitation ( | ||
| 125 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 126 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 127 | - inviter_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 128 | - PRIMARY KEY (community_id, user_id) | ||
| 129 | - ); | ||
| 130 | -", | ||
| 131 | - " | ||
| 132 | - CREATE TABLE community_log ( | ||
| 133 | - id TEXT PRIMARY KEY, | ||
| 134 | - community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 135 | - actor_id TEXT REFERENCES user (id) ON DELETE SET NULL, | ||
| 136 | - target_id TEXT REFERENCES user (id) ON DELETE SET NULL, | ||
| 137 | - action TEXT NOT NULL, | ||
| 138 | - detail TEXT | ||
| 139 | - ); | ||
| 140 | - | ||
| 141 | - CREATE INDEX community_log_community_id_id ON community_log (community_id, id); | ||
| 142 | -", | ||
| 143 | - " | ||
| 144 | - UPDATE user SET role = 'builder' WHERE role = 'staff'; | ||
| 145 | - UPDATE user_community SET rank = 'builder' WHERE rank = 'staff'; | ||
| 146 | -", | ||
| 147 | - " | ||
| 148 | - CREATE TABLE admin_log ( | ||
| 149 | - id TEXT PRIMARY KEY, | ||
| 150 | - actor_id TEXT REFERENCES user (id) ON DELETE SET NULL, | ||
| 151 | - target_id TEXT REFERENCES user (id) ON DELETE SET NULL, | ||
| 152 | - community TEXT, | ||
| 153 | - action TEXT NOT NULL, | ||
| 154 | - detail TEXT | ||
| 155 | - ); | ||
| 156 | -", | ||
| 157 | - " | ||
| 158 | - ALTER TABLE user ADD COLUMN suspended INTEGER NOT NULL DEFAULT 0; | ||
| 159 | -", | ||
| 160 | - " | ||
| 161 | - CREATE TABLE server_settings ( | ||
| 162 | - id INTEGER PRIMARY KEY CHECK (id = 1), | ||
| 163 | - name TEXT NOT NULL, | ||
| 164 | - registration_open INTEGER NOT NULL, | ||
| 165 | - max_attachment_bytes INTEGER NOT NULL | ||
| 166 | - ); | ||
| 167 | - | ||
| 168 | - INSERT INTO server_settings (id, name, registration_open, max_attachment_bytes) | ||
| 169 | - VALUES (1, 'yumush', 1, 26214400); | ||
| 170 | -", | ||
| 171 | - " | ||
| 172 | - ALTER TABLE user ADD COLUMN last_seen INTEGER; | ||
| 173 | - ALTER TABLE session ADD COLUMN id TEXT; | ||
| 174 | - ALTER TABLE session ADD COLUMN device TEXT NOT NULL DEFAULT ''; | ||
| 175 | - ALTER TABLE session ADD COLUMN last_seen INTEGER; | ||
| 176 | - UPDATE session SET id = lower(hex(randomblob(16))) WHERE id IS NULL; | ||
| 177 | -", | ||
| 178 | - " | ||
| 179 | - ALTER TABLE user ADD COLUMN suspended_until INTEGER; | ||
| 180 | - ALTER TABLE user ADD COLUMN last_ip TEXT; | ||
| 181 | - | ||
| 182 | - CREATE TABLE server_ban ( | ||
| 183 | - id TEXT PRIMARY KEY, | ||
| 184 | - kind TEXT NOT NULL, | ||
| 185 | - value TEXT NOT NULL, | ||
| 186 | - reason TEXT, | ||
| 187 | - created_by TEXT REFERENCES user (id) ON DELETE SET NULL | ||
| 188 | - ); | ||
| 189 | -", | ||
| 190 | - " | ||
| 191 | - CREATE TABLE invite_code ( | ||
| 192 | - code TEXT PRIMARY KEY, | ||
| 193 | - uses_left INTEGER NOT NULL, | ||
| 194 | - expires_at INTEGER, | ||
| 195 | - created_by TEXT REFERENCES user (id) ON DELETE SET NULL | ||
| 196 | - ); | ||
| 197 | -", | ||
| 198 | - " | ||
| 199 | - ALTER TABLE server_settings ADD COLUMN maintenance INTEGER NOT NULL DEFAULT 0; | ||
| 200 | -", | ||
| 201 | - " | ||
| 202 | - CREATE TABLE report ( | ||
| 203 | - id TEXT PRIMARY KEY, | ||
| 204 | - reporter_id TEXT REFERENCES user (id) ON DELETE SET NULL, | ||
| 205 | - target_id TEXT REFERENCES user (id) ON DELETE SET NULL, | ||
| 206 | - message_id TEXT, | ||
| 207 | - community_id TEXT, | ||
| 208 | - body TEXT, | ||
| 209 | - reason TEXT NOT NULL, | ||
| 210 | - status TEXT NOT NULL DEFAULT 'open', | ||
| 211 | - handled_by TEXT REFERENCES user (id) ON DELETE SET NULL | ||
| 212 | - ); | ||
| 213 | -", | ||
| 214 | - " | ||
| 215 | - ALTER TABLE user ADD COLUMN voice_muted INTEGER NOT NULL DEFAULT 0; | ||
| 216 | -", | ||
| 217 | - " | ||
| 218 | - ALTER TABLE community ADD COLUMN voice_enabled INTEGER NOT NULL DEFAULT 1; | ||
| 219 | -", | ||
| 220 | - " | ||
| 221 | - ALTER TABLE server_settings ADD COLUMN user_quota_bytes INTEGER NOT NULL DEFAULT 0; | ||
| 222 | - ALTER TABLE server_settings ADD COLUMN community_quota_bytes INTEGER NOT NULL DEFAULT 0; | ||
| 223 | - ALTER TABLE server_settings ADD COLUMN message_retention_days INTEGER NOT NULL DEFAULT 0; | ||
| 224 | - ALTER TABLE server_settings ADD COLUMN attachment_retention_days INTEGER NOT NULL DEFAULT 0; | ||
| 225 | -", | ||
| 226 | - " | ||
| 227 | - ALTER TABLE server_settings ADD COLUMN announcement TEXT NOT NULL DEFAULT ''; | ||
| 228 | - ALTER TABLE server_settings ADD COLUMN max_communities_per_user INTEGER NOT NULL DEFAULT 0; | ||
| 229 | - ALTER TABLE server_settings ADD COLUMN max_message_length INTEGER NOT NULL DEFAULT 1024; | ||
| 230 | - ALTER TABLE server_settings ADD COLUMN max_avatar_bytes INTEGER NOT NULL DEFAULT 32768; | ||
| 231 | - ALTER TABLE server_settings ADD COLUMN messages_per_minute INTEGER NOT NULL DEFAULT 30; | ||
| 232 | - ALTER TABLE server_settings ADD COLUMN logins_per_minute INTEGER NOT NULL DEFAULT 10; | ||
| 233 | -", | ||
| 234 | - " | ||
| 235 | - CREATE TABLE daily_active ( | ||
| 236 | - day INTEGER NOT NULL, | ||
| 237 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 238 | - PRIMARY KEY (day, user_id) | ||
| 239 | - ); | ||
| 240 | -", | ||
| 241 | - " | ||
| 242 | - ALTER TABLE user ADD COLUMN ghost INTEGER NOT NULL DEFAULT 0; | ||
| 243 | -", | ||
| 244 | - " | ||
| 245 | - ALTER TABLE user ADD COLUMN presence TEXT NOT NULL DEFAULT 'online'; | ||
| 246 | -", | ||
| 247 | - " | ||
| 248 | - ALTER TABLE message ADD COLUMN call TEXT; | ||
| 249 | - ALTER TABLE message ADD COLUMN call_seconds INTEGER NOT NULL DEFAULT 0; | ||
| 250 | -", | ||
| 251 | - " | ||
| 252 | - CREATE TABLE reaction ( | ||
| 253 | - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, | ||
| 254 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 255 | - emoji TEXT NOT NULL, | ||
| 256 | - PRIMARY KEY (message_id, user_id, emoji) | ||
| 257 | - ); | ||
| 258 | -", | ||
| 259 | - " | ||
| 260 | - ALTER TABLE message ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0; | ||
| 261 | -", | ||
| 262 | - " | ||
| 263 | - ALTER TABLE user_community ADD COLUMN last_read TEXT; | ||
| 264 | - UPDATE user_community SET last_read = (SELECT MAX(id) FROM message WHERE message.community_id = user_community.community_id); | ||
| 265 | -", | ||
| 266 | - " | ||
| 267 | - CREATE TABLE notes ( | ||
| 268 | - user_id TEXT PRIMARY KEY REFERENCES user (id) ON DELETE CASCADE, | ||
| 269 | - community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE | ||
| 270 | - ); | ||
| 271 | -", | ||
| 272 | - " | ||
| 273 | - CREATE TABLE poll ( | ||
| 274 | - message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, | ||
| 275 | - question TEXT NOT NULL, | ||
| 276 | - multiple INTEGER NOT NULL, | ||
| 277 | - closed INTEGER NOT NULL DEFAULT 0 | ||
| 278 | - ); | ||
| 279 | - CREATE TABLE poll_option ( | ||
| 280 | - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, | ||
| 281 | - position INTEGER NOT NULL, | ||
| 282 | - text TEXT NOT NULL, | ||
| 283 | - PRIMARY KEY (message_id, position) | ||
| 284 | - ); | ||
| 285 | - CREATE TABLE poll_vote ( | ||
| 286 | - message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, | ||
| 287 | - position INTEGER NOT NULL, | ||
| 288 | - user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 289 | - PRIMARY KEY (message_id, position, user_id) | ||
| 290 | - ); | ||
| 291 | -", | ||
| 292 | - "ALTER TABLE snippet_message ADD COLUMN poll BLOB;", | ||
| 293 | -]; | ||
| 294 | - | ||
| 295 | -pub async fn open(path: &str) -> Result<DB, ServerError> { | ||
| 296 | - let db = turso::Builder::new_local(path).build().await?; | ||
| 297 | - migrate(&db).await?; | ||
| 298 | - | ||
| 299 | - Ok(db) | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -pub async fn connect(db: &DB) -> Result<Connection, ServerError> { | ||
| 303 | - let conn = db.connect()?; | ||
| 304 | - conn.busy_timeout(BUSY_TIMEOUT)?; | ||
| 305 | - conn.execute_batch("PRAGMA foreign_keys = ON;").await?; | ||
| 306 | - | ||
| 307 | - Ok(conn) | ||
| 308 | -} | ||
| 309 | - | ||
| 310 | -pub async fn scalar_i64( | ||
| 311 | - conn: &Connection, | ||
| 312 | - sql: &str, | ||
| 313 | - params: impl turso::IntoParams, | ||
| 314 | -) -> Result<i64, ServerError> { | ||
| 315 | - let mut rows = conn.query(sql, params).await?; | ||
| 316 | - let row = rows | ||
| 317 | - .next() | ||
| 318 | - .await? | ||
| 319 | - .ok_or(turso::Error::QueryReturnedNoRows)?; | ||
| 320 | - | ||
| 321 | - Ok(row.get(0)?) | ||
| 322 | -} | ||
| 323 | - | ||
| 324 | -pub async fn exists( | ||
| 325 | - conn: &Connection, | ||
| 326 | - sql: &str, | ||
| 327 | - params: impl turso::IntoParams, | ||
| 328 | -) -> Result<bool, ServerError> { | ||
| 329 | - Ok(scalar_i64(conn, sql, params).await? != 0) | ||
| 330 | -} | ||
| 331 | - | ||
| 332 | -pub async fn ids( | ||
| 333 | - conn: &Connection, | ||
| 334 | - sql: &str, | ||
| 335 | - params: impl turso::IntoParams, | ||
| 336 | -) -> Result<Vec<String>, ServerError> { | ||
| 337 | - let mut rows = conn.query(sql, params).await?; | ||
| 338 | - | ||
| 339 | - let mut ids = Vec::new(); | ||
| 340 | - while let Some(row) = rows.next().await? { | ||
| 341 | - ids.push(row.get(0)?); | ||
| 342 | - } | ||
| 343 | - | ||
| 344 | - Ok(ids) | ||
| 345 | -} | ||
| 346 | - | ||
| 347 | -pub fn expect_one(affected: u64) -> Result<(), ServerError> { | ||
| 348 | - if affected != 1 { | ||
| 349 | - return Err(CommonError::NotFound.into()); | ||
| 350 | - } | ||
| 351 | - | ||
| 352 | - Ok(()) | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -async fn migrate(db: &DB) -> Result<(), ServerError> { | ||
| 356 | - let mut conn = connect(db).await?; | ||
| 357 | - let applied = user_version(&conn).await?; | ||
| 358 | - | ||
| 359 | - for (index, migration) in MIGRATIONS.iter().enumerate().skip(applied) { | ||
| 360 | - let tx = conn.transaction().await?; | ||
| 361 | - tx.execute_batch(migration).await?; | ||
| 362 | - tx.pragma_update("user_version", index + 1).await?; | ||
| 363 | - tx.commit().await?; | ||
| 364 | - } | ||
| 365 | - | ||
| 366 | - Ok(()) | ||
| 367 | -} | ||
| 368 | - | ||
| 369 | -async fn user_version(conn: &Connection) -> Result<usize, ServerError> { | ||
| 370 | - Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize) | ||
| 371 | -} | ||
| 372 | - | ||
| 373 | -pub fn new_id() -> String { | ||
| 374 | - uuid::Uuid::now_v7().to_string() | ||
| 375 | -} | ||
crates/server/src/datagram.rsmodified+8 -2
| @@ -1,12 +1,18 @@ | |||
| 1 | use std::sync::Arc; | 1 | use std::sync::Arc; |
| 2 | 2 | ||
| 3 | use quinn::Connection; | 3 | use quinn::Connection; |
| 4 | +use tracing::warn; | ||
| 4 | 5 | ||
| 5 | -use crate::{hub::Client, network::Shared, publish::publish}; | 6 | +use crate::{hub::Client, network::Shared, publish}; |
| 6 | 7 | ||
| 7 | pub(crate) async fn relay_datagrams(connection: Connection, client: Arc<Client>, shared: Shared) { | 8 | pub(crate) async fn relay_datagrams(connection: Connection, client: Arc<Client>, shared: Shared) { |
| 8 | while let Ok(bytes) = connection.read_datagram().await { | 9 | while let Ok(bytes) = connection.read_datagram().await { |
| 9 | let broadcasts = shared.services.rooms.relay(&client, &bytes); | 10 | let broadcasts = shared.services.rooms.relay(&client, &bytes); |
| 10 | - publish(&shared, broadcasts).await; | 11 | + if broadcasts.is_empty() { |
| 12 | + continue; | ||
| 13 | + } | ||
| 14 | + if let Err(error) = publish::job(&shared, async |_| Ok(broadcasts)).await { | ||
| 15 | + warn!("relay: {error}"); | ||
| 16 | + } | ||
| 11 | } | 17 | } |
| 12 | } | 18 | } |
crates/server/src/db/attachment.rsadded+268 -0
| @@ -0,0 +1,268 @@ | |||
| 1 | +use std::collections::HashSet; | ||
| 2 | + | ||
| 3 | +use common::{ | ||
| 4 | + constant::MAXIMUM_ATTACHMENTS_PER_MESSAGE, | ||
| 5 | + error::Error, | ||
| 6 | + model::{Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, Id, Usage}, | ||
| 7 | + time::now_ms, | ||
| 8 | +}; | ||
| 9 | + | ||
| 10 | +use super::{Connection, Reader, community, one, run, user}; | ||
| 11 | +use crate::error::{ServerError, ensure_with}; | ||
| 12 | + | ||
| 13 | +const LIST_LIMIT: u32 = 200; | ||
| 14 | +const USAGE_LIMIT: u32 = 50; | ||
| 15 | + | ||
| 16 | +pub const COLUMNS: &str = "attachment.id, attachment.name, attachment.size, attachment.kind, attachment.width, attachment.height, attachment.created_at"; | ||
| 17 | + | ||
| 18 | +pub struct Stored { | ||
| 19 | + pub attachment: Attachment, | ||
| 20 | + pub file: String, | ||
| 21 | + pub uploader_id: Id, | ||
| 22 | + pub community_id: Id, | ||
| 23 | + pub message_id: Option<Id>, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +pub fn row(r: &mut Reader) -> Result<Attachment, ServerError> { | ||
| 27 | + Ok(Attachment { | ||
| 28 | + id: r.get()?, | ||
| 29 | + name: r.get()?, | ||
| 30 | + size: r.get()?, | ||
| 31 | + kind: r.named()?, | ||
| 32 | + width: r.get()?, | ||
| 33 | + height: r.get()?, | ||
| 34 | + created_at: r.get()?, | ||
| 35 | + }) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +pub async fn of_message( | ||
| 39 | + message_id: Id, | ||
| 40 | + snippet_position: Option<u32>, | ||
| 41 | + db: &Connection, | ||
| 42 | +) -> Result<Vec<Attachment>, ServerError> { | ||
| 43 | + super::all( | ||
| 44 | + db, | ||
| 45 | + &format!( | ||
| 46 | + "SELECT {COLUMNS} FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id" | ||
| 47 | + ), | ||
| 48 | + (message_id, snippet_position), | ||
| 49 | + row, | ||
| 50 | + ) | ||
| 51 | + .await | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +pub async fn bind( | ||
| 55 | + message_id: Id, | ||
| 56 | + user_id: Id, | ||
| 57 | + community_id: Id, | ||
| 58 | + attachment_ids: &[Id], | ||
| 59 | + db: &Connection, | ||
| 60 | +) -> Result<(), ServerError> { | ||
| 61 | + ensure_with( | ||
| 62 | + attachment_ids.len() <= MAXIMUM_ATTACHMENTS_PER_MESSAGE, | ||
| 63 | + Error::NotFound, | ||
| 64 | + )?; | ||
| 65 | + for attachment_id in attachment_ids { | ||
| 66 | + let bound = run( | ||
| 67 | + db, | ||
| 68 | + "UPDATE attachment SET message_id = ?1 WHERE id = ?2 AND uploader_id = ?3 AND community_id = ?4 AND message_id IS NULL", | ||
| 69 | + (message_id, *attachment_id, user_id, community_id), | ||
| 70 | + ) | ||
| 71 | + .await?; | ||
| 72 | + ensure_with(bound == 1, Error::NotFound)?; | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + Ok(()) | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +pub async fn copy_row( | ||
| 79 | + id: Id, | ||
| 80 | + message_id: Id, | ||
| 81 | + user_id: Id, | ||
| 82 | + community_id: Id, | ||
| 83 | + snippet_position: Option<u32>, | ||
| 84 | + db: &Connection, | ||
| 85 | +) -> Result<(), ServerError> { | ||
| 86 | + let copied = run( | ||
| 87 | + db, | ||
| 88 | + "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", | ||
| 89 | + (id, user_id, community_id, message_id, snippet_position, now_ms()), | ||
| 90 | + ) | ||
| 91 | + .await?; | ||
| 92 | + ensure_with(copied == 1, Error::NotFound) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +#[allow(clippy::too_many_arguments)] | ||
| 96 | +pub async fn insert( | ||
| 97 | + uploader_id: Id, | ||
| 98 | + community_id: Id, | ||
| 99 | + file: &str, | ||
| 100 | + name: &str, | ||
| 101 | + size: u64, | ||
| 102 | + kind: AttachmentKind, | ||
| 103 | + width: Option<u32>, | ||
| 104 | + height: Option<u32>, | ||
| 105 | + db: &Connection, | ||
| 106 | +) -> Result<Attachment, ServerError> { | ||
| 107 | + let id: Id = one( | ||
| 108 | + db, | ||
| 109 | + "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", | ||
| 110 | + ( | ||
| 111 | + uploader_id, | ||
| 112 | + community_id, | ||
| 113 | + now_ms(), | ||
| 114 | + file, | ||
| 115 | + name, | ||
| 116 | + size, | ||
| 117 | + kind.as_str(), | ||
| 118 | + width, | ||
| 119 | + height, | ||
| 120 | + ), | ||
| 121 | + |r| r.get(), | ||
| 122 | + ) | ||
| 123 | + .await?; | ||
| 124 | + | ||
| 125 | + Ok(read(id, db).await?.attachment) | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +pub async fn read(id: Id, db: &Connection) -> Result<Stored, ServerError> { | ||
| 129 | + one( | ||
| 130 | + db, | ||
| 131 | + &format!( | ||
| 132 | + "SELECT {COLUMNS}, attachment.file, attachment.uploader_id, attachment.community_id, attachment.message_id FROM attachment WHERE attachment.id = ?1" | ||
| 133 | + ), | ||
| 134 | + (id,), | ||
| 135 | + |r| { | ||
| 136 | + Ok(Stored { | ||
| 137 | + attachment: row(r)?, | ||
| 138 | + file: r.get()?, | ||
| 139 | + uploader_id: r.get()?, | ||
| 140 | + community_id: r.get()?, | ||
| 141 | + message_id: r.get()?, | ||
| 142 | + }) | ||
| 143 | + }, | ||
| 144 | + ) | ||
| 145 | + .await | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 149 | + run(db, "DELETE FROM attachment WHERE id = ?1", (id,)).await?; | ||
| 150 | + | ||
| 151 | + Ok(()) | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +pub async fn delete_uploads(user_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 155 | + run( | ||
| 156 | + db, | ||
| 157 | + "DELETE FROM attachment WHERE uploader_id = ?1", | ||
| 158 | + (user_id,), | ||
| 159 | + ) | ||
| 160 | + .await?; | ||
| 161 | + | ||
| 162 | + Ok(()) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +pub async fn delete_stale_unbound(cutoff: u64, db: &Connection) -> Result<(), ServerError> { | ||
| 166 | + run( | ||
| 167 | + db, | ||
| 168 | + "DELETE FROM attachment WHERE message_id IS NULL AND created_at < ?1", | ||
| 169 | + (cutoff,), | ||
| 170 | + ) | ||
| 171 | + .await?; | ||
| 172 | + | ||
| 173 | + Ok(()) | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +pub async fn delete_before(cutoff: u64, limit: u32, db: &Connection) -> Result<u64, ServerError> { | ||
| 177 | + run( | ||
| 178 | + db, | ||
| 179 | + "DELETE FROM attachment WHERE id IN (SELECT id FROM attachment WHERE created_at < ?1 ORDER BY id LIMIT ?2)", | ||
| 180 | + (cutoff, limit), | ||
| 181 | + ) | ||
| 182 | + .await | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +pub async fn files(db: &Connection) -> Result<HashSet<String>, ServerError> { | ||
| 186 | + let files = super::all(db, "SELECT file FROM attachment", (), |r| r.get()).await?; | ||
| 187 | + | ||
| 188 | + Ok(files.into_iter().collect()) | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +pub async fn quota( | ||
| 192 | + user_id: Id, | ||
| 193 | + community_id: Id, | ||
| 194 | + db: &Connection, | ||
| 195 | +) -> Result<(u64, u64), ServerError> { | ||
| 196 | + one( | ||
| 197 | + db, | ||
| 198 | + "SELECT (SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1), (SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?2)", | ||
| 199 | + (user_id, community_id), | ||
| 200 | + |r| Ok((r.get()?, r.get()?)), | ||
| 201 | + ) | ||
| 202 | + .await | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +pub async fn all( | ||
| 206 | + user_id: Option<Id>, | ||
| 207 | + community_id: Option<Id>, | ||
| 208 | + db: &Connection, | ||
| 209 | +) -> Result<Vec<AttachmentInfo>, ServerError> { | ||
| 210 | + let rows = super::all( | ||
| 211 | + db, | ||
| 212 | + &format!( | ||
| 213 | + "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" | ||
| 214 | + ), | ||
| 215 | + (user_id, community_id, LIST_LIMIT), | ||
| 216 | + |r| Ok((row(r)?, r.get::<Id>()?, r.get::<Id>()?)), | ||
| 217 | + ) | ||
| 218 | + .await?; | ||
| 219 | + | ||
| 220 | + let mut infos = Vec::new(); | ||
| 221 | + for (attachment, uploader_id, community_id) in rows { | ||
| 222 | + infos.push(AttachmentInfo { | ||
| 223 | + attachment, | ||
| 224 | + uploader: Some(user::read(uploader_id, db).await?), | ||
| 225 | + community: community::label(community_id, db).await?, | ||
| 226 | + }); | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + Ok(infos) | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +pub async fn usage(db: &Connection) -> Result<(Vec<Usage>, Vec<CommunityUsage>), ServerError> { | ||
| 233 | + let by_user: Vec<(Id, u64, u64)> = super::all( | ||
| 234 | + db, | ||
| 235 | + "SELECT uploader_id, SUM(size), COUNT(*) FROM attachment GROUP BY uploader_id ORDER BY SUM(size) DESC LIMIT ?1", | ||
| 236 | + (USAGE_LIMIT,), | ||
| 237 | + |r| Ok((r.get()?, r.get()?, r.get()?)), | ||
| 238 | + ) | ||
| 239 | + .await?; | ||
| 240 | + let by_community: Vec<(Id, u64, u64)> = super::all( | ||
| 241 | + db, | ||
| 242 | + "SELECT community_id, SUM(size), COUNT(*) FROM attachment GROUP BY community_id ORDER BY SUM(size) DESC LIMIT ?1", | ||
| 243 | + (USAGE_LIMIT,), | ||
| 244 | + |r| Ok((r.get()?, r.get()?, r.get()?)), | ||
| 245 | + ) | ||
| 246 | + .await?; | ||
| 247 | + | ||
| 248 | + let mut users = Vec::new(); | ||
| 249 | + for (user_id, bytes, count) in by_user { | ||
| 250 | + users.push(Usage { | ||
| 251 | + user: user::read(user_id, db).await?, | ||
| 252 | + bytes, | ||
| 253 | + count, | ||
| 254 | + }); | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + let mut communities = Vec::new(); | ||
| 258 | + for (community_id, bytes, count) in by_community { | ||
| 259 | + communities.push(CommunityUsage { | ||
| 260 | + community: community::label(community_id, db).await?, | ||
| 261 | + community_id, | ||
| 262 | + bytes, | ||
| 263 | + count, | ||
| 264 | + }); | ||
| 265 | + } | ||
| 266 | + | ||
| 267 | + Ok((users, communities)) | ||
| 268 | +} | ||
crates/server/src/db/avatar.rsadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +use common::model::Id; | ||
| 2 | + | ||
| 3 | +use super::{Connection, one, run}; | ||
| 4 | +use crate::error::ServerError; | ||
| 5 | + | ||
| 6 | +pub async fn read(id: Id, db: &Connection) -> Result<Vec<u8>, ServerError> { | ||
| 7 | + one(db, "SELECT data FROM avatar WHERE id = ?1", (id,), |r| { | ||
| 8 | + r.get() | ||
| 9 | + }) | ||
| 10 | + .await | ||
| 11 | +} | ||
| 12 | + | ||
| 13 | +pub async fn set_user( | ||
| 14 | + user_id: Id, | ||
| 15 | + avatar: Option<&[u8]>, | ||
| 16 | + db: &Connection, | ||
| 17 | +) -> Result<(), ServerError> { | ||
| 18 | + run(db, "DELETE FROM avatar WHERE user_id = ?1", (user_id,)).await?; | ||
| 19 | + if let Some(bytes) = avatar { | ||
| 20 | + run( | ||
| 21 | + db, | ||
| 22 | + "INSERT INTO avatar (user_id, data) VALUES (?1, ?2)", | ||
| 23 | + (user_id, bytes), | ||
| 24 | + ) | ||
| 25 | + .await?; | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + Ok(()) | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +pub async fn set_community( | ||
| 32 | + community_id: Id, | ||
| 33 | + avatar: Option<&[u8]>, | ||
| 34 | + db: &Connection, | ||
| 35 | +) -> Result<(), ServerError> { | ||
| 36 | + run( | ||
| 37 | + db, | ||
| 38 | + "DELETE FROM avatar WHERE community_id = ?1", | ||
| 39 | + (community_id,), | ||
| 40 | + ) | ||
| 41 | + .await?; | ||
| 42 | + if let Some(bytes) = avatar { | ||
| 43 | + run( | ||
| 44 | + db, | ||
| 45 | + "INSERT INTO avatar (community_id, data) VALUES (?1, ?2)", | ||
| 46 | + (community_id, bytes), | ||
| 47 | + ) | ||
| 48 | + .await?; | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + Ok(()) | ||
| 52 | +} | ||
crates/server/src/db/community.rsadded+182 -0
| @@ -0,0 +1,182 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::{Community, CommunityKind, Id}, | ||
| 4 | + string_enum, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use super::{Connection, Reader, all, maybe, one, run, user}; | ||
| 8 | +use crate::error::{ServerError, ensure_with}; | ||
| 9 | + | ||
| 10 | +string_enum! { | ||
| 11 | + #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 12 | + Kind { | ||
| 13 | + Group => "group", | ||
| 14 | + Direct => "direct", | ||
| 15 | + Notes => "notes", | ||
| 16 | + } | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +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"; | ||
| 20 | + | ||
| 21 | +struct Raw { | ||
| 22 | + id: Id, | ||
| 23 | + name: String, | ||
| 24 | + kind: Kind, | ||
| 25 | + avatar_id: Option<Id>, | ||
| 26 | + voice_enabled: bool, | ||
| 27 | + peer: Option<Id>, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +fn raw(r: &mut Reader) -> Result<Raw, ServerError> { | ||
| 31 | + Ok(Raw { | ||
| 32 | + id: r.get()?, | ||
| 33 | + name: r.get()?, | ||
| 34 | + kind: r.named()?, | ||
| 35 | + avatar_id: r.get()?, | ||
| 36 | + voice_enabled: r.get()?, | ||
| 37 | + peer: r.get()?, | ||
| 38 | + }) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +pub async fn read(id: Id, viewer: Id, db: &Connection) -> Result<Community, ServerError> { | ||
| 42 | + let raw = one(db, READ, (id, viewer), raw).await?; | ||
| 43 | + let kind = match raw.kind { | ||
| 44 | + Kind::Group => CommunityKind::Group, | ||
| 45 | + Kind::Direct => CommunityKind::Direct { | ||
| 46 | + peer: user::read(raw.peer.ok_or(Error::NotFound)?, db).await?, | ||
| 47 | + }, | ||
| 48 | + Kind::Notes => CommunityKind::Notes, | ||
| 49 | + }; | ||
| 50 | + | ||
| 51 | + Ok(Community { | ||
| 52 | + id: raw.id, | ||
| 53 | + name: raw.name, | ||
| 54 | + kind, | ||
| 55 | + avatar_id: raw.avatar_id, | ||
| 56 | + voice_enabled: raw.voice_enabled, | ||
| 57 | + }) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +pub async fn create(kind: Kind, name: &str, db: &Connection) -> Result<Id, ServerError> { | ||
| 61 | + one( | ||
| 62 | + db, | ||
| 63 | + "INSERT INTO community (kind, name, voice_enabled) VALUES (?1, ?2, ?3) RETURNING id", | ||
| 64 | + (kind.as_str(), name, true), | ||
| 65 | + |r| r.get(), | ||
| 66 | + ) | ||
| 67 | + .await | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +pub async fn communities_of(user_id: Id, db: &Connection) -> Result<Vec<Community>, ServerError> { | ||
| 71 | + let ids: Vec<Id> = all( | ||
| 72 | + db, | ||
| 73 | + "SELECT community_id FROM member WHERE user_id = ?1 ORDER BY community_id", | ||
| 74 | + (user_id,), | ||
| 75 | + |r| r.get(), | ||
| 76 | + ) | ||
| 77 | + .await?; | ||
| 78 | + | ||
| 79 | + let mut communities = Vec::new(); | ||
| 80 | + for id in ids { | ||
| 81 | + communities.push(read(id, user_id, db).await?); | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + Ok(communities) | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +pub async fn groups(db: &Connection) -> Result<Vec<Community>, ServerError> { | ||
| 88 | + all( | ||
| 89 | + db, | ||
| 90 | + "SELECT id, name, (SELECT avatar.id FROM avatar WHERE avatar.community_id = community.id), voice_enabled FROM community WHERE kind = ?1 ORDER BY name", | ||
| 91 | + (Kind::Group.as_str(),), | ||
| 92 | + |r| { | ||
| 93 | + Ok(Community { | ||
| 94 | + id: r.get()?, | ||
| 95 | + name: r.get()?, | ||
| 96 | + kind: CommunityKind::Group, | ||
| 97 | + avatar_id: r.get()?, | ||
| 98 | + voice_enabled: r.get()?, | ||
| 99 | + }) | ||
| 100 | + }, | ||
| 101 | + ) | ||
| 102 | + .await | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +pub async fn update( | ||
| 106 | + community_id: Id, | ||
| 107 | + name: &str, | ||
| 108 | + viewer_id: Id, | ||
| 109 | + db: &Connection, | ||
| 110 | +) -> Result<Community, ServerError> { | ||
| 111 | + let changed = run( | ||
| 112 | + db, | ||
| 113 | + "UPDATE community SET name = ?2 WHERE id = ?1", | ||
| 114 | + (community_id, name), | ||
| 115 | + ) | ||
| 116 | + .await?; | ||
| 117 | + ensure_with(changed == 1, Error::NotFound)?; | ||
| 118 | + | ||
| 119 | + read(community_id, viewer_id, db).await | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 123 | + ensure_with( | ||
| 124 | + run(db, "DELETE FROM community WHERE id = ?1", (id,)).await? == 1, | ||
| 125 | + Error::NotFound, | ||
| 126 | + ) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +pub async fn kind_of(id: Id, db: &Connection) -> Result<Option<Kind>, ServerError> { | ||
| 130 | + maybe(db, "SELECT kind FROM community WHERE id = ?1", (id,), |r| { | ||
| 131 | + r.named() | ||
| 132 | + }) | ||
| 133 | + .await | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +pub async fn set_voice_enabled( | ||
| 137 | + community_id: Id, | ||
| 138 | + enabled: bool, | ||
| 139 | + db: &Connection, | ||
| 140 | +) -> Result<(), ServerError> { | ||
| 141 | + run( | ||
| 142 | + db, | ||
| 143 | + "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", | ||
| 144 | + (community_id, enabled), | ||
| 145 | + ) | ||
| 146 | + .await?; | ||
| 147 | + | ||
| 148 | + Ok(()) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +pub async fn voice_enabled(community_id: Id, db: &Connection) -> Result<bool, ServerError> { | ||
| 152 | + one( | ||
| 153 | + db, | ||
| 154 | + "SELECT voice_enabled FROM community WHERE id = ?1", | ||
| 155 | + (community_id,), | ||
| 156 | + |r| r.get(), | ||
| 157 | + ) | ||
| 158 | + .await | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +pub async fn label(id: Id, db: &Connection) -> Result<String, ServerError> { | ||
| 162 | + let prefix = match kind_of(id, db).await?.ok_or(Error::NotFound)? { | ||
| 163 | + Kind::Group => { | ||
| 164 | + return one(db, "SELECT name FROM community WHERE id = ?1", (id,), |r| { | ||
| 165 | + r.get() | ||
| 166 | + }) | ||
| 167 | + .await; | ||
| 168 | + } | ||
| 169 | + Kind::Direct => "DM", | ||
| 170 | + Kind::Notes => "Notes", | ||
| 171 | + }; | ||
| 172 | + | ||
| 173 | + let usernames: Vec<String> = all( | ||
| 174 | + db, | ||
| 175 | + "SELECT user.username FROM user JOIN member ON member.user_id = user.id WHERE member.community_id = ?1 ORDER BY user.username", | ||
| 176 | + (id,), | ||
| 177 | + |r| r.get(), | ||
| 178 | + ) | ||
| 179 | + .await?; | ||
| 180 | + | ||
| 181 | + Ok(format!("{prefix} · {}", usernames.join(" & "))) | ||
| 182 | +} | ||
crates/server/src/db/direct.rsadded+47 -0
| @@ -0,0 +1,47 @@ | |||
| 1 | +use common::model::{Community, Id, Rank}; | ||
| 2 | + | ||
| 3 | +use super::{Connection, community, maybe, member, run}; | ||
| 4 | +use crate::error::ServerError; | ||
| 5 | + | ||
| 6 | +pub enum Opening { | ||
| 7 | + Created(Community), | ||
| 8 | + Existing(Community), | ||
| 9 | +} | ||
| 10 | + | ||
| 11 | +pub async fn open(me: Id, other: Id, db: &Connection) -> Result<Opening, ServerError> { | ||
| 12 | + let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; | ||
| 13 | + | ||
| 14 | + let existing: Option<Id> = maybe( | ||
| 15 | + db, | ||
| 16 | + "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", | ||
| 17 | + (user_a, user_b), | ||
| 18 | + |r| r.get(), | ||
| 19 | + ) | ||
| 20 | + .await?; | ||
| 21 | + if let Some(community_id) = existing { | ||
| 22 | + return Ok(Opening::Existing( | ||
| 23 | + community::read(community_id, me, db).await?, | ||
| 24 | + )); | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + let community_id = if me == other { | ||
| 28 | + let community_id = community::create(community::Kind::Notes, "", db).await?; | ||
| 29 | + member::join(me, community_id, Rank::Owner, db).await?; | ||
| 30 | + community_id | ||
| 31 | + } else { | ||
| 32 | + let community_id = community::create(community::Kind::Direct, "", db).await?; | ||
| 33 | + member::join(me, community_id, Rank::Member, db).await?; | ||
| 34 | + member::join(other, community_id, Rank::Member, db).await?; | ||
| 35 | + community_id | ||
| 36 | + }; | ||
| 37 | + run( | ||
| 38 | + db, | ||
| 39 | + "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)", | ||
| 40 | + (user_a, user_b, community_id), | ||
| 41 | + ) | ||
| 42 | + .await?; | ||
| 43 | + | ||
| 44 | + Ok(Opening::Created( | ||
| 45 | + community::read(community_id, me, db).await?, | ||
| 46 | + )) | ||
| 47 | +} | ||
crates/server/src/db/friend.rsadded+104 -0
| @@ -0,0 +1,104 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::{Friends, Id, User}, | ||
| 4 | + string_enum, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use super::{Connection, all, maybe, run, user}; | ||
| 8 | +use crate::error::{ServerError, ensure_with}; | ||
| 9 | + | ||
| 10 | +string_enum! { | ||
| 11 | + #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 12 | + FriendState { | ||
| 13 | + Requested => "requested", | ||
| 14 | + Accepted => "accepted", | ||
| 15 | + } | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +async fn users( | ||
| 19 | + sql: &str, | ||
| 20 | + state: FriendState, | ||
| 21 | + id: Id, | ||
| 22 | + db: &Connection, | ||
| 23 | +) -> Result<Vec<User>, ServerError> { | ||
| 24 | + all(db, sql, (id, state.as_str()), user::row).await | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +pub async fn state(user_id: Id, db: &Connection) -> Result<Friends, ServerError> { | ||
| 28 | + let columns = user::COLUMNS; | ||
| 29 | + | ||
| 30 | + Ok(Friends { | ||
| 31 | + friends: users( | ||
| 32 | + &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"), | ||
| 33 | + FriendState::Accepted, | ||
| 34 | + user_id, | ||
| 35 | + db, | ||
| 36 | + ) | ||
| 37 | + .await?, | ||
| 38 | + incoming: users( | ||
| 39 | + &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"), | ||
| 40 | + FriendState::Requested, | ||
| 41 | + user_id, | ||
| 42 | + db, | ||
| 43 | + ) | ||
| 44 | + .await?, | ||
| 45 | + outgoing: users( | ||
| 46 | + &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"), | ||
| 47 | + FriendState::Requested, | ||
| 48 | + user_id, | ||
| 49 | + db, | ||
| 50 | + ) | ||
| 51 | + .await?, | ||
| 52 | + }) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +pub async fn pair(me: Id, other: Id, db: &Connection) -> Result<Option<FriendState>, ServerError> { | ||
| 56 | + maybe( | ||
| 57 | + db, | ||
| 58 | + "SELECT state FROM friend WHERE user_id = ?1 AND friend_id = ?2", | ||
| 59 | + (me, other), | ||
| 60 | + |r| r.named(), | ||
| 61 | + ) | ||
| 62 | + .await | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +pub async fn request(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 66 | + run( | ||
| 67 | + db, | ||
| 68 | + "INSERT INTO friend (user_id, friend_id, state) VALUES (?1, ?2, ?3)", | ||
| 69 | + (me, other, FriendState::Requested.as_str()), | ||
| 70 | + ) | ||
| 71 | + .await?; | ||
| 72 | + | ||
| 73 | + Ok(()) | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +pub async fn accept(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 77 | + let accepted = FriendState::Accepted.as_str(); | ||
| 78 | + let updated = run( | ||
| 79 | + db, | ||
| 80 | + "UPDATE friend SET state = ?3 WHERE user_id = ?1 AND friend_id = ?2 AND state = ?4", | ||
| 81 | + (other, me, accepted, FriendState::Requested.as_str()), | ||
| 82 | + ) | ||
| 83 | + .await?; | ||
| 84 | + ensure_with(updated == 1, Error::NotFound)?; | ||
| 85 | + run( | ||
| 86 | + db, | ||
| 87 | + "INSERT OR REPLACE INTO friend (user_id, friend_id, state) VALUES (?1, ?2, ?3)", | ||
| 88 | + (me, other, accepted), | ||
| 89 | + ) | ||
| 90 | + .await?; | ||
| 91 | + | ||
| 92 | + Ok(()) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +pub async fn remove(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 96 | + run( | ||
| 97 | + db, | ||
| 98 | + "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)", | ||
| 99 | + (me, other), | ||
| 100 | + ) | ||
| 101 | + .await?; | ||
| 102 | + | ||
| 103 | + Ok(()) | ||
| 104 | +} | ||
crates/server/src/db/invitation.rsadded+63 -0
| @@ -0,0 +1,63 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::{Id, Invitation}, | ||
| 4 | +}; | ||
| 5 | + | ||
| 6 | +use super::{Connection, all, community, one, run, user}; | ||
| 7 | +use crate::error::{ServerError, ensure_with}; | ||
| 8 | + | ||
| 9 | +pub async fn of(user_id: Id, db: &Connection) -> Result<Vec<Invitation>, ServerError> { | ||
| 10 | + let pairs: Vec<(Id, Id)> = all( | ||
| 11 | + db, | ||
| 12 | + "SELECT community_id, inviter_id FROM invitation WHERE user_id = ?1 ORDER BY community_id", | ||
| 13 | + (user_id,), | ||
| 14 | + |r| Ok((r.get()?, r.get()?)), | ||
| 15 | + ) | ||
| 16 | + .await?; | ||
| 17 | + | ||
| 18 | + let mut invitations = Vec::new(); | ||
| 19 | + for (community_id, inviter_id) in pairs { | ||
| 20 | + invitations.push(Invitation { | ||
| 21 | + community: community::read(community_id, user_id, db).await?, | ||
| 22 | + inviter: user::read(inviter_id, db).await?, | ||
| 23 | + }); | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + Ok(invitations) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +pub async fn exists(community_id: Id, user_id: Id, db: &Connection) -> Result<bool, ServerError> { | ||
| 30 | + one( | ||
| 31 | + db, | ||
| 32 | + "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", | ||
| 33 | + (community_id, user_id), | ||
| 34 | + |r| r.get(), | ||
| 35 | + ) | ||
| 36 | + .await | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +pub async fn insert( | ||
| 40 | + community_id: Id, | ||
| 41 | + user_id: Id, | ||
| 42 | + inviter_id: Id, | ||
| 43 | + db: &Connection, | ||
| 44 | +) -> Result<(), ServerError> { | ||
| 45 | + run( | ||
| 46 | + db, | ||
| 47 | + "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", | ||
| 48 | + (community_id, user_id, inviter_id), | ||
| 49 | + ) | ||
| 50 | + .await?; | ||
| 51 | + | ||
| 52 | + Ok(()) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +pub async fn take(community_id: Id, user_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 56 | + let deleted = run( | ||
| 57 | + db, | ||
| 58 | + "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2", | ||
| 59 | + (community_id, user_id), | ||
| 60 | + ) | ||
| 61 | + .await?; | ||
| 62 | + ensure_with(deleted == 1, Error::NotFound) | ||
| 63 | +} | ||
crates/server/src/db/log.rsadded+134 -0
| @@ -0,0 +1,134 @@ | |||
| 1 | +use common::{ | ||
| 2 | + constant::LOG_PAGE_LIMIT, | ||
| 3 | + model::{AdminAction, AdminActionKind, AdminLogEntry, Id, LogAction, LogEntry, User}, | ||
| 4 | + time::now_ms, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use super::{Connection, all, run, user}; | ||
| 8 | +use crate::error::ServerError; | ||
| 9 | + | ||
| 10 | +pub async fn optional_user(id: Option<Id>, db: &Connection) -> Result<Option<User>, ServerError> { | ||
| 11 | + match id { | ||
| 12 | + Some(id) => Ok(Some(user::read(id, db).await?)), | ||
| 13 | + None => Ok(None), | ||
| 14 | + } | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +pub async fn record( | ||
| 18 | + community_id: Id, | ||
| 19 | + actor_id: Option<Id>, | ||
| 20 | + target_id: Option<Id>, | ||
| 21 | + action: &LogAction, | ||
| 22 | + db: &Connection, | ||
| 23 | +) -> Result<(), ServerError> { | ||
| 24 | + run( | ||
| 25 | + db, | ||
| 26 | + "INSERT INTO community_log (community_id, created_at, actor_id, target_id, action) VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 27 | + (community_id, now_ms(), actor_id, target_id, bitcode::encode(action)), | ||
| 28 | + ) | ||
| 29 | + .await?; | ||
| 30 | + | ||
| 31 | + Ok(()) | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +pub async fn list(community_id: Id, db: &Connection) -> Result<Vec<LogEntry>, ServerError> { | ||
| 35 | + let raws = all( | ||
| 36 | + db, | ||
| 37 | + "SELECT id, created_at, actor_id, target_id, action FROM community_log WHERE community_id = ?1 ORDER BY id DESC LIMIT ?2", | ||
| 38 | + (community_id, LOG_PAGE_LIMIT), | ||
| 39 | + |r| { | ||
| 40 | + Ok(( | ||
| 41 | + r.get::<Id>()?, | ||
| 42 | + r.get::<u64>()?, | ||
| 43 | + r.get::<Option<Id>>()?, | ||
| 44 | + r.get::<Option<Id>>()?, | ||
| 45 | + r.blob::<LogAction>()?, | ||
| 46 | + )) | ||
| 47 | + }, | ||
| 48 | + ) | ||
| 49 | + .await?; | ||
| 50 | + | ||
| 51 | + let mut entries = Vec::new(); | ||
| 52 | + for (id, created_at, actor_id, target_id, action) in raws { | ||
| 53 | + entries.push(LogEntry { | ||
| 54 | + id, | ||
| 55 | + created_at, | ||
| 56 | + actor: optional_user(actor_id, db).await?, | ||
| 57 | + target: optional_user(target_id, db).await?, | ||
| 58 | + action, | ||
| 59 | + }); | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + Ok(entries) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +pub async fn record_admin( | ||
| 66 | + actor_id: Option<Id>, | ||
| 67 | + target_id: Option<Id>, | ||
| 68 | + community: Option<&str>, | ||
| 69 | + action: &AdminAction, | ||
| 70 | + db: &Connection, | ||
| 71 | +) -> Result<(), ServerError> { | ||
| 72 | + run( | ||
| 73 | + db, | ||
| 74 | + "INSERT INTO admin_log (created_at, actor_id, target_id, community, kind, action) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | ||
| 75 | + ( | ||
| 76 | + now_ms(), | ||
| 77 | + actor_id, | ||
| 78 | + target_id, | ||
| 79 | + community, | ||
| 80 | + action.kind().as_str(), | ||
| 81 | + bitcode::encode(action), | ||
| 82 | + ), | ||
| 83 | + ) | ||
| 84 | + .await?; | ||
| 85 | + | ||
| 86 | + Ok(()) | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +pub async fn list_admin( | ||
| 90 | + actor_id: Option<Id>, | ||
| 91 | + target_id: Option<Id>, | ||
| 92 | + kind: Option<AdminActionKind>, | ||
| 93 | + after_ms: Option<u64>, | ||
| 94 | + before_ms: Option<u64>, | ||
| 95 | + db: &Connection, | ||
| 96 | +) -> Result<Vec<AdminLogEntry>, ServerError> { | ||
| 97 | + let raws = all( | ||
| 98 | + db, | ||
| 99 | + "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", | ||
| 100 | + ( | ||
| 101 | + actor_id, | ||
| 102 | + target_id, | ||
| 103 | + kind.map(AdminActionKind::as_str), | ||
| 104 | + after_ms.map(|ms| ms as i64), | ||
| 105 | + before_ms.map(|ms| ms as i64), | ||
| 106 | + LOG_PAGE_LIMIT, | ||
| 107 | + ), | ||
| 108 | + |r| { | ||
| 109 | + Ok(( | ||
| 110 | + r.get::<Id>()?, | ||
| 111 | + r.get::<u64>()?, | ||
| 112 | + r.get::<Option<Id>>()?, | ||
| 113 | + r.get::<Option<Id>>()?, | ||
| 114 | + r.get::<Option<String>>()?, | ||
| 115 | + r.blob::<AdminAction>()?, | ||
| 116 | + )) | ||
| 117 | + }, | ||
| 118 | + ) | ||
| 119 | + .await?; | ||
| 120 | + | ||
| 121 | + let mut entries = Vec::new(); | ||
| 122 | + for (id, created_at, actor_id, target_id, community, action) in raws { | ||
| 123 | + entries.push(AdminLogEntry { | ||
| 124 | + id, | ||
| 125 | + actor: optional_user(actor_id, db).await?, | ||
| 126 | + target: optional_user(target_id, db).await?, | ||
| 127 | + created_at, | ||
| 128 | + community, | ||
| 129 | + action, | ||
| 130 | + }); | ||
| 131 | + } | ||
| 132 | + | ||
| 133 | + Ok(entries) | ||
| 134 | +} | ||
crates/server/src/db/member.rsadded+234 -0
| @@ -0,0 +1,234 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | + | ||
| 3 | +use common::model::{Ban, Id, Member, Rank, Unread, mentions}; | ||
| 4 | + | ||
| 5 | +use super::{Connection, all, community, maybe, one, run, user}; | ||
| 6 | +use crate::error::ServerError; | ||
| 7 | + | ||
| 8 | +pub async fn join( | ||
| 9 | + user_id: Id, | ||
| 10 | + community_id: Id, | ||
| 11 | + rank: Rank, | ||
| 12 | + db: &Connection, | ||
| 13 | +) -> Result<(), ServerError> { | ||
| 14 | + run( | ||
| 15 | + db, | ||
| 16 | + "INSERT INTO member (user_id, community_id, rank) VALUES (?1, ?2, ?3)", | ||
| 17 | + (user_id, community_id, rank.as_str()), | ||
| 18 | + ) | ||
| 19 | + .await?; | ||
| 20 | + | ||
| 21 | + Ok(()) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +pub async fn leave(user_id: Id, community_id: Id, db: &Connection) -> Result<u64, ServerError> { | ||
| 25 | + run( | ||
| 26 | + db, | ||
| 27 | + "DELETE FROM member WHERE user_id = ?1 AND community_id = ?2", | ||
| 28 | + (user_id, community_id), | ||
| 29 | + ) | ||
| 30 | + .await | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +pub async fn rank( | ||
| 34 | + user_id: Id, | ||
| 35 | + community_id: Id, | ||
| 36 | + db: &Connection, | ||
| 37 | +) -> Result<Option<Rank>, ServerError> { | ||
| 38 | + maybe( | ||
| 39 | + db, | ||
| 40 | + "SELECT rank FROM member WHERE user_id = ?1 AND community_id = ?2", | ||
| 41 | + (user_id, community_id), | ||
| 42 | + |r| r.named(), | ||
| 43 | + ) | ||
| 44 | + .await | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +pub async fn set_rank( | ||
| 48 | + user_id: Id, | ||
| 49 | + community_id: Id, | ||
| 50 | + rank: Rank, | ||
| 51 | + db: &Connection, | ||
| 52 | +) -> Result<(), ServerError> { | ||
| 53 | + run( | ||
| 54 | + db, | ||
| 55 | + "UPDATE member SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", | ||
| 56 | + (user_id, community_id, rank.as_str()), | ||
| 57 | + ) | ||
| 58 | + .await?; | ||
| 59 | + | ||
| 60 | + Ok(()) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +pub async fn mark_read( | ||
| 64 | + user_id: Id, | ||
| 65 | + community_id: Id, | ||
| 66 | + message_id: Id, | ||
| 67 | + db: &Connection, | ||
| 68 | +) -> Result<(), ServerError> { | ||
| 69 | + run( | ||
| 70 | + db, | ||
| 71 | + "UPDATE member SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", | ||
| 72 | + (user_id, community_id, message_id), | ||
| 73 | + ) | ||
| 74 | + .await?; | ||
| 75 | + | ||
| 76 | + Ok(()) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +pub async fn unreads( | ||
| 80 | + user_id: Id, | ||
| 81 | + username: &str, | ||
| 82 | + db: &Connection, | ||
| 83 | +) -> Result<Vec<Unread>, ServerError> { | ||
| 84 | + let mut unreads = all( | ||
| 85 | + db, | ||
| 86 | + "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", | ||
| 87 | + (user_id,), | ||
| 88 | + |r| { | ||
| 89 | + Ok(Unread { | ||
| 90 | + community_id: r.get()?, | ||
| 91 | + messages: r.get()?, | ||
| 92 | + mentions: 0, | ||
| 93 | + last_read: r.get()?, | ||
| 94 | + }) | ||
| 95 | + }, | ||
| 96 | + ) | ||
| 97 | + .await?; | ||
| 98 | + | ||
| 99 | + let needle = format!("@{}", username.to_lowercase()); | ||
| 100 | + let bodies: Vec<(Id, String)> = all( | ||
| 101 | + db, | ||
| 102 | + "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", | ||
| 103 | + (user_id, needle.as_str()), | ||
| 104 | + |r| Ok((r.get()?, r.get()?)), | ||
| 105 | + ) | ||
| 106 | + .await?; | ||
| 107 | + | ||
| 108 | + let mut counts: HashMap<Id, u32> = HashMap::new(); | ||
| 109 | + for (community_id, body) in bodies { | ||
| 110 | + if mentions(&body, username) { | ||
| 111 | + *counts.entry(community_id).or_default() += 1; | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + for unread in &mut unreads { | ||
| 116 | + unread.mentions = counts | ||
| 117 | + .get(&unread.community_id) | ||
| 118 | + .copied() | ||
| 119 | + .unwrap_or_default(); | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + Ok(unreads) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +pub async fn member_ids(community_id: Id, db: &Connection) -> Result<Vec<Id>, ServerError> { | ||
| 126 | + all( | ||
| 127 | + db, | ||
| 128 | + "SELECT user_id FROM member WHERE community_id = ?1", | ||
| 129 | + (community_id,), | ||
| 130 | + |r| r.get(), | ||
| 131 | + ) | ||
| 132 | + .await | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +pub async fn members(community_id: Id, db: &Connection) -> Result<Vec<Member>, ServerError> { | ||
| 136 | + all( | ||
| 137 | + db, | ||
| 138 | + &format!( | ||
| 139 | + "SELECT {}, member.rank FROM user JOIN member ON member.user_id = user.id WHERE member.community_id = ?1 ORDER BY user.id", | ||
| 140 | + user::COLUMNS | ||
| 141 | + ), | ||
| 142 | + (community_id,), | ||
| 143 | + |r| { | ||
| 144 | + Ok(Member { | ||
| 145 | + user: user::row(r)?, | ||
| 146 | + rank: r.named()?, | ||
| 147 | + }) | ||
| 148 | + }, | ||
| 149 | + ) | ||
| 150 | + .await | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +pub async fn owned_groups(user_id: Id, db: &Connection) -> Result<u32, ServerError> { | ||
| 154 | + one( | ||
| 155 | + db, | ||
| 156 | + "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", | ||
| 157 | + ( | ||
| 158 | + user_id, | ||
| 159 | + Rank::Owner.as_str(), | ||
| 160 | + community::Kind::Group.as_str(), | ||
| 161 | + ), | ||
| 162 | + |r| r.get(), | ||
| 163 | + ) | ||
| 164 | + .await | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +pub async fn owned(user_id: Id, db: &Connection) -> Result<Vec<Id>, ServerError> { | ||
| 168 | + all( | ||
| 169 | + db, | ||
| 170 | + "SELECT community_id FROM member WHERE user_id = ?1 AND rank = ?2", | ||
| 171 | + (user_id, Rank::Owner.as_str()), | ||
| 172 | + |r| r.get(), | ||
| 173 | + ) | ||
| 174 | + .await | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +pub async fn ban( | ||
| 178 | + user_id: Id, | ||
| 179 | + community_id: Id, | ||
| 180 | + reason: Option<&str>, | ||
| 181 | + db: &Connection, | ||
| 182 | +) -> Result<(), ServerError> { | ||
| 183 | + run( | ||
| 184 | + db, | ||
| 185 | + "INSERT OR REPLACE INTO community_ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", | ||
| 186 | + (user_id, community_id, reason), | ||
| 187 | + ) | ||
| 188 | + .await?; | ||
| 189 | + | ||
| 190 | + Ok(()) | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +pub async fn unban(user_id: Id, community_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 194 | + run( | ||
| 195 | + db, | ||
| 196 | + "DELETE FROM community_ban WHERE user_id = ?1 AND community_id = ?2", | ||
| 197 | + (user_id, community_id), | ||
| 198 | + ) | ||
| 199 | + .await?; | ||
| 200 | + | ||
| 201 | + Ok(()) | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +pub async fn is_banned( | ||
| 205 | + user_id: Id, | ||
| 206 | + community_id: Id, | ||
| 207 | + db: &Connection, | ||
| 208 | +) -> Result<bool, ServerError> { | ||
| 209 | + one( | ||
| 210 | + db, | ||
| 211 | + "SELECT EXISTS (SELECT 1 FROM community_ban WHERE user_id = ?1 AND community_id = ?2)", | ||
| 212 | + (user_id, community_id), | ||
| 213 | + |r| r.get(), | ||
| 214 | + ) | ||
| 215 | + .await | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +pub async fn bans(community_id: Id, db: &Connection) -> Result<Vec<Ban>, ServerError> { | ||
| 219 | + all( | ||
| 220 | + db, | ||
| 221 | + &format!( | ||
| 222 | + "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", | ||
| 223 | + user::COLUMNS | ||
| 224 | + ), | ||
| 225 | + (community_id,), | ||
| 226 | + |r| { | ||
| 227 | + Ok(Ban { | ||
| 228 | + user: user::row(r)?, | ||
| 229 | + reason: r.get()?, | ||
| 230 | + }) | ||
| 231 | + }, | ||
| 232 | + ) | ||
| 233 | + .await | ||
| 234 | +} | ||
crates/server/src/db/message.rsadded+513 -0
| @@ -0,0 +1,513 @@ | |||
| 1 | +use common::{ | ||
| 2 | + constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, | ||
| 3 | + error::{Error, Field, Problem}, | ||
| 4 | + model::{CallLog, Id, Message, MessageHit, Quote, Reaction, SnippetMessage}, | ||
| 5 | + time::now_ms, | ||
| 6 | +}; | ||
| 7 | + | ||
| 8 | +use super::{Connection, Reader, all, attachment, community, maybe, one, poll, run, snippet, user}; | ||
| 9 | +use crate::error::{ServerError, ensure_with}; | ||
| 10 | + | ||
| 11 | +const SEARCH_LIMIT: u32 = 200; | ||
| 12 | +const PAGE_LIMIT: u32 = MESSAGE_PAGE_LIMIT as u32; | ||
| 13 | + | ||
| 14 | +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"; | ||
| 15 | + | ||
| 16 | +fn row(r: &mut Reader) -> Result<Message, ServerError> { | ||
| 17 | + let id = r.get()?; | ||
| 18 | + let user_id = r.get()?; | ||
| 19 | + let community_id = r.get()?; | ||
| 20 | + let created_at = r.get()?; | ||
| 21 | + let body = r.get()?; | ||
| 22 | + let edited = r.get()?; | ||
| 23 | + let reply_id: Option<Id> = r.get()?; | ||
| 24 | + let reply_user_id: Option<Id> = r.get()?; | ||
| 25 | + let reply_body: Option<String> = r.get()?; | ||
| 26 | + let reply_attachments: u32 = r.get()?; | ||
| 27 | + let call: Option<String> = r.get()?; | ||
| 28 | + let call_seconds: u64 = r.get()?; | ||
| 29 | + let pinned = r.get()?; | ||
| 30 | + | ||
| 31 | + let reply = match (reply_id, reply_user_id, reply_body) { | ||
| 32 | + (Some(message_id), Some(user_id), Some(body)) => Some(Quote { | ||
| 33 | + message_id, | ||
| 34 | + user_id, | ||
| 35 | + body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(), | ||
| 36 | + attachments: reply_attachments, | ||
| 37 | + }), | ||
| 38 | + _ => None, | ||
| 39 | + }; | ||
| 40 | + | ||
| 41 | + Ok(Message { | ||
| 42 | + id, | ||
| 43 | + user_id, | ||
| 44 | + community_id, | ||
| 45 | + created_at, | ||
| 46 | + body, | ||
| 47 | + attachments: Vec::new(), | ||
| 48 | + reactions: Vec::new(), | ||
| 49 | + reply, | ||
| 50 | + snippet: None, | ||
| 51 | + poll: None, | ||
| 52 | + edited, | ||
| 53 | + pinned, | ||
| 54 | + call: call.and_then(|text| CallLog::parse(&text, call_seconds)), | ||
| 55 | + }) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +async fn reactions(message_id: Id, db: &Connection) -> Result<Vec<Reaction>, ServerError> { | ||
| 59 | + let rows: Vec<(String, Id)> = all( | ||
| 60 | + db, | ||
| 61 | + "SELECT emoji, user_id FROM reaction WHERE message_id = ?1 ORDER BY emoji, user_id", | ||
| 62 | + (message_id,), | ||
| 63 | + |r| Ok((r.get()?, r.get()?)), | ||
| 64 | + ) | ||
| 65 | + .await?; | ||
| 66 | + | ||
| 67 | + let mut reactions: Vec<Reaction> = Vec::new(); | ||
| 68 | + for (emoji, user_id) in rows { | ||
| 69 | + match reactions | ||
| 70 | + .last_mut() | ||
| 71 | + .filter(|reaction| reaction.emoji == emoji) | ||
| 72 | + { | ||
| 73 | + Some(reaction) => reaction.user_ids.push(user_id), | ||
| 74 | + None => reactions.push(Reaction { | ||
| 75 | + emoji, | ||
| 76 | + user_ids: vec![user_id], | ||
| 77 | + }), | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + Ok(reactions) | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +async fn insert( | ||
| 85 | + user_id: Id, | ||
| 86 | + community_id: Id, | ||
| 87 | + body: &str, | ||
| 88 | + reply_to: Option<Id>, | ||
| 89 | + db: &Connection, | ||
| 90 | +) -> Result<Id, ServerError> { | ||
| 91 | + one( | ||
| 92 | + db, | ||
| 93 | + "INSERT INTO message (community_id, user_id, created_at, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", | ||
| 94 | + (community_id, user_id, now_ms(), body, reply_to), | ||
| 95 | + |r| r.get(), | ||
| 96 | + ) | ||
| 97 | + .await | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +pub async fn community_of(message_id: Id, db: &Connection) -> Result<Id, ServerError> { | ||
| 101 | + one( | ||
| 102 | + db, | ||
| 103 | + "SELECT community_id FROM message WHERE id = ?1", | ||
| 104 | + (message_id,), | ||
| 105 | + |r| r.get(), | ||
| 106 | + ) | ||
| 107 | + .await | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +pub async fn create_call_log( | ||
| 111 | + community_id: Id, | ||
| 112 | + user_id: Id, | ||
| 113 | + call: CallLog, | ||
| 114 | + db: &Connection, | ||
| 115 | +) -> Result<Message, ServerError> { | ||
| 116 | + let id: Id = one( | ||
| 117 | + db, | ||
| 118 | + "INSERT INTO message (community_id, user_id, created_at, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5) RETURNING id", | ||
| 119 | + (community_id, user_id, now_ms(), call.as_str(), call.seconds()), | ||
| 120 | + |r| r.get(), | ||
| 121 | + ) | ||
| 122 | + .await?; | ||
| 123 | + | ||
| 124 | + read(id, db).await | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +pub async fn create( | ||
| 128 | + user_id: Id, | ||
| 129 | + community_id: Id, | ||
| 130 | + body: &str, | ||
| 131 | + attachments: &[Id], | ||
| 132 | + reply_to: Option<Id>, | ||
| 133 | + db: &Connection, | ||
| 134 | +) -> Result<Message, ServerError> { | ||
| 135 | + let id = insert(user_id, community_id, body, reply_to, db).await?; | ||
| 136 | + attachment::bind(id, user_id, community_id, attachments, db).await?; | ||
| 137 | + | ||
| 138 | + read(id, db).await | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +pub async fn read(id: Id, db: &Connection) -> Result<Message, ServerError> { | ||
| 142 | + let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?; | ||
| 143 | + message.reactions = reactions(id, db).await?; | ||
| 144 | + message.poll = poll::of(id, db).await?; | ||
| 145 | + message.attachments = attachment::of_message(id, None, db).await?; | ||
| 146 | + message.snippet = snippet::of(id, db).await?; | ||
| 147 | + | ||
| 148 | + Ok(message) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +async fn read_all(ids: Vec<Id>, db: &Connection) -> Result<Vec<Message>, ServerError> { | ||
| 152 | + let mut messages = Vec::new(); | ||
| 153 | + for id in ids { | ||
| 154 | + messages.push(read(id, db).await?); | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + Ok(messages) | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +pub async fn read_page( | ||
| 161 | + community_id: Id, | ||
| 162 | + before: Option<Id>, | ||
| 163 | + db: &Connection, | ||
| 164 | +) -> Result<Vec<Message>, ServerError> { | ||
| 165 | + let mut ids = all( | ||
| 166 | + db, | ||
| 167 | + "SELECT id FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) ORDER BY id DESC LIMIT ?3", | ||
| 168 | + (community_id, before, PAGE_LIMIT), | ||
| 169 | + |r| r.get(), | ||
| 170 | + ) | ||
| 171 | + .await?; | ||
| 172 | + ids.reverse(); | ||
| 173 | + | ||
| 174 | + read_all(ids, db).await | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +pub async fn pinned(community_id: Id, db: &Connection) -> Result<Vec<Message>, ServerError> { | ||
| 178 | + let ids = all( | ||
| 179 | + db, | ||
| 180 | + "SELECT id FROM message WHERE community_id = ?1 AND pinned = 1 ORDER BY id DESC", | ||
| 181 | + (community_id,), | ||
| 182 | + |r| r.get(), | ||
| 183 | + ) | ||
| 184 | + .await?; | ||
| 185 | + | ||
| 186 | + read_all(ids, db).await | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +pub async fn create_poll( | ||
| 190 | + user_id: Id, | ||
| 191 | + community_id: Id, | ||
| 192 | + question: &str, | ||
| 193 | + options: &[String], | ||
| 194 | + multiple: bool, | ||
| 195 | + db: &Connection, | ||
| 196 | +) -> Result<Message, ServerError> { | ||
| 197 | + let id = insert(user_id, community_id, "", None, db).await?; | ||
| 198 | + poll::create(id, question, options, multiple, db).await?; | ||
| 199 | + | ||
| 200 | + read(id, db).await | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +pub async fn vote( | ||
| 204 | + message_id: Id, | ||
| 205 | + user_id: Id, | ||
| 206 | + positions: &[u32], | ||
| 207 | + db: &Connection, | ||
| 208 | +) -> Result<Message, ServerError> { | ||
| 209 | + poll::set_votes(message_id, user_id, positions, db).await?; | ||
| 210 | + | ||
| 211 | + read(message_id, db).await | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +pub async fn close_poll(message_id: Id, db: &Connection) -> Result<Message, ServerError> { | ||
| 215 | + poll::close(message_id, db).await?; | ||
| 216 | + | ||
| 217 | + read(message_id, db).await | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +pub async fn react( | ||
| 221 | + message_id: Id, | ||
| 222 | + user_id: Id, | ||
| 223 | + emoji: &str, | ||
| 224 | + db: &Connection, | ||
| 225 | +) -> Result<Message, ServerError> { | ||
| 226 | + let removed = run( | ||
| 227 | + db, | ||
| 228 | + "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", | ||
| 229 | + (message_id, user_id, emoji), | ||
| 230 | + ) | ||
| 231 | + .await?; | ||
| 232 | + if removed == 0 { | ||
| 233 | + run( | ||
| 234 | + db, | ||
| 235 | + "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)", | ||
| 236 | + (message_id, user_id, emoji), | ||
| 237 | + ) | ||
| 238 | + .await?; | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + read(message_id, db).await | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +pub async fn pin(message_id: Id, pinned: bool, db: &Connection) -> Result<Message, ServerError> { | ||
| 245 | + run( | ||
| 246 | + db, | ||
| 247 | + "UPDATE message SET pinned = ?2 WHERE id = ?1", | ||
| 248 | + (message_id, pinned), | ||
| 249 | + ) | ||
| 250 | + .await?; | ||
| 251 | + | ||
| 252 | + read(message_id, db).await | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +pub async fn update(message_id: Id, body: &str, db: &Connection) -> Result<Message, ServerError> { | ||
| 256 | + ensure_with( | ||
| 257 | + run( | ||
| 258 | + db, | ||
| 259 | + "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1", | ||
| 260 | + (message_id, body), | ||
| 261 | + ) | ||
| 262 | + .await? | ||
| 263 | + == 1, | ||
| 264 | + Error::NotFound, | ||
| 265 | + )?; | ||
| 266 | + | ||
| 267 | + read(message_id, db).await | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +pub async fn delete(message_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 271 | + ensure_with( | ||
| 272 | + run(db, "DELETE FROM message WHERE id = ?1", (message_id,)).await? == 1, | ||
| 273 | + Error::NotFound, | ||
| 274 | + ) | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +pub async fn delete_where_user(user_id: Id, db: &Connection) -> Result<Vec<(Id, Id)>, ServerError> { | ||
| 278 | + all( | ||
| 279 | + db, | ||
| 280 | + "DELETE FROM message WHERE user_id = ?1 RETURNING community_id, id", | ||
| 281 | + (user_id,), | ||
| 282 | + |r| Ok((r.get()?, r.get()?)), | ||
| 283 | + ) | ||
| 284 | + .await | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +pub async fn delete_before( | ||
| 288 | + cutoff: u64, | ||
| 289 | + limit: u32, | ||
| 290 | + db: &Connection, | ||
| 291 | +) -> Result<Vec<(Id, Id)>, ServerError> { | ||
| 292 | + all( | ||
| 293 | + db, | ||
| 294 | + "DELETE FROM message WHERE id IN (SELECT id FROM message WHERE created_at < ?1 ORDER BY id LIMIT ?2) RETURNING community_id, id", | ||
| 295 | + (cutoff, limit), | ||
| 296 | + |r| Ok((r.get()?, r.get()?)), | ||
| 297 | + ) | ||
| 298 | + .await | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +pub async fn search( | ||
| 302 | + text: Option<&str>, | ||
| 303 | + user_id: Option<Id>, | ||
| 304 | + community_id: Option<Id>, | ||
| 305 | + after_ms: Option<u64>, | ||
| 306 | + before_ms: Option<u64>, | ||
| 307 | + db: &Connection, | ||
| 308 | +) -> Result<Vec<MessageHit>, ServerError> { | ||
| 309 | + let ids: Vec<Id> = all( | ||
| 310 | + db, | ||
| 311 | + "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", | ||
| 312 | + ( | ||
| 313 | + text, | ||
| 314 | + user_id, | ||
| 315 | + community_id, | ||
| 316 | + after_ms.map(|ms| ms as i64), | ||
| 317 | + before_ms.map(|ms| ms as i64), | ||
| 318 | + SEARCH_LIMIT, | ||
| 319 | + ), | ||
| 320 | + |r| r.get(), | ||
| 321 | + ) | ||
| 322 | + .await?; | ||
| 323 | + | ||
| 324 | + let mut hits = Vec::new(); | ||
| 325 | + for id in ids { | ||
| 326 | + let message = read(id, db).await?; | ||
| 327 | + let community = community::label(message.community_id, db).await?; | ||
| 328 | + let author = user::read(message.user_id, db).await?; | ||
| 329 | + hits.push(MessageHit { | ||
| 330 | + message, | ||
| 331 | + community, | ||
| 332 | + author: Some(author), | ||
| 333 | + }); | ||
| 334 | + } | ||
| 335 | + | ||
| 336 | + Ok(hits) | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +async fn origin(sources: &[Message], db: &Connection) -> Result<Option<String>, ServerError> { | ||
| 340 | + let Some(first) = sources.first() else { | ||
| 341 | + return Ok(None); | ||
| 342 | + }; | ||
| 343 | + if sources | ||
| 344 | + .iter() | ||
| 345 | + .any(|source| source.community_id != first.community_id) | ||
| 346 | + { | ||
| 347 | + return Ok(None); | ||
| 348 | + } | ||
| 349 | + | ||
| 350 | + maybe( | ||
| 351 | + db, | ||
| 352 | + "SELECT name FROM community WHERE id = ?1 AND kind = ?2", | ||
| 353 | + (first.community_id, community::Kind::Group.as_str()), | ||
| 354 | + |r| r.get(), | ||
| 355 | + ) | ||
| 356 | + .await | ||
| 357 | +} | ||
| 358 | + | ||
| 359 | +async fn entry(source: &Message, db: &Connection) -> Result<SnippetMessage, ServerError> { | ||
| 360 | + let author = user::read(source.user_id, db).await?; | ||
| 361 | + | ||
| 362 | + Ok(SnippetMessage { | ||
| 363 | + id: source.id, | ||
| 364 | + user_id: author.id, | ||
| 365 | + username: author.username, | ||
| 366 | + avatar_id: author.avatar_id, | ||
| 367 | + created_at: source.created_at, | ||
| 368 | + body: source.body.clone(), | ||
| 369 | + attachments: source.attachments.clone(), | ||
| 370 | + poll: source.poll.clone(), | ||
| 371 | + }) | ||
| 372 | +} | ||
| 373 | + | ||
| 374 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 375 | +pub enum ForwardMode { | ||
| 376 | + Copy, | ||
| 377 | + Snippet, | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +pub async fn forward( | ||
| 381 | + user_id: Id, | ||
| 382 | + community_id: Id, | ||
| 383 | + sources: &[Message], | ||
| 384 | + mode: ForwardMode, | ||
| 385 | + db: &Connection, | ||
| 386 | +) -> Result<Vec<Message>, ServerError> { | ||
| 387 | + if mode == ForwardMode::Copy { | ||
| 388 | + let mut created = Vec::new(); | ||
| 389 | + for source in sources { | ||
| 390 | + let id = insert(user_id, community_id, &source.body, None, db).await?; | ||
| 391 | + for attachment in &source.attachments { | ||
| 392 | + attachment::copy_row(attachment.id, id, user_id, community_id, None, db).await?; | ||
| 393 | + } | ||
| 394 | + if let Some(inner) = &source.snippet { | ||
| 395 | + snippet::write( | ||
| 396 | + id, | ||
| 397 | + user_id, | ||
| 398 | + community_id, | ||
| 399 | + inner.origin.as_deref(), | ||
| 400 | + &inner.messages, | ||
| 401 | + db, | ||
| 402 | + ) | ||
| 403 | + .await?; | ||
| 404 | + } | ||
| 405 | + created.push(read(id, db).await?); | ||
| 406 | + } | ||
| 407 | + | ||
| 408 | + return Ok(created); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + let mut entries = Vec::new(); | ||
| 412 | + for source in sources { | ||
| 413 | + match &source.snippet { | ||
| 414 | + Some(inner) => entries.extend(inner.messages.iter().cloned()), | ||
| 415 | + None => entries.push(entry(source, db).await?), | ||
| 416 | + } | ||
| 417 | + } | ||
| 418 | + if entries.len() > MAXIMUM_FORWARD_MESSAGES { | ||
| 419 | + return Err(Error::Invalid { | ||
| 420 | + field: Field::Forward, | ||
| 421 | + problem: Problem::Length { | ||
| 422 | + min: 1, | ||
| 423 | + max: MAXIMUM_FORWARD_MESSAGES as u64, | ||
| 424 | + actual: entries.len() as u64, | ||
| 425 | + }, | ||
| 426 | + } | ||
| 427 | + .into()); | ||
| 428 | + } | ||
| 429 | + | ||
| 430 | + let origin = origin(sources, db).await?; | ||
| 431 | + let id = insert(user_id, community_id, "", None, db).await?; | ||
| 432 | + snippet::write(id, user_id, community_id, origin.as_deref(), &entries, db).await?; | ||
| 433 | + | ||
| 434 | + Ok(vec![read(id, db).await?]) | ||
| 435 | +} | ||
| 436 | + | ||
| 437 | +#[cfg(test)] | ||
| 438 | +mod tests { | ||
| 439 | + use common::model::Role; | ||
| 440 | + | ||
| 441 | + use super::{ForwardMode, create, forward, read_page}; | ||
| 442 | + use crate::{ | ||
| 443 | + db::{community, user}, | ||
| 444 | + test, | ||
| 445 | + }; | ||
| 446 | + | ||
| 447 | + #[tokio::test] | ||
| 448 | + async fn read_page_orders_and_pages() { | ||
| 449 | + let db = test::db().await; | ||
| 450 | + let conn = db.lock().await.unwrap(); | ||
| 451 | + let user_1 = user::create("Tahinli", "hash", Role::User, &conn) | ||
| 452 | + .await | ||
| 453 | + .unwrap(); | ||
| 454 | + let user_2 = user::create("Not Tahinli", "hash", Role::User, &conn) | ||
| 455 | + .await | ||
| 456 | + .unwrap(); | ||
| 457 | + let community = community::create(community::Kind::Group, "Tahinli", &conn) | ||
| 458 | + .await | ||
| 459 | + .unwrap(); | ||
| 460 | + | ||
| 461 | + let message_1 = create(user_1.id, community, "Tahinli", &[], None, &conn) | ||
| 462 | + .await | ||
| 463 | + .unwrap(); | ||
| 464 | + let message_2 = create(user_2.id, community, "Tahinli", &[], None, &conn) | ||
| 465 | + .await | ||
| 466 | + .unwrap(); | ||
| 467 | + let message_3 = create(user_2.id, community, "Tahinli", &[], None, &conn) | ||
| 468 | + .await | ||
| 469 | + .unwrap(); | ||
| 470 | + | ||
| 471 | + let newest = read_page(community, None, &conn).await.unwrap(); | ||
| 472 | + let older = read_page(community, Some(message_3.id), &conn) | ||
| 473 | + .await | ||
| 474 | + .unwrap(); | ||
| 475 | + | ||
| 476 | + assert_eq!( | ||
| 477 | + vec![message_1.clone(), message_2.clone(), message_3], | ||
| 478 | + newest | ||
| 479 | + ); | ||
| 480 | + assert_eq!(vec![message_1, message_2], older); | ||
| 481 | + } | ||
| 482 | + | ||
| 483 | + #[tokio::test] | ||
| 484 | + async fn forward_two_as_snippet() { | ||
| 485 | + let db = test::db().await; | ||
| 486 | + let conn = db.lock().await.unwrap(); | ||
| 487 | + let user = user::create("Tahinli", "hash", Role::User, &conn) | ||
| 488 | + .await | ||
| 489 | + .unwrap(); | ||
| 490 | + let community = community::create(community::Kind::Group, "Tahinli", &conn) | ||
| 491 | + .await | ||
| 492 | + .unwrap(); | ||
| 493 | + let first = create(user.id, community, "First", &[], None, &conn) | ||
| 494 | + .await | ||
| 495 | + .unwrap(); | ||
| 496 | + let second = create(user.id, community, "Second", &[], None, &conn) | ||
| 497 | + .await | ||
| 498 | + .unwrap(); | ||
| 499 | + | ||
| 500 | + let created = forward( | ||
| 501 | + user.id, | ||
| 502 | + community, | ||
| 503 | + &[first, second], | ||
| 504 | + ForwardMode::Snippet, | ||
| 505 | + &conn, | ||
| 506 | + ) | ||
| 507 | + .await | ||
| 508 | + .unwrap(); | ||
| 509 | + | ||
| 510 | + assert_eq!(1, created.len()); | ||
| 511 | + assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len()); | ||
| 512 | + } | ||
| 513 | +} | ||
crates/server/src/db/mod.rsadded+167 -0
| @@ -0,0 +1,167 @@ | |||
| 1 | +pub mod attachment; | ||
| 2 | +pub mod avatar; | ||
| 3 | +pub mod community; | ||
| 4 | +pub mod direct; | ||
| 5 | +pub mod friend; | ||
| 6 | +pub mod invitation; | ||
| 7 | +pub mod log; | ||
| 8 | +pub mod member; | ||
| 9 | +pub mod message; | ||
| 10 | +pub mod poll; | ||
| 11 | +pub mod registration_code; | ||
| 12 | +pub mod report; | ||
| 13 | +pub mod server_ban; | ||
| 14 | +pub mod session; | ||
| 15 | +pub mod settings; | ||
| 16 | +pub mod snippet; | ||
| 17 | +pub mod stats; | ||
| 18 | +pub mod user; | ||
| 19 | + | ||
| 20 | +use std::sync::Arc; | ||
| 21 | + | ||
| 22 | +use bitcode::DecodeOwned; | ||
| 23 | +use common::{error::Error, model::Named}; | ||
| 24 | +use tokio::sync::{Mutex, MutexGuard}; | ||
| 25 | +use turso::{Builder, Database, IntoParams, Row, core::types::FromValue}; | ||
| 26 | + | ||
| 27 | +pub use turso::Connection; | ||
| 28 | + | ||
| 29 | +use crate::error::ServerError; | ||
| 30 | + | ||
| 31 | +const SCHEMA: &str = include_str!("schema.sql"); | ||
| 32 | + | ||
| 33 | +#[derive(Clone)] | ||
| 34 | +pub struct Db { | ||
| 35 | + database: Database, | ||
| 36 | + conn: Arc<Mutex<Connection>>, | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +impl Db { | ||
| 40 | + pub async fn open(path: &str) -> Result<Self, ServerError> { | ||
| 41 | + let database = Builder::new_local(path).build().await?; | ||
| 42 | + let conn = database.connect()?; | ||
| 43 | + conn.execute_batch("PRAGMA foreign_keys = ON").await?; | ||
| 44 | + if schema(&conn).await?.is_empty() { | ||
| 45 | + conn.execute_batch(SCHEMA).await?; | ||
| 46 | + } | ||
| 47 | + let fresh_database = Builder::new_local(":memory:").build().await?; | ||
| 48 | + let fresh = fresh_database.connect()?; | ||
| 49 | + fresh.execute_batch(SCHEMA).await?; | ||
| 50 | + if schema(&conn).await? != schema(&fresh).await? { | ||
| 51 | + return Err(ServerError::Internal(format!( | ||
| 52 | + "{path} has an old schema, delete it" | ||
| 53 | + ))); | ||
| 54 | + } | ||
| 55 | + settings::read(&conn).await?; | ||
| 56 | + | ||
| 57 | + Ok(Self { | ||
| 58 | + database, | ||
| 59 | + conn: Arc::new(Mutex::new(conn)), | ||
| 60 | + }) | ||
| 61 | + } | ||
| 62 | + | ||
| 63 | + pub async fn lock(&self) -> Result<MutexGuard<'_, Connection>, ServerError> { | ||
| 64 | + let conn = self.conn.lock().await; | ||
| 65 | + if !conn.is_autocommit()? { | ||
| 66 | + conn.execute("ROLLBACK", ()).await?; | ||
| 67 | + } | ||
| 68 | + Ok(conn) | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + pub async fn run<T>( | ||
| 72 | + &self, | ||
| 73 | + work: impl AsyncFnOnce(&Connection) -> Result<T, ServerError>, | ||
| 74 | + ) -> Result<T, ServerError> { | ||
| 75 | + let db = self.lock().await?; | ||
| 76 | + atomic(&db, work(&db)).await | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub async fn backup(&self, target: &str) -> Result<(), ServerError> { | ||
| 80 | + self.database | ||
| 81 | + .connect()? | ||
| 82 | + .execute("VACUUM INTO ?1", (target,)) | ||
| 83 | + .await?; | ||
| 84 | + Ok(()) | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +pub async fn atomic<T>( | ||
| 89 | + db: &Connection, | ||
| 90 | + work: impl Future<Output = Result<T, ServerError>>, | ||
| 91 | +) -> Result<T, ServerError> { | ||
| 92 | + db.execute("BEGIN IMMEDIATE", ()).await?; | ||
| 93 | + let result = work.await; | ||
| 94 | + db.execute(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }, ()) | ||
| 95 | + .await?; | ||
| 96 | + result | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +async fn schema(db: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 100 | + all( | ||
| 101 | + db, | ||
| 102 | + "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY name", | ||
| 103 | + (), | ||
| 104 | + |r| r.get(), | ||
| 105 | + ) | ||
| 106 | + .await | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +pub struct Reader<'a> { | ||
| 110 | + row: &'a Row, | ||
| 111 | + at: usize, | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +impl Reader<'_> { | ||
| 115 | + pub fn get<T: FromValue>(&mut self) -> Result<T, ServerError> { | ||
| 116 | + self.at += 1; | ||
| 117 | + Ok(self.row.get(self.at - 1)?) | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + pub fn named<T: Named>(&mut self) -> Result<T, ServerError> { | ||
| 121 | + let text: String = self.get()?; | ||
| 122 | + T::parse(&text).ok_or_else(|| ServerError::Internal(format!("unknown enum text {text}"))) | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + pub fn blob<T: DecodeOwned>(&mut self) -> Result<T, ServerError> { | ||
| 126 | + let bytes: Vec<u8> = self.get()?; | ||
| 127 | + Ok(bitcode::decode(&bytes)?) | ||
| 128 | + } | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +pub async fn all<T>( | ||
| 132 | + db: &Connection, | ||
| 133 | + sql: &str, | ||
| 134 | + params: impl IntoParams, | ||
| 135 | + read: impl Fn(&mut Reader) -> Result<T, ServerError>, | ||
| 136 | +) -> Result<Vec<T>, ServerError> { | ||
| 137 | + let mut rows = db.prepare_cached(sql).await?.query(params).await?; | ||
| 138 | + let mut values = Vec::new(); | ||
| 139 | + while let Some(row) = rows.next().await? { | ||
| 140 | + values.push(read(&mut Reader { row: &row, at: 0 })?); | ||
| 141 | + } | ||
| 142 | + Ok(values) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +pub async fn maybe<T>( | ||
| 146 | + db: &Connection, | ||
| 147 | + sql: &str, | ||
| 148 | + params: impl IntoParams, | ||
| 149 | + read: impl Fn(&mut Reader) -> Result<T, ServerError>, | ||
| 150 | +) -> Result<Option<T>, ServerError> { | ||
| 151 | + Ok(all(db, sql, params, read).await?.into_iter().next()) | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +pub async fn one<T>( | ||
| 155 | + db: &Connection, | ||
| 156 | + sql: &str, | ||
| 157 | + params: impl IntoParams, | ||
| 158 | + read: impl Fn(&mut Reader) -> Result<T, ServerError>, | ||
| 159 | +) -> Result<T, ServerError> { | ||
| 160 | + maybe(db, sql, params, read) | ||
| 161 | + .await? | ||
| 162 | + .ok_or_else(|| Error::NotFound.into()) | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +pub async fn run(db: &Connection, sql: &str, params: impl IntoParams) -> Result<u64, ServerError> { | ||
| 166 | + Ok(db.prepare_cached(sql).await?.execute(params).await?) | ||
| 167 | +} | ||
crates/server/src/db/poll.rsadded+114 -0
| @@ -0,0 +1,114 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::{Id, Poll, PollOption}, | ||
| 4 | +}; | ||
| 5 | + | ||
| 6 | +use super::{Connection, all, maybe, run}; | ||
| 7 | +use crate::error::{ServerError, ensure_with}; | ||
| 8 | + | ||
| 9 | +pub async fn create( | ||
| 10 | + message_id: Id, | ||
| 11 | + question: &str, | ||
| 12 | + options: &[String], | ||
| 13 | + multiple: bool, | ||
| 14 | + db: &Connection, | ||
| 15 | +) -> Result<(), ServerError> { | ||
| 16 | + run( | ||
| 17 | + db, | ||
| 18 | + "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", | ||
| 19 | + (message_id, question, multiple), | ||
| 20 | + ) | ||
| 21 | + .await?; | ||
| 22 | + for (position, text) in (0u32..).zip(options) { | ||
| 23 | + run( | ||
| 24 | + db, | ||
| 25 | + "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)", | ||
| 26 | + (message_id, position, text.as_str()), | ||
| 27 | + ) | ||
| 28 | + .await?; | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + Ok(()) | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +pub async fn of(message_id: Id, db: &Connection) -> Result<Option<Poll>, ServerError> { | ||
| 35 | + let Some((question, multiple, closed)) = maybe( | ||
| 36 | + db, | ||
| 37 | + "SELECT question, multiple, closed FROM poll WHERE message_id = ?1", | ||
| 38 | + (message_id,), | ||
| 39 | + |r| Ok((r.get::<String>()?, r.get::<bool>()?, r.get::<bool>()?)), | ||
| 40 | + ) | ||
| 41 | + .await? | ||
| 42 | + else { | ||
| 43 | + return Ok(None); | ||
| 44 | + }; | ||
| 45 | + | ||
| 46 | + let mut options: Vec<PollOption> = all( | ||
| 47 | + db, | ||
| 48 | + "SELECT text FROM poll_option WHERE message_id = ?1 ORDER BY position", | ||
| 49 | + (message_id,), | ||
| 50 | + |r| { | ||
| 51 | + Ok(PollOption { | ||
| 52 | + text: r.get()?, | ||
| 53 | + voter_ids: Vec::new(), | ||
| 54 | + }) | ||
| 55 | + }, | ||
| 56 | + ) | ||
| 57 | + .await?; | ||
| 58 | + let votes: Vec<(u32, Id)> = all( | ||
| 59 | + db, | ||
| 60 | + "SELECT position, user_id FROM poll_vote WHERE message_id = ?1 ORDER BY position, user_id", | ||
| 61 | + (message_id,), | ||
| 62 | + |r| Ok((r.get()?, r.get()?)), | ||
| 63 | + ) | ||
| 64 | + .await?; | ||
| 65 | + for (position, user_id) in votes { | ||
| 66 | + if let Some(option) = options.get_mut(position as usize) { | ||
| 67 | + option.voter_ids.push(user_id); | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + Ok(Some(Poll { | ||
| 72 | + question, | ||
| 73 | + options, | ||
| 74 | + multiple, | ||
| 75 | + closed, | ||
| 76 | + })) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +pub async fn set_votes( | ||
| 80 | + message_id: Id, | ||
| 81 | + user_id: Id, | ||
| 82 | + positions: &[u32], | ||
| 83 | + db: &Connection, | ||
| 84 | +) -> Result<(), ServerError> { | ||
| 85 | + run( | ||
| 86 | + db, | ||
| 87 | + "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", | ||
| 88 | + (message_id, user_id), | ||
| 89 | + ) | ||
| 90 | + .await?; | ||
| 91 | + for position in positions { | ||
| 92 | + run( | ||
| 93 | + db, | ||
| 94 | + "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)", | ||
| 95 | + (message_id, *position, user_id), | ||
| 96 | + ) | ||
| 97 | + .await?; | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + Ok(()) | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +pub async fn close(message_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 104 | + ensure_with( | ||
| 105 | + run( | ||
| 106 | + db, | ||
| 107 | + "UPDATE poll SET closed = 1 WHERE message_id = ?1", | ||
| 108 | + (message_id,), | ||
| 109 | + ) | ||
| 110 | + .await? | ||
| 111 | + == 1, | ||
| 112 | + Error::NotFound, | ||
| 113 | + ) | ||
| 114 | +} | ||
crates/server/src/db/registration_code.rsadded+60 -0
| @@ -0,0 +1,60 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::InviteCode, | ||
| 4 | + time::{HOUR_MILLIS, now_ms}, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use super::{Connection, all, run}; | ||
| 8 | +use crate::error::{ServerError, ensure_with}; | ||
| 9 | + | ||
| 10 | +pub async fn create( | ||
| 11 | + code: &str, | ||
| 12 | + uses: u32, | ||
| 13 | + hours: Option<u32>, | ||
| 14 | + db: &Connection, | ||
| 15 | +) -> Result<InviteCode, ServerError> { | ||
| 16 | + let expires_at = hours.map(|hours| now_ms() + u64::from(hours) * HOUR_MILLIS); | ||
| 17 | + run( | ||
| 18 | + db, | ||
| 19 | + "INSERT INTO registration_code (code, uses_left, expires_at) VALUES (?1, ?2, ?3)", | ||
| 20 | + (code, uses, expires_at.map(|ms| ms as i64)), | ||
| 21 | + ) | ||
| 22 | + .await?; | ||
| 23 | + | ||
| 24 | + Ok(InviteCode { | ||
| 25 | + code: code.to_string(), | ||
| 26 | + uses_left: uses, | ||
| 27 | + expires_at, | ||
| 28 | + }) | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +pub async fn list(db: &Connection) -> Result<Vec<InviteCode>, ServerError> { | ||
| 32 | + all( | ||
| 33 | + db, | ||
| 34 | + "SELECT code, uses_left, expires_at FROM registration_code", | ||
| 35 | + (), | ||
| 36 | + |r| { | ||
| 37 | + Ok(InviteCode { | ||
| 38 | + code: r.get()?, | ||
| 39 | + uses_left: r.get()?, | ||
| 40 | + expires_at: r.get()?, | ||
| 41 | + }) | ||
| 42 | + }, | ||
| 43 | + ) | ||
| 44 | + .await | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +pub async fn delete(code: &str, db: &Connection) -> Result<(), ServerError> { | ||
| 48 | + let deleted = run(db, "DELETE FROM registration_code WHERE code = ?1", (code,)).await?; | ||
| 49 | + ensure_with(deleted == 1, Error::NotFound) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +pub async fn consume(code: &str, db: &Connection) -> Result<(), ServerError> { | ||
| 53 | + let updated = run( | ||
| 54 | + db, | ||
| 55 | + "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)", | ||
| 56 | + (code, now_ms()), | ||
| 57 | + ) | ||
| 58 | + .await?; | ||
| 59 | + ensure_with(updated == 1, Error::RegistrationClosed) | ||
| 60 | +} | ||
crates/server/src/db/report.rsadded+126 -0
| @@ -0,0 +1,126 @@ | |||
| 1 | +use common::{ | ||
| 2 | + constant::LOG_PAGE_LIMIT, | ||
| 3 | + model::{Id, Report, ReportStatus}, | ||
| 4 | + time::now_ms, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use super::{Connection, all, log::optional_user, one, run}; | ||
| 8 | +use crate::error::ServerError; | ||
| 9 | + | ||
| 10 | +struct Raw { | ||
| 11 | + id: Id, | ||
| 12 | + created_at: u64, | ||
| 13 | + reporter_id: Option<Id>, | ||
| 14 | + target_id: Option<Id>, | ||
| 15 | + community: Option<String>, | ||
| 16 | + message_id: Option<Id>, | ||
| 17 | + community_id: Option<Id>, | ||
| 18 | + body: Option<String>, | ||
| 19 | + reason: String, | ||
| 20 | + status: ReportStatus, | ||
| 21 | + handled_by: Option<Id>, | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +pub async fn is_open( | ||
| 25 | + reporter_id: Id, | ||
| 26 | + target_id: Id, | ||
| 27 | + message_id: Option<Id>, | ||
| 28 | + db: &Connection, | ||
| 29 | +) -> Result<bool, ServerError> { | ||
| 30 | + one( | ||
| 31 | + db, | ||
| 32 | + "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", | ||
| 33 | + (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), | ||
| 34 | + |r| r.get(), | ||
| 35 | + ) | ||
| 36 | + .await | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +pub async fn insert( | ||
| 40 | + reporter_id: Id, | ||
| 41 | + target_id: Id, | ||
| 42 | + message_id: Option<Id>, | ||
| 43 | + community_id: Option<Id>, | ||
| 44 | + body: Option<&str>, | ||
| 45 | + reason: &str, | ||
| 46 | + db: &Connection, | ||
| 47 | +) -> Result<(), ServerError> { | ||
| 48 | + run( | ||
| 49 | + db, | ||
| 50 | + "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)", | ||
| 51 | + ( | ||
| 52 | + now_ms(), | ||
| 53 | + reporter_id, | ||
| 54 | + target_id, | ||
| 55 | + message_id, | ||
| 56 | + community_id, | ||
| 57 | + body, | ||
| 58 | + reason, | ||
| 59 | + ReportStatus::Open.as_str(), | ||
| 60 | + ), | ||
| 61 | + ) | ||
| 62 | + .await?; | ||
| 63 | + | ||
| 64 | + Ok(()) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +pub async fn list( | ||
| 68 | + status: Option<ReportStatus>, | ||
| 69 | + db: &Connection, | ||
| 70 | +) -> Result<Vec<Report>, ServerError> { | ||
| 71 | + let raws = all( | ||
| 72 | + db, | ||
| 73 | + "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", | ||
| 74 | + (status.map(ReportStatus::as_str), LOG_PAGE_LIMIT), | ||
| 75 | + |r| { | ||
| 76 | + Ok(Raw { | ||
| 77 | + id: r.get()?, | ||
| 78 | + created_at: r.get()?, | ||
| 79 | + reporter_id: r.get()?, | ||
| 80 | + target_id: r.get()?, | ||
| 81 | + community: r.get()?, | ||
| 82 | + message_id: r.get()?, | ||
| 83 | + community_id: r.get()?, | ||
| 84 | + body: r.get()?, | ||
| 85 | + reason: r.get()?, | ||
| 86 | + status: r.named()?, | ||
| 87 | + handled_by: r.get()?, | ||
| 88 | + }) | ||
| 89 | + }, | ||
| 90 | + ) | ||
| 91 | + .await?; | ||
| 92 | + | ||
| 93 | + let mut reports = Vec::new(); | ||
| 94 | + for raw in raws { | ||
| 95 | + reports.push(Report { | ||
| 96 | + id: raw.id, | ||
| 97 | + created_at: raw.created_at, | ||
| 98 | + reporter: optional_user(raw.reporter_id, db).await?, | ||
| 99 | + target: optional_user(raw.target_id, db).await?, | ||
| 100 | + message_id: raw.message_id, | ||
| 101 | + community_id: raw.community_id, | ||
| 102 | + community: raw.community, | ||
| 103 | + body: raw.body, | ||
| 104 | + reason: raw.reason, | ||
| 105 | + status: raw.status, | ||
| 106 | + handled_by: optional_user(raw.handled_by, db).await?, | ||
| 107 | + }); | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + Ok(reports) | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +pub async fn handle( | ||
| 114 | + report_id: Id, | ||
| 115 | + status: ReportStatus, | ||
| 116 | + handled_by: Id, | ||
| 117 | + db: &Connection, | ||
| 118 | +) -> Result<Option<Id>, ServerError> { | ||
| 119 | + one( | ||
| 120 | + db, | ||
| 121 | + "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", | ||
| 122 | + (report_id, status.as_str(), handled_by, ReportStatus::Open.as_str()), | ||
| 123 | + |r| r.get(), | ||
| 124 | + ) | ||
| 125 | + .await | ||
| 126 | +} | ||
crates/server/src/db/schema.sqladded+215 -0
| @@ -0,0 +1,215 @@ | |||
| 1 | +CREATE TABLE user ( | ||
| 2 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 3 | + username TEXT NOT NULL UNIQUE COLLATE NOCASE, | ||
| 4 | + password_hash TEXT NOT NULL, | ||
| 5 | + role TEXT NOT NULL, | ||
| 6 | + status TEXT NOT NULL DEFAULT '', | ||
| 7 | + presence TEXT NOT NULL, | ||
| 8 | + suspended INTEGER NOT NULL DEFAULT 0, | ||
| 9 | + suspended_until INTEGER, | ||
| 10 | + voice_muted INTEGER NOT NULL DEFAULT 0, | ||
| 11 | + ghost INTEGER NOT NULL DEFAULT 0, | ||
| 12 | + last_ip TEXT, | ||
| 13 | + last_seen INTEGER, | ||
| 14 | + created_at INTEGER NOT NULL | ||
| 15 | +) STRICT; | ||
| 16 | + | ||
| 17 | +CREATE TABLE session ( | ||
| 18 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 19 | + token_hash BLOB NOT NULL UNIQUE, | ||
| 20 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 21 | + device TEXT NOT NULL DEFAULT '', | ||
| 22 | + last_seen INTEGER | ||
| 23 | +) STRICT; | ||
| 24 | +CREATE INDEX session_user ON session (user_id); | ||
| 25 | + | ||
| 26 | +CREATE TABLE community ( | ||
| 27 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 28 | + kind TEXT NOT NULL, | ||
| 29 | + name TEXT NOT NULL DEFAULT '' COLLATE NOCASE, | ||
| 30 | + voice_enabled INTEGER NOT NULL | ||
| 31 | +) STRICT; | ||
| 32 | + | ||
| 33 | +CREATE TABLE avatar ( | ||
| 34 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 35 | + user_id INTEGER UNIQUE REFERENCES user (id) ON DELETE CASCADE, | ||
| 36 | + community_id INTEGER UNIQUE REFERENCES community (id) ON DELETE CASCADE, | ||
| 37 | + data BLOB NOT NULL, | ||
| 38 | + CHECK ((user_id IS NULL) != (community_id IS NULL)) | ||
| 39 | +) STRICT; | ||
| 40 | + | ||
| 41 | +CREATE TABLE member ( | ||
| 42 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 43 | + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 44 | + rank TEXT NOT NULL, | ||
| 45 | + last_read INTEGER, | ||
| 46 | + PRIMARY KEY (user_id, community_id) | ||
| 47 | +) STRICT; | ||
| 48 | +CREATE INDEX member_community ON member (community_id); | ||
| 49 | + | ||
| 50 | +CREATE TABLE community_ban ( | ||
| 51 | + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 52 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 53 | + reason TEXT, | ||
| 54 | + PRIMARY KEY (community_id, user_id) | ||
| 55 | +) STRICT; | ||
| 56 | + | ||
| 57 | +CREATE TABLE direct ( | ||
| 58 | + user_a INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 59 | + user_b INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 60 | + community_id INTEGER NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE, | ||
| 61 | + PRIMARY KEY (user_a, user_b), | ||
| 62 | + CHECK (user_a <= user_b) | ||
| 63 | +) STRICT; | ||
| 64 | + | ||
| 65 | +CREATE TABLE invitation ( | ||
| 66 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 67 | + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 68 | + inviter_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 69 | + PRIMARY KEY (user_id, community_id) | ||
| 70 | +) STRICT; | ||
| 71 | + | ||
| 72 | +CREATE TABLE friend ( | ||
| 73 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 74 | + friend_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 75 | + state TEXT NOT NULL, | ||
| 76 | + PRIMARY KEY (user_id, friend_id) | ||
| 77 | +) STRICT; | ||
| 78 | + | ||
| 79 | +CREATE TABLE message ( | ||
| 80 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 81 | + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 82 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 83 | + created_at INTEGER NOT NULL, | ||
| 84 | + body TEXT NOT NULL, | ||
| 85 | + reply_to INTEGER REFERENCES message (id) ON DELETE SET NULL, | ||
| 86 | + edited INTEGER NOT NULL DEFAULT 0, | ||
| 87 | + pinned INTEGER NOT NULL DEFAULT 0, | ||
| 88 | + call TEXT, | ||
| 89 | + call_seconds INTEGER NOT NULL DEFAULT 0 | ||
| 90 | +) STRICT; | ||
| 91 | +CREATE INDEX message_community ON message (community_id, id); | ||
| 92 | +CREATE INDEX message_user ON message (user_id); | ||
| 93 | +CREATE INDEX message_created ON message (created_at); | ||
| 94 | +CREATE INDEX message_reply ON message (reply_to); | ||
| 95 | + | ||
| 96 | +CREATE TABLE attachment ( | ||
| 97 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 98 | + uploader_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 99 | + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 100 | + message_id INTEGER REFERENCES message (id) ON DELETE CASCADE, | ||
| 101 | + snippet_position INTEGER, | ||
| 102 | + created_at INTEGER NOT NULL, | ||
| 103 | + file TEXT NOT NULL, | ||
| 104 | + name TEXT NOT NULL, | ||
| 105 | + size INTEGER NOT NULL, | ||
| 106 | + kind TEXT NOT NULL, | ||
| 107 | + width INTEGER, | ||
| 108 | + height INTEGER | ||
| 109 | +) STRICT; | ||
| 110 | +CREATE INDEX attachment_message ON attachment (message_id); | ||
| 111 | +CREATE INDEX attachment_uploader ON attachment (uploader_id); | ||
| 112 | +CREATE INDEX attachment_community ON attachment (community_id); | ||
| 113 | + | ||
| 114 | +CREATE TABLE reaction ( | ||
| 115 | + message_id INTEGER NOT NULL REFERENCES message (id) ON DELETE CASCADE, | ||
| 116 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 117 | + emoji TEXT NOT NULL, | ||
| 118 | + PRIMARY KEY (message_id, user_id, emoji) | ||
| 119 | +) STRICT; | ||
| 120 | + | ||
| 121 | +CREATE TABLE poll ( | ||
| 122 | + message_id INTEGER PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, | ||
| 123 | + question TEXT NOT NULL, | ||
| 124 | + multiple INTEGER NOT NULL, | ||
| 125 | + closed INTEGER NOT NULL DEFAULT 0 | ||
| 126 | +) STRICT; | ||
| 127 | + | ||
| 128 | +CREATE TABLE poll_option ( | ||
| 129 | + message_id INTEGER NOT NULL REFERENCES poll (message_id) ON DELETE CASCADE, | ||
| 130 | + position INTEGER NOT NULL, | ||
| 131 | + text TEXT NOT NULL, | ||
| 132 | + PRIMARY KEY (message_id, position) | ||
| 133 | +) STRICT; | ||
| 134 | + | ||
| 135 | +CREATE TABLE poll_vote ( | ||
| 136 | + message_id INTEGER NOT NULL REFERENCES poll (message_id) ON DELETE CASCADE, | ||
| 137 | + position INTEGER NOT NULL, | ||
| 138 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 139 | + PRIMARY KEY (message_id, position, user_id) | ||
| 140 | +) STRICT; | ||
| 141 | + | ||
| 142 | +CREATE TABLE snippet ( | ||
| 143 | + message_id INTEGER PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, | ||
| 144 | + origin TEXT | ||
| 145 | +) STRICT; | ||
| 146 | + | ||
| 147 | +CREATE TABLE snippet_message ( | ||
| 148 | + message_id INTEGER NOT NULL REFERENCES snippet (message_id) ON DELETE CASCADE, | ||
| 149 | + position INTEGER NOT NULL, | ||
| 150 | + original_id INTEGER NOT NULL, | ||
| 151 | + user_id INTEGER NOT NULL, | ||
| 152 | + username TEXT NOT NULL, | ||
| 153 | + created_at INTEGER NOT NULL, | ||
| 154 | + body TEXT NOT NULL, | ||
| 155 | + poll BLOB NOT NULL, | ||
| 156 | + PRIMARY KEY (message_id, position) | ||
| 157 | +) STRICT; | ||
| 158 | + | ||
| 159 | +CREATE TABLE community_log ( | ||
| 160 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 161 | + community_id INTEGER NOT NULL REFERENCES community (id) ON DELETE CASCADE, | ||
| 162 | + created_at INTEGER NOT NULL, | ||
| 163 | + actor_id INTEGER REFERENCES user (id) ON DELETE SET NULL, | ||
| 164 | + target_id INTEGER REFERENCES user (id) ON DELETE SET NULL, | ||
| 165 | + action BLOB NOT NULL | ||
| 166 | +) STRICT; | ||
| 167 | +CREATE INDEX community_log_community ON community_log (community_id, id); | ||
| 168 | + | ||
| 169 | +CREATE TABLE admin_log ( | ||
| 170 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 171 | + created_at INTEGER NOT NULL, | ||
| 172 | + actor_id INTEGER REFERENCES user (id) ON DELETE SET NULL, | ||
| 173 | + target_id INTEGER REFERENCES user (id) ON DELETE SET NULL, | ||
| 174 | + community TEXT, | ||
| 175 | + kind TEXT NOT NULL, | ||
| 176 | + action BLOB NOT NULL | ||
| 177 | +) STRICT; | ||
| 178 | + | ||
| 179 | +CREATE TABLE report ( | ||
| 180 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 181 | + created_at INTEGER NOT NULL, | ||
| 182 | + reporter_id INTEGER REFERENCES user (id) ON DELETE SET NULL, | ||
| 183 | + target_id INTEGER REFERENCES user (id) ON DELETE SET NULL, | ||
| 184 | + message_id INTEGER, | ||
| 185 | + community_id INTEGER, | ||
| 186 | + body TEXT, | ||
| 187 | + reason TEXT NOT NULL, | ||
| 188 | + status TEXT NOT NULL, | ||
| 189 | + handled_by INTEGER REFERENCES user (id) ON DELETE SET NULL | ||
| 190 | +) STRICT; | ||
| 191 | + | ||
| 192 | +CREATE TABLE server_ban ( | ||
| 193 | + id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| 194 | + kind TEXT NOT NULL, | ||
| 195 | + value TEXT NOT NULL COLLATE NOCASE, | ||
| 196 | + reason TEXT, | ||
| 197 | + UNIQUE (kind, value) | ||
| 198 | +) STRICT; | ||
| 199 | + | ||
| 200 | +CREATE TABLE registration_code ( | ||
| 201 | + code TEXT PRIMARY KEY, | ||
| 202 | + uses_left INTEGER NOT NULL, | ||
| 203 | + expires_at INTEGER | ||
| 204 | +) STRICT; | ||
| 205 | + | ||
| 206 | +CREATE TABLE daily_active ( | ||
| 207 | + day INTEGER NOT NULL, | ||
| 208 | + user_id INTEGER NOT NULL REFERENCES user (id) ON DELETE CASCADE, | ||
| 209 | + PRIMARY KEY (day, user_id) | ||
| 210 | +) STRICT; | ||
| 211 | + | ||
| 212 | +CREATE TABLE server_settings ( | ||
| 213 | + id INTEGER PRIMARY KEY CHECK (id = 1), | ||
| 214 | + data BLOB NOT NULL | ||
| 215 | +) STRICT; | ||
crates/server/src/db/server_ban.rsadded+63 -0
| @@ -0,0 +1,63 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::{Id, ServerBan, ServerBanKind}, | ||
| 4 | +}; | ||
| 5 | + | ||
| 6 | +use super::{Connection, all, one, run}; | ||
| 7 | +use crate::error::{ServerError, ensure_with}; | ||
| 8 | + | ||
| 9 | +pub async fn insert( | ||
| 10 | + kind: ServerBanKind, | ||
| 11 | + value: &str, | ||
| 12 | + reason: Option<&str>, | ||
| 13 | + db: &Connection, | ||
| 14 | +) -> Result<(), ServerError> { | ||
| 15 | + run( | ||
| 16 | + db, | ||
| 17 | + "INSERT OR IGNORE INTO server_ban (kind, value, reason) VALUES (?1, ?2, ?3)", | ||
| 18 | + (kind.as_str(), value, reason), | ||
| 19 | + ) | ||
| 20 | + .await?; | ||
| 21 | + | ||
| 22 | + Ok(()) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +pub async fn list(db: &Connection) -> Result<Vec<ServerBan>, ServerError> { | ||
| 26 | + all( | ||
| 27 | + db, | ||
| 28 | + "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", | ||
| 29 | + (), | ||
| 30 | + |r| { | ||
| 31 | + Ok(ServerBan { | ||
| 32 | + id: r.get()?, | ||
| 33 | + kind: r.named()?, | ||
| 34 | + value: r.get()?, | ||
| 35 | + reason: r.get()?, | ||
| 36 | + }) | ||
| 37 | + }, | ||
| 38 | + ) | ||
| 39 | + .await | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +async fn exists(kind: ServerBanKind, value: &str, db: &Connection) -> Result<bool, ServerError> { | ||
| 43 | + one( | ||
| 44 | + db, | ||
| 45 | + "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", | ||
| 46 | + (kind.as_str(), value), | ||
| 47 | + |r| r.get(), | ||
| 48 | + ) | ||
| 49 | + .await | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +pub async fn username_banned(username: &str, db: &Connection) -> Result<bool, ServerError> { | ||
| 53 | + exists(ServerBanKind::Username, username, db).await | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +pub async fn ip_banned(ip: &str, db: &Connection) -> Result<bool, ServerError> { | ||
| 57 | + exists(ServerBanKind::Ip, ip, db).await | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +pub async fn remove(id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 61 | + let deleted = run(db, "DELETE FROM server_ban WHERE id = ?1", (id,)).await?; | ||
| 62 | + ensure_with(deleted == 1, Error::NotFound) | ||
| 63 | +} | ||
crates/server/src/db/session.rsadded+109 -0
| @@ -0,0 +1,109 @@ | |||
| 1 | +use common::{ | ||
| 2 | + model::{Id, SessionInfo, User}, | ||
| 3 | + time::now_ms, | ||
| 4 | +}; | ||
| 5 | + | ||
| 6 | +use super::{Connection, all, maybe, one, run, user}; | ||
| 7 | +use crate::error::ServerError; | ||
| 8 | + | ||
| 9 | +pub async fn insert(token_hash: &[u8], user_id: Id, db: &Connection) -> Result<Id, ServerError> { | ||
| 10 | + one( | ||
| 11 | + db, | ||
| 12 | + "INSERT INTO session (token_hash, user_id) VALUES (?1, ?2) RETURNING id", | ||
| 13 | + (token_hash, user_id), | ||
| 14 | + |r| r.get(), | ||
| 15 | + ) | ||
| 16 | + .await | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +pub async fn find(token_hash: &[u8], db: &Connection) -> Result<Option<(Id, User)>, ServerError> { | ||
| 20 | + maybe( | ||
| 21 | + db, | ||
| 22 | + &format!( | ||
| 23 | + "SELECT session.id, {} FROM session JOIN user ON user.id = session.user_id WHERE session.token_hash = ?1", | ||
| 24 | + user::COLUMNS | ||
| 25 | + ), | ||
| 26 | + (token_hash,), | ||
| 27 | + |r| Ok((r.get()?, user::row(r)?)), | ||
| 28 | + ) | ||
| 29 | + .await | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +pub async fn user_of(session_id: Id, db: &Connection) -> Result<Option<User>, ServerError> { | ||
| 33 | + maybe( | ||
| 34 | + db, | ||
| 35 | + &format!( | ||
| 36 | + "SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.id = ?1", | ||
| 37 | + user::COLUMNS | ||
| 38 | + ), | ||
| 39 | + (session_id,), | ||
| 40 | + user::row, | ||
| 41 | + ) | ||
| 42 | + .await | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +pub async fn seen(session_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 46 | + let now = now_ms(); | ||
| 47 | + run( | ||
| 48 | + db, | ||
| 49 | + "UPDATE user SET last_seen = ?2 WHERE id = (SELECT user_id FROM session WHERE id = ?1) AND ghost = 0", | ||
| 50 | + (session_id, now), | ||
| 51 | + ) | ||
| 52 | + .await?; | ||
| 53 | + run( | ||
| 54 | + db, | ||
| 55 | + "UPDATE session SET last_seen = ?2 WHERE id = ?1 AND user_id IN (SELECT id FROM user WHERE ghost = 0)", | ||
| 56 | + (session_id, now), | ||
| 57 | + ) | ||
| 58 | + .await?; | ||
| 59 | + | ||
| 60 | + Ok(()) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +pub async fn set_device(session_id: Id, device: &str, db: &Connection) -> Result<(), ServerError> { | ||
| 64 | + run( | ||
| 65 | + db, | ||
| 66 | + "UPDATE session SET device = ?2 WHERE id = ?1", | ||
| 67 | + (session_id, device), | ||
| 68 | + ) | ||
| 69 | + .await?; | ||
| 70 | + | ||
| 71 | + Ok(()) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +pub async fn list(user_id: Id, db: &Connection) -> Result<Vec<SessionInfo>, ServerError> { | ||
| 75 | + all( | ||
| 76 | + db, | ||
| 77 | + "SELECT id, device, last_seen FROM session WHERE user_id = ?1 ORDER BY last_seen DESC", | ||
| 78 | + (user_id,), | ||
| 79 | + |r| { | ||
| 80 | + Ok(SessionInfo { | ||
| 81 | + id: r.get()?, | ||
| 82 | + device: r.get()?, | ||
| 83 | + last_seen: r.get()?, | ||
| 84 | + }) | ||
| 85 | + }, | ||
| 86 | + ) | ||
| 87 | + .await | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +pub async fn delete(session_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 91 | + run(db, "DELETE FROM session WHERE id = ?1", (session_id,)).await?; | ||
| 92 | + | ||
| 93 | + Ok(()) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +pub async fn delete_of(user_id: Id, session_id: Id, db: &Connection) -> Result<u64, ServerError> { | ||
| 97 | + run( | ||
| 98 | + db, | ||
| 99 | + "DELETE FROM session WHERE id = ?1 AND user_id = ?2", | ||
| 100 | + (session_id, user_id), | ||
| 101 | + ) | ||
| 102 | + .await | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +pub async fn delete_all(user_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 106 | + run(db, "DELETE FROM session WHERE user_id = ?1", (user_id,)).await?; | ||
| 107 | + | ||
| 108 | + Ok(()) | ||
| 109 | +} | ||
crates/server/src/db/settings.rsadded+26 -0
| @@ -0,0 +1,26 @@ | |||
| 1 | +use common::model::ServerSettings; | ||
| 2 | + | ||
| 3 | +use super::{Connection, maybe, run}; | ||
| 4 | +use crate::error::ServerError; | ||
| 5 | + | ||
| 6 | +pub async fn read(db: &Connection) -> Result<ServerSettings, ServerError> { | ||
| 7 | + Ok(maybe( | ||
| 8 | + db, | ||
| 9 | + "SELECT data FROM server_settings WHERE id = 1", | ||
| 10 | + (), | ||
| 11 | + |r| r.blob::<ServerSettings>(), | ||
| 12 | + ) | ||
| 13 | + .await? | ||
| 14 | + .unwrap_or_default()) | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +pub async fn update(settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> { | ||
| 18 | + run( | ||
| 19 | + db, | ||
| 20 | + "INSERT OR REPLACE INTO server_settings (id, data) VALUES (1, ?1)", | ||
| 21 | + (bitcode::encode(settings),), | ||
| 22 | + ) | ||
| 23 | + .await?; | ||
| 24 | + | ||
| 25 | + Ok(()) | ||
| 26 | +} | ||
crates/server/src/db/snippet.rsadded+94 -0
| @@ -0,0 +1,94 @@ | |||
| 1 | +use common::model::{Id, Poll, Snippet, SnippetMessage}; | ||
| 2 | + | ||
| 3 | +use super::{Connection, all, attachment, maybe, run}; | ||
| 4 | +use crate::error::ServerError; | ||
| 5 | + | ||
| 6 | +pub async fn of(message_id: Id, db: &Connection) -> Result<Option<Snippet>, ServerError> { | ||
| 7 | + let Some(origin) = maybe( | ||
| 8 | + db, | ||
| 9 | + "SELECT origin FROM snippet WHERE message_id = ?1", | ||
| 10 | + (message_id,), | ||
| 11 | + |r| r.get::<Option<String>>(), | ||
| 12 | + ) | ||
| 13 | + .await? | ||
| 14 | + else { | ||
| 15 | + return Ok(None); | ||
| 16 | + }; | ||
| 17 | + | ||
| 18 | + let entries: Vec<(u32, SnippetMessage)> = all( | ||
| 19 | + db, | ||
| 20 | + "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", | ||
| 21 | + (message_id,), | ||
| 22 | + |r| { | ||
| 23 | + Ok(( | ||
| 24 | + r.get()?, | ||
| 25 | + SnippetMessage { | ||
| 26 | + id: r.get()?, | ||
| 27 | + user_id: r.get()?, | ||
| 28 | + username: r.get()?, | ||
| 29 | + avatar_id: r.get()?, | ||
| 30 | + created_at: r.get()?, | ||
| 31 | + body: r.get()?, | ||
| 32 | + attachments: Vec::new(), | ||
| 33 | + poll: r.blob::<Option<Poll>>()?, | ||
| 34 | + }, | ||
| 35 | + )) | ||
| 36 | + }, | ||
| 37 | + ) | ||
| 38 | + .await?; | ||
| 39 | + | ||
| 40 | + let mut messages = Vec::new(); | ||
| 41 | + for (position, mut entry) in entries { | ||
| 42 | + entry.attachments = attachment::of_message(message_id, Some(position), db).await?; | ||
| 43 | + messages.push(entry); | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + Ok(Some(Snippet { origin, messages })) | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +pub async fn write( | ||
| 50 | + message_id: Id, | ||
| 51 | + user_id: Id, | ||
| 52 | + community_id: Id, | ||
| 53 | + origin: Option<&str>, | ||
| 54 | + entries: &[SnippetMessage], | ||
| 55 | + db: &Connection, | ||
| 56 | +) -> Result<(), ServerError> { | ||
| 57 | + run( | ||
| 58 | + db, | ||
| 59 | + "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)", | ||
| 60 | + (message_id, origin), | ||
| 61 | + ) | ||
| 62 | + .await?; | ||
| 63 | + | ||
| 64 | + for (position, entry) in (0u32..).zip(entries) { | ||
| 65 | + run( | ||
| 66 | + db, | ||
| 67 | + "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)", | ||
| 68 | + ( | ||
| 69 | + message_id, | ||
| 70 | + position, | ||
| 71 | + entry.id, | ||
| 72 | + entry.user_id, | ||
| 73 | + entry.username.as_str(), | ||
| 74 | + entry.created_at, | ||
| 75 | + entry.body.as_str(), | ||
| 76 | + bitcode::encode(&entry.poll), | ||
| 77 | + ), | ||
| 78 | + ) | ||
| 79 | + .await?; | ||
| 80 | + for attachment in &entry.attachments { | ||
| 81 | + attachment::copy_row( | ||
| 82 | + attachment.id, | ||
| 83 | + message_id, | ||
| 84 | + user_id, | ||
| 85 | + community_id, | ||
| 86 | + Some(position), | ||
| 87 | + db, | ||
| 88 | + ) | ||
| 89 | + .await?; | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + Ok(()) | ||
| 94 | +} | ||
crates/server/src/db/stats.rsadded+69 -0
| @@ -0,0 +1,69 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | + | ||
| 3 | +use common::{ | ||
| 4 | + model::{DayStat, Id, Role}, | ||
| 5 | + time::{DAY_MILLIS, now_ms}, | ||
| 6 | +}; | ||
| 7 | + | ||
| 8 | +use super::{Connection, all, community::Kind, one, run}; | ||
| 9 | +use crate::error::ServerError; | ||
| 10 | + | ||
| 11 | +const MAXIMUM_DAYS: u32 = 90; | ||
| 12 | + | ||
| 13 | +pub async fn mark_active(user_id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 14 | + run( | ||
| 15 | + db, | ||
| 16 | + "INSERT OR IGNORE INTO daily_active (day, user_id) SELECT ?1, id FROM user WHERE id = ?2 AND ghost = 0", | ||
| 17 | + (now_ms() / DAY_MILLIS, user_id), | ||
| 18 | + ) | ||
| 19 | + .await?; | ||
| 20 | + | ||
| 21 | + Ok(()) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +pub async fn daily(days: u32, db: &Connection) -> Result<Vec<DayStat>, ServerError> { | ||
| 25 | + let days = u64::from(days.clamp(1, MAXIMUM_DAYS)); | ||
| 26 | + let today = now_ms() / DAY_MILLIS; | ||
| 27 | + let first = today + 1 - days; | ||
| 28 | + let active: HashMap<u64, u64> = all( | ||
| 29 | + db, | ||
| 30 | + "SELECT day, COUNT(*) FROM daily_active WHERE day >= ?1 GROUP BY day", | ||
| 31 | + (first,), | ||
| 32 | + |r| Ok((r.get()?, r.get()?)), | ||
| 33 | + ) | ||
| 34 | + .await? | ||
| 35 | + .into_iter() | ||
| 36 | + .collect(); | ||
| 37 | + let messages: HashMap<u64, u64> = all( | ||
| 38 | + db, | ||
| 39 | + "SELECT created_at / ?2 AS day, COUNT(*) FROM message WHERE created_at >= ?1 * ?2 GROUP BY day", | ||
| 40 | + (first, DAY_MILLIS), | ||
| 41 | + |r| Ok((r.get()?, r.get()?)), | ||
| 42 | + ) | ||
| 43 | + .await? | ||
| 44 | + .into_iter() | ||
| 45 | + .collect(); | ||
| 46 | + | ||
| 47 | + Ok((first..=today) | ||
| 48 | + .map(|day| DayStat { | ||
| 49 | + day, | ||
| 50 | + active_users: active.get(&day).copied().unwrap_or_default(), | ||
| 51 | + messages: messages.get(&day).copied().unwrap_or_default(), | ||
| 52 | + }) | ||
| 53 | + .collect()) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +pub async fn counts(db: &Connection) -> Result<(u64, u64, u64, u64), ServerError> { | ||
| 57 | + one( | ||
| 58 | + db, | ||
| 59 | + "SELECT | ||
| 60 | + (SELECT COUNT(*) FROM user), | ||
| 61 | + (SELECT COUNT(*) FROM user WHERE role = ?1), | ||
| 62 | + (SELECT COUNT(*) FROM community WHERE kind = ?2), | ||
| 63 | + (SELECT COALESCE(SUM(size), 0) FROM attachment) | ||
| 64 | + + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar)", | ||
| 65 | + (Role::Builder.as_str(), Kind::Group.as_str()), | ||
| 66 | + |r| Ok((r.get()?, r.get()?, r.get()?, r.get()?)), | ||
| 67 | + ) | ||
| 68 | + .await | ||
| 69 | +} | ||
crates/server/src/db/user.rsadded+314 -0
| @@ -0,0 +1,314 @@ | |||
| 1 | +use common::{ | ||
| 2 | + error::Error, | ||
| 3 | + model::{Account, Id, Presence, Role, User}, | ||
| 4 | + permission, | ||
| 5 | + time::now_ms, | ||
| 6 | +}; | ||
| 7 | + | ||
| 8 | +use super::{Connection, Reader, all, maybe, one, run}; | ||
| 9 | +use crate::error::{ServerError, ensure_with}; | ||
| 10 | + | ||
| 11 | +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"; | ||
| 12 | + | ||
| 13 | +pub fn row(r: &mut Reader) -> Result<User, ServerError> { | ||
| 14 | + Ok(User { | ||
| 15 | + id: r.get()?, | ||
| 16 | + username: r.get()?, | ||
| 17 | + role: r.named()?, | ||
| 18 | + status: r.get()?, | ||
| 19 | + avatar_id: r.get()?, | ||
| 20 | + created_at: r.get()?, | ||
| 21 | + }) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +pub async fn read(id: Id, db: &Connection) -> Result<User, ServerError> { | ||
| 25 | + one( | ||
| 26 | + db, | ||
| 27 | + &format!("SELECT {COLUMNS} FROM user WHERE user.id = ?1"), | ||
| 28 | + (id,), | ||
| 29 | + row, | ||
| 30 | + ) | ||
| 31 | + .await | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +pub async fn create( | ||
| 35 | + username: &str, | ||
| 36 | + password_hash: &str, | ||
| 37 | + role: Role, | ||
| 38 | + db: &Connection, | ||
| 39 | +) -> Result<User, ServerError> { | ||
| 40 | + let id: Id = one( | ||
| 41 | + db, | ||
| 42 | + "INSERT INTO user (username, password_hash, role, presence, created_at) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", | ||
| 43 | + ( | ||
| 44 | + username, | ||
| 45 | + password_hash, | ||
| 46 | + role.as_str(), | ||
| 47 | + Presence::Online.as_str(), | ||
| 48 | + now_ms(), | ||
| 49 | + ), | ||
| 50 | + |r| r.get(), | ||
| 51 | + ) | ||
| 52 | + .await?; | ||
| 53 | + | ||
| 54 | + read(id, db).await | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +pub async fn any(db: &Connection) -> Result<bool, ServerError> { | ||
| 58 | + one(db, "SELECT EXISTS (SELECT 1 FROM user)", (), |r| r.get()).await | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +pub async fn by_username(username: &str, db: &Connection) -> Result<Option<User>, ServerError> { | ||
| 62 | + maybe( | ||
| 63 | + db, | ||
| 64 | + &format!("SELECT {COLUMNS} FROM user WHERE user.username = ?1"), | ||
| 65 | + (username,), | ||
| 66 | + row, | ||
| 67 | + ) | ||
| 68 | + .await | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +pub async fn password_hash_of( | ||
| 72 | + username: &str, | ||
| 73 | + db: &Connection, | ||
| 74 | +) -> Result<Option<(User, String)>, ServerError> { | ||
| 75 | + maybe( | ||
| 76 | + db, | ||
| 77 | + &format!("SELECT {COLUMNS}, user.password_hash FROM user WHERE user.username = ?1"), | ||
| 78 | + (username,), | ||
| 79 | + |r| Ok((row(r)?, r.get()?)), | ||
| 80 | + ) | ||
| 81 | + .await | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +pub async fn update(id: Id, username: &str, db: &Connection) -> Result<User, ServerError> { | ||
| 85 | + run( | ||
| 86 | + db, | ||
| 87 | + "UPDATE user SET username = ?2 WHERE id = ?1", | ||
| 88 | + (id, username), | ||
| 89 | + ) | ||
| 90 | + .await?; | ||
| 91 | + | ||
| 92 | + read(id, db).await | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +pub async fn update_status(id: Id, status: &str, db: &Connection) -> Result<User, ServerError> { | ||
| 96 | + run( | ||
| 97 | + db, | ||
| 98 | + "UPDATE user SET status = ?2 WHERE id = ?1", | ||
| 99 | + (id, status), | ||
| 100 | + ) | ||
| 101 | + .await?; | ||
| 102 | + | ||
| 103 | + read(id, db).await | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +pub async fn set_role_by_id(id: Id, role: Role, db: &Connection) -> Result<User, ServerError> { | ||
| 107 | + run( | ||
| 108 | + db, | ||
| 109 | + "UPDATE user SET role = ?2 WHERE id = ?1", | ||
| 110 | + (id, role.as_str()), | ||
| 111 | + ) | ||
| 112 | + .await?; | ||
| 113 | + | ||
| 114 | + read(id, db).await | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +pub async fn suspended(id: Id, db: &Connection) -> Result<Option<Option<u64>>, ServerError> { | ||
| 118 | + let (suspended, until): (bool, Option<u64>) = one( | ||
| 119 | + db, | ||
| 120 | + "SELECT suspended, suspended_until FROM user WHERE id = ?1", | ||
| 121 | + (id,), | ||
| 122 | + |r| Ok((r.get()?, r.get()?)), | ||
| 123 | + ) | ||
| 124 | + .await?; | ||
| 125 | + | ||
| 126 | + if suspended { | ||
| 127 | + return Ok(Some(None)); | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + Ok(until.filter(|until| *until > now_ms()).map(Some)) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +pub async fn set_timeout(id: Id, until: Option<u64>, db: &Connection) -> Result<(), ServerError> { | ||
| 134 | + run( | ||
| 135 | + db, | ||
| 136 | + "UPDATE user SET suspended_until = ?2 WHERE id = ?1", | ||
| 137 | + (id, until.map(|ms| ms as i64)), | ||
| 138 | + ) | ||
| 139 | + .await?; | ||
| 140 | + | ||
| 141 | + Ok(()) | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +pub async fn set_last_ip(id: Id, ip: &str, db: &Connection) -> Result<(), ServerError> { | ||
| 145 | + run(db, "UPDATE user SET last_ip = ?2 WHERE id = ?1", (id, ip)).await?; | ||
| 146 | + | ||
| 147 | + Ok(()) | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +pub async fn last_ip(id: Id, db: &Connection) -> Result<Option<String>, ServerError> { | ||
| 151 | + one(db, "SELECT last_ip FROM user WHERE id = ?1", (id,), |r| { | ||
| 152 | + r.get() | ||
| 153 | + }) | ||
| 154 | + .await | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +pub async fn builder_ids(db: &Connection) -> Result<Vec<Id>, ServerError> { | ||
| 158 | + all( | ||
| 159 | + db, | ||
| 160 | + "SELECT id FROM user WHERE role = ?1", | ||
| 161 | + (Role::Builder.as_str(),), | ||
| 162 | + |r| r.get(), | ||
| 163 | + ) | ||
| 164 | + .await | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +pub async fn set_suspended(id: Id, suspended: bool, db: &Connection) -> Result<(), ServerError> { | ||
| 168 | + run( | ||
| 169 | + db, | ||
| 170 | + "UPDATE user SET suspended = ?2 WHERE id = ?1", | ||
| 171 | + (id, suspended), | ||
| 172 | + ) | ||
| 173 | + .await?; | ||
| 174 | + | ||
| 175 | + Ok(()) | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +pub async fn set_voice_muted(id: Id, muted: bool, db: &Connection) -> Result<(), ServerError> { | ||
| 179 | + run( | ||
| 180 | + db, | ||
| 181 | + "UPDATE user SET voice_muted = ?2 WHERE id = ?1", | ||
| 182 | + (id, muted), | ||
| 183 | + ) | ||
| 184 | + .await?; | ||
| 185 | + | ||
| 186 | + Ok(()) | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +pub async fn set_ghost(id: Id, ghost: bool, db: &Connection) -> Result<(), ServerError> { | ||
| 190 | + run(db, "UPDATE user SET ghost = ?2 WHERE id = ?1", (id, ghost)).await?; | ||
| 191 | + | ||
| 192 | + Ok(()) | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +pub async fn is_ghost(id: Id, db: &Connection) -> Result<bool, ServerError> { | ||
| 196 | + Ok( | ||
| 197 | + maybe(db, "SELECT ghost FROM user WHERE id = ?1", (id,), |r| { | ||
| 198 | + r.get() | ||
| 199 | + }) | ||
| 200 | + .await? | ||
| 201 | + .unwrap_or(false), | ||
| 202 | + ) | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +pub async fn presence(id: Id, db: &Connection) -> Result<Presence, ServerError> { | ||
| 206 | + one(db, "SELECT presence FROM user WHERE id = ?1", (id,), |r| { | ||
| 207 | + r.named() | ||
| 208 | + }) | ||
| 209 | + .await | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +pub async fn update_presence( | ||
| 213 | + id: Id, | ||
| 214 | + presence: Presence, | ||
| 215 | + db: &Connection, | ||
| 216 | +) -> Result<(), ServerError> { | ||
| 217 | + run( | ||
| 218 | + db, | ||
| 219 | + "UPDATE user SET presence = ?2 WHERE id = ?1", | ||
| 220 | + (id, presence.as_str()), | ||
| 221 | + ) | ||
| 222 | + .await?; | ||
| 223 | + | ||
| 224 | + Ok(()) | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +pub async fn voice_muted(id: Id, db: &Connection) -> Result<bool, ServerError> { | ||
| 228 | + let (muted, role): (bool, Role) = one( | ||
| 229 | + db, | ||
| 230 | + "SELECT voice_muted, role FROM user WHERE id = ?1", | ||
| 231 | + (id,), | ||
| 232 | + |r| Ok((r.get()?, r.named()?)), | ||
| 233 | + ) | ||
| 234 | + .await?; | ||
| 235 | + | ||
| 236 | + Ok(muted && !permission::is_builder(role)) | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +pub async fn set_password_hash( | ||
| 240 | + id: Id, | ||
| 241 | + password_hash: &str, | ||
| 242 | + db: &Connection, | ||
| 243 | +) -> Result<(), ServerError> { | ||
| 244 | + run( | ||
| 245 | + db, | ||
| 246 | + "UPDATE user SET password_hash = ?2 WHERE id = ?1", | ||
| 247 | + (id, password_hash), | ||
| 248 | + ) | ||
| 249 | + .await?; | ||
| 250 | + | ||
| 251 | + Ok(()) | ||
| 252 | +} | ||
| 253 | + | ||
| 254 | +pub async fn all_accounts(db: &Connection) -> Result<Vec<Account>, ServerError> { | ||
| 255 | + all( | ||
| 256 | + db, | ||
| 257 | + &format!("SELECT {COLUMNS}, user.suspended, user.last_seen, user.suspended_until, user.ghost FROM user ORDER BY user.username"), | ||
| 258 | + (), | ||
| 259 | + |r| { | ||
| 260 | + Ok(Account { | ||
| 261 | + user: row(r)?, | ||
| 262 | + suspended: r.get()?, | ||
| 263 | + last_seen: r.get()?, | ||
| 264 | + suspended_until: r.get()?, | ||
| 265 | + ghost: r.get()?, | ||
| 266 | + }) | ||
| 267 | + }, | ||
| 268 | + ) | ||
| 269 | + .await | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { | ||
| 273 | + ensure_with( | ||
| 274 | + run(db, "DELETE FROM user WHERE id = ?1", (id,)).await? == 1, | ||
| 275 | + Error::NotFound, | ||
| 276 | + ) | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +#[cfg(test)] | ||
| 280 | +mod tests { | ||
| 281 | + use common::{error::Error, model::Role}; | ||
| 282 | + | ||
| 283 | + use crate::{db::user, error::ServerError, test}; | ||
| 284 | + | ||
| 285 | + #[tokio::test] | ||
| 286 | + async fn read_by_username() { | ||
| 287 | + let db = test::db().await; | ||
| 288 | + let conn = db.lock().await.unwrap(); | ||
| 289 | + | ||
| 290 | + let created_user = user::create("Tahinli", "hash", Role::User, &conn) | ||
| 291 | + .await | ||
| 292 | + .unwrap(); | ||
| 293 | + let _other_user = user::create("Not Tahinli", "hash", Role::User, &conn) | ||
| 294 | + .await | ||
| 295 | + .unwrap(); | ||
| 296 | + | ||
| 297 | + let searched_user = user::by_username("tahinli", &conn).await.unwrap(); | ||
| 298 | + | ||
| 299 | + assert_eq!(Some(created_user), searched_user); | ||
| 300 | + } | ||
| 301 | + | ||
| 302 | + #[tokio::test] | ||
| 303 | + async fn update_on_missing_user() { | ||
| 304 | + let db = test::db().await; | ||
| 305 | + let conn = db.lock().await.unwrap(); | ||
| 306 | + | ||
| 307 | + let updated_user = user::update(404, "Not Tahinli", &conn).await; | ||
| 308 | + | ||
| 309 | + assert!(matches!( | ||
| 310 | + updated_user, | ||
| 311 | + Err(ServerError::Wire(Error::NotFound)) | ||
| 312 | + )); | ||
| 313 | + } | ||
| 314 | +} | ||
crates/server/src/direct.rsdeleted+0 -51
| @@ -1,51 +0,0 @@ | |||
| 1 | -use common::model::{Community, Rank}; | ||
| 2 | -use turso::Connection; | ||
| 3 | - | ||
| 4 | -use crate::{community, error::ServerError, request::ensure, user, user_community}; | ||
| 5 | - | ||
| 6 | -async fn find( | ||
| 7 | - user_a: &str, | ||
| 8 | - user_b: &str, | ||
| 9 | - conn: &Connection, | ||
| 10 | -) -> Result<Option<String>, ServerError> { | ||
| 11 | - let mut rows = conn | ||
| 12 | - .query( | ||
| 13 | - "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", | ||
| 14 | - (user_a, user_b), | ||
| 15 | - ) | ||
| 16 | - .await?; | ||
| 17 | - | ||
| 18 | - Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) | ||
| 19 | -} | ||
| 20 | - | ||
| 21 | -pub enum Opening { | ||
| 22 | - Created(Community), | ||
| 23 | - Existing(Community), | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result<Opening, ServerError> { | ||
| 27 | - ensure(me != other)?; | ||
| 28 | - user::read(other, conn).await?; | ||
| 29 | - | ||
| 30 | - let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; | ||
| 31 | - let tx = conn.transaction().await?; | ||
| 32 | - if let Some(community_id) = find(user_a, user_b, &tx).await? { | ||
| 33 | - let community = community::read(&community_id, me, &tx).await?; | ||
| 34 | - tx.commit().await?; | ||
| 35 | - | ||
| 36 | - return Ok(Opening::Existing(community)); | ||
| 37 | - } | ||
| 38 | - | ||
| 39 | - let community_id = community::create_fixed(community::Kind::Direct, &tx).await?; | ||
| 40 | - user_community::join(me, &community_id, Rank::Member, &tx).await?; | ||
| 41 | - user_community::join(other, &community_id, Rank::Member, &tx).await?; | ||
| 42 | - tx.execute( | ||
| 43 | - "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)", | ||
| 44 | - (user_a, user_b, community_id.as_str()), | ||
| 45 | - ) | ||
| 46 | - .await?; | ||
| 47 | - let community = community::read(&community_id, me, &tx).await?; | ||
| 48 | - tx.commit().await?; | ||
| 49 | - | ||
| 50 | - Ok(Opening::Created(community)) | ||
| 51 | -} | ||
crates/server/src/error.rsmodified+31 -1
| @@ -21,6 +21,36 @@ impl From<ServerError> for common::error::Error { | |||
| 21 | } | 21 | } |
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | +impl From<turso::Error> for ServerError { | ||
| 25 | + fn from(error: turso::Error) -> Self { | ||
| 26 | + match &error { | ||
| 27 | + turso::Error::Constraint(message) | ||
| 28 | + if message.starts_with("UNIQUE constraint failed") => | ||
| 29 | + { | ||
| 30 | + common::error::Error::Taken.into() | ||
| 31 | + } | ||
| 32 | + turso::Error::Constraint(message) | ||
| 33 | + if message.starts_with("FOREIGN KEY constraint failed") => | ||
| 34 | + { | ||
| 35 | + common::error::Error::NotFound.into() | ||
| 36 | + } | ||
| 37 | + _ => ServerError::Internal(error.to_string()), | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +pub fn ensure(condition: bool) -> Result<(), ServerError> { | ||
| 43 | + ensure_with(condition, common::error::Error::Forbidden) | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +pub fn ensure_with(condition: bool, error: common::error::Error) -> Result<(), ServerError> { | ||
| 47 | + if !condition { | ||
| 48 | + return Err(error.into()); | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + Ok(()) | ||
| 52 | +} | ||
| 53 | + | ||
| 24 | macro_rules! internal_from { | 54 | macro_rules! internal_from { |
| 25 | ($($source:ty),+ $(,)?) => { | 55 | ($($source:ty),+ $(,)?) => { |
| 26 | $( | 56 | $( |
| @@ -36,7 +66,7 @@ macro_rules! internal_from { | |||
| 36 | internal_from! { | 66 | internal_from! { |
| 37 | std::net::AddrParseError, | 67 | std::net::AddrParseError, |
| 38 | std::io::Error, | 68 | std::io::Error, |
| 39 | - turso::Error, | 69 | + tokio::task::JoinError, |
| 40 | quinn::ConnectionError, | 70 | quinn::ConnectionError, |
| 41 | quinn::ReadError, | 71 | quinn::ReadError, |
| 42 | quinn::ReadExactError, | 72 | quinn::ReadExactError, |
crates/server/src/files.rsadded+497 -0
| @@ -0,0 +1,497 @@ | |||
| 1 | +use std::{ | ||
| 2 | + io::{BufReader, Cursor}, | ||
| 3 | + path::{Path, PathBuf}, | ||
| 4 | + time::{Duration, SystemTime}, | ||
| 5 | +}; | ||
| 6 | + | ||
| 7 | +use common::{ | ||
| 8 | + constant::{ | ||
| 9 | + ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, AVATAR_SIZE, MAXIMUM_AVATAR_BYTES, | ||
| 10 | + THUMBNAIL_SIZE, | ||
| 11 | + }, | ||
| 12 | + error::{Error as CommonError, Field, Problem}, | ||
| 13 | + frame::{self, DOWN_MAX, Sending}, | ||
| 14 | + model::{Attachment, AttachmentKind, Id, ServerSettings, User}, | ||
| 15 | + open::{Blob, Upload}, | ||
| 16 | + permission, | ||
| 17 | + time::{HOUR_MILLIS, now_ms}, | ||
| 18 | + validate::{validate_attachment_name, validate_attachment_size, validate_avatar_size}, | ||
| 19 | +}; | ||
| 20 | +use image::{ImageFormat, ImageReader, Limits}; | ||
| 21 | +use quinn::{RecvStream, VarInt}; | ||
| 22 | +use tokio::{ | ||
| 23 | + fs::File, | ||
| 24 | + io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, | ||
| 25 | +}; | ||
| 26 | +use tracing::error; | ||
| 27 | + | ||
| 28 | +use crate::{ | ||
| 29 | + authentication::random_bytes, | ||
| 30 | + backup, | ||
| 31 | + db::{self, Db}, | ||
| 32 | + error::{ServerError, ensure, ensure_with}, | ||
| 33 | +}; | ||
| 34 | + | ||
| 35 | +const COLLECT_INTERVAL: Duration = Duration::from_secs(600); | ||
| 36 | +const MAXIMUM_IMAGE_SIDE: u32 = 16384; | ||
| 37 | +const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; | ||
| 38 | +const THUMB_SUFFIX: &str = ".thumb"; | ||
| 39 | +const FILE_NAME_BYTES: usize = 16; | ||
| 40 | + | ||
| 41 | +fn thumb_path(directory: &Path, file: &str) -> PathBuf { | ||
| 42 | + directory.join(format!("{file}{THUMB_SUFFIX}")) | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +fn remove_files(directory: &Path, file: &str) { | ||
| 46 | + let _ = std::fs::remove_file(directory.join(file)); | ||
| 47 | + let _ = std::fs::remove_file(thumb_path(directory, file)); | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +fn media_kind(head: &[u8]) -> AttachmentKind { | ||
| 51 | + if is_video(head) { | ||
| 52 | + AttachmentKind::Video | ||
| 53 | + } else if is_audio(head) { | ||
| 54 | + AttachmentKind::Audio | ||
| 55 | + } else { | ||
| 56 | + AttachmentKind::File | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +fn is_image(head: &[u8]) -> bool { | ||
| 61 | + matches!( | ||
| 62 | + image::guess_format(head), | ||
| 63 | + Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) | ||
| 64 | + ) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +fn is_video(head: &[u8]) -> bool { | ||
| 68 | + head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +fn is_audio(head: &[u8]) -> bool { | ||
| 72 | + head.starts_with(b"OggS") | ||
| 73 | + || head.starts_with(b"fLaC") | ||
| 74 | + || head.starts_with(b"ID3") | ||
| 75 | + || head.starts_with(&[0xFF, 0xFB]) | ||
| 76 | + || head.starts_with(&[0xFF, 0xF3]) | ||
| 77 | + || head.starts_with(&[0xFF, 0xF2]) | ||
| 78 | + || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE")) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> { | ||
| 82 | + let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?)) | ||
| 83 | + .with_guessed_format() | ||
| 84 | + .ok()?; | ||
| 85 | + let mut limits = Limits::default(); | ||
| 86 | + limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE); | ||
| 87 | + limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE); | ||
| 88 | + limits.max_alloc = Some(MAXIMUM_DECODE_BYTES); | ||
| 89 | + reader.limits(limits); | ||
| 90 | + let image = reader.decode().ok()?; | ||
| 91 | + let (width, height) = (image.width(), image.height()); | ||
| 92 | + | ||
| 93 | + let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE { | ||
| 94 | + image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE) | ||
| 95 | + } else { | ||
| 96 | + image | ||
| 97 | + }; | ||
| 98 | + let mut bytes = Cursor::new(Vec::new()); | ||
| 99 | + fitted | ||
| 100 | + .to_rgb8() | ||
| 101 | + .write_to(&mut bytes, ImageFormat::Jpeg) | ||
| 102 | + .ok()?; | ||
| 103 | + std::fs::write(thumbnail, bytes.into_inner()).ok()?; | ||
| 104 | + | ||
| 105 | + Some((width, height)) | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> { | ||
| 109 | + validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; | ||
| 110 | + let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { | ||
| 111 | + CommonError::Invalid { | ||
| 112 | + field: Field::Avatar, | ||
| 113 | + problem: Problem::NotJpeg, | ||
| 114 | + } | ||
| 115 | + })?; | ||
| 116 | + if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { | ||
| 117 | + return Err(CommonError::Invalid { | ||
| 118 | + field: Field::Avatar, | ||
| 119 | + problem: Problem::Dimensions { | ||
| 120 | + expected: AVATAR_SIZE, | ||
| 121 | + }, | ||
| 122 | + } | ||
| 123 | + .into()); | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + Ok(()) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +async fn receive_body<R: AsyncRead + Unpin>( | ||
| 130 | + reader: &mut R, | ||
| 131 | + path: &Path, | ||
| 132 | + size: u64, | ||
| 133 | +) -> Result<Vec<u8>, ServerError> { | ||
| 134 | + let mismatch = |actual: u64| CommonError::Invalid { | ||
| 135 | + field: Field::Attachment, | ||
| 136 | + problem: Problem::Length { | ||
| 137 | + min: size, | ||
| 138 | + max: size, | ||
| 139 | + actual, | ||
| 140 | + }, | ||
| 141 | + }; | ||
| 142 | + let mut file = File::create(path).await?; | ||
| 143 | + | ||
| 144 | + let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize]; | ||
| 145 | + reader.read_exact(&mut head).await?; | ||
| 146 | + file.write_all(&head).await?; | ||
| 147 | + | ||
| 148 | + let mut received = head.len() as u64; | ||
| 149 | + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; | ||
| 150 | + loop { | ||
| 151 | + let read = reader.read(&mut buffer).await?; | ||
| 152 | + if read == 0 { | ||
| 153 | + break; | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + received += read as u64; | ||
| 157 | + if received > size { | ||
| 158 | + return Err(mismatch(received).into()); | ||
| 159 | + } | ||
| 160 | + file.write_all(&buffer[..read]).await?; | ||
| 161 | + } | ||
| 162 | + | ||
| 163 | + if received != size { | ||
| 164 | + return Err(mismatch(received).into()); | ||
| 165 | + } | ||
| 166 | + file.flush().await?; | ||
| 167 | + | ||
| 168 | + Ok(head) | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +async fn ensure_quota( | ||
| 172 | + user_id: Id, | ||
| 173 | + community_id: Id, | ||
| 174 | + size: u64, | ||
| 175 | + settings: &ServerSettings, | ||
| 176 | + db: &db::Connection, | ||
| 177 | +) -> Result<(), ServerError> { | ||
| 178 | + let (user_used, community_used) = db::attachment::quota(user_id, community_id, db).await?; | ||
| 179 | + let over = |used: u64, limit: u64| limit != 0 && used.saturating_add(size) > limit; | ||
| 180 | + ensure_with( | ||
| 181 | + !over(user_used, settings.user_quota_bytes) | ||
| 182 | + && !over(community_used, settings.community_quota_bytes), | ||
| 183 | + CommonError::QuotaExceeded, | ||
| 184 | + ) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +async fn write_file( | ||
| 188 | + reader: &mut (impl AsyncRead + Unpin), | ||
| 189 | + header: &Upload, | ||
| 190 | + path: &Path, | ||
| 191 | + thumbnail: PathBuf, | ||
| 192 | +) -> Result<(AttachmentKind, Option<u32>, Option<u32>), ServerError> { | ||
| 193 | + let head = receive_body(reader, path, header.size).await?; | ||
| 194 | + let described = if is_image(&head) { | ||
| 195 | + let source = path.to_path_buf(); | ||
| 196 | + tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)).await? | ||
| 197 | + } else { | ||
| 198 | + None | ||
| 199 | + }; | ||
| 200 | + | ||
| 201 | + Ok(match described { | ||
| 202 | + Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)), | ||
| 203 | + None => (media_kind(&head), None, None), | ||
| 204 | + }) | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +pub async fn store<R: AsyncRead + Unpin>( | ||
| 208 | + user: &User, | ||
| 209 | + header: &Upload, | ||
| 210 | + reader: &mut R, | ||
| 211 | + db: &Db, | ||
| 212 | + directory: &Path, | ||
| 213 | +) -> Result<Attachment, ServerError> { | ||
| 214 | + let settings = db | ||
| 215 | + .run(async |conn| { | ||
| 216 | + let rank = permission::effective_rank( | ||
| 217 | + user.role, | ||
| 218 | + db::member::rank(user.id, header.community_id, conn).await?, | ||
| 219 | + ); | ||
| 220 | + ensure(permission::can_post(rank))?; | ||
| 221 | + validate_attachment_name(&header.name)?; | ||
| 222 | + let settings = db::settings::read(conn).await?; | ||
| 223 | + validate_attachment_size(header.size, settings.max_attachment_bytes)?; | ||
| 224 | + ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?; | ||
| 225 | + | ||
| 226 | + Ok(settings) | ||
| 227 | + }) | ||
| 228 | + .await?; | ||
| 229 | + | ||
| 230 | + let file: String = random_bytes::<FILE_NAME_BYTES>()? | ||
| 231 | + .iter() | ||
| 232 | + .map(|byte| format!("{byte:02x}")) | ||
| 233 | + .collect(); | ||
| 234 | + let path = directory.join(&file); | ||
| 235 | + let (kind, width, height) = | ||
| 236 | + match write_file(reader, header, &path, thumb_path(directory, &file)).await { | ||
| 237 | + Ok(described) => described, | ||
| 238 | + Err(error) => { | ||
| 239 | + remove_files(directory, &file); | ||
| 240 | + return Err(error); | ||
| 241 | + } | ||
| 242 | + }; | ||
| 243 | + | ||
| 244 | + let stored = db | ||
| 245 | + .run(async |conn| { | ||
| 246 | + ensure_quota(user.id, header.community_id, header.size, &settings, conn).await?; | ||
| 247 | + db::attachment::insert( | ||
| 248 | + user.id, | ||
| 249 | + header.community_id, | ||
| 250 | + &file, | ||
| 251 | + &header.name, | ||
| 252 | + header.size, | ||
| 253 | + kind, | ||
| 254 | + width, | ||
| 255 | + height, | ||
| 256 | + conn, | ||
| 257 | + ) | ||
| 258 | + .await | ||
| 259 | + }) | ||
| 260 | + .await; | ||
| 261 | + if stored.is_err() { | ||
| 262 | + remove_files(directory, &file); | ||
| 263 | + } | ||
| 264 | + | ||
| 265 | + stored | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +pub async fn upload( | ||
| 269 | + user: Option<&User>, | ||
| 270 | + header: Upload, | ||
| 271 | + mut receive_stream: RecvStream, | ||
| 272 | + mut send_stream: Sending, | ||
| 273 | + db: &Db, | ||
| 274 | + directory: &Path, | ||
| 275 | +) -> Result<(), ServerError> { | ||
| 276 | + let stored = match user { | ||
| 277 | + Some(user) => store(user, &header, &mut receive_stream, db, directory).await, | ||
| 278 | + None => Err(CommonError::Unauthenticated.into()), | ||
| 279 | + }; | ||
| 280 | + let rejected = stored.is_err(); | ||
| 281 | + let reply = stored.map_err(CommonError::from); | ||
| 282 | + | ||
| 283 | + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; | ||
| 284 | + send_stream.finish()?; | ||
| 285 | + if rejected { | ||
| 286 | + let _ = receive_stream.stop(VarInt::from_u32(0)); | ||
| 287 | + } | ||
| 288 | + | ||
| 289 | + Ok(()) | ||
| 290 | +} | ||
| 291 | + | ||
| 292 | +async fn locate( | ||
| 293 | + user: Option<&User>, | ||
| 294 | + attachment_id: Id, | ||
| 295 | + thumbnail: bool, | ||
| 296 | + db: &Db, | ||
| 297 | + directory: &Path, | ||
| 298 | +) -> Result<(PathBuf, u64), ServerError> { | ||
| 299 | + let user = user.ok_or(CommonError::Unauthenticated)?; | ||
| 300 | + let stored = db | ||
| 301 | + .run(async |conn| { | ||
| 302 | + let stored = db::attachment::read(attachment_id, conn).await?; | ||
| 303 | + let rank = permission::effective_rank( | ||
| 304 | + user.role, | ||
| 305 | + db::member::rank(user.id, stored.community_id, conn).await?, | ||
| 306 | + ); | ||
| 307 | + ensure(permission::can_read(rank))?; | ||
| 308 | + ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; | ||
| 309 | + | ||
| 310 | + Ok(stored) | ||
| 311 | + }) | ||
| 312 | + .await?; | ||
| 313 | + | ||
| 314 | + let path = if thumbnail { | ||
| 315 | + thumb_path(directory, &stored.file) | ||
| 316 | + } else { | ||
| 317 | + directory.join(&stored.file) | ||
| 318 | + }; | ||
| 319 | + let length = tokio::fs::metadata(&path) | ||
| 320 | + .await | ||
| 321 | + .map_err(|_| CommonError::NotFound)? | ||
| 322 | + .len(); | ||
| 323 | + | ||
| 324 | + Ok((path, length)) | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +pub async fn fetch( | ||
| 328 | + user: Option<&User>, | ||
| 329 | + blob: Blob, | ||
| 330 | + mut send_stream: Sending, | ||
| 331 | + db: &Db, | ||
| 332 | + directory: &Path, | ||
| 333 | + backups: &Path, | ||
| 334 | +) -> Result<(), ServerError> { | ||
| 335 | + let located = match &blob { | ||
| 336 | + Blob::Attachment(id) => locate(user, *id, false, db, directory).await, | ||
| 337 | + Blob::Thumbnail(id) => locate(user, *id, true, db, directory).await, | ||
| 338 | + Blob::Backup(name) => backup::locate(user, name, db, backups).await, | ||
| 339 | + }; | ||
| 340 | + let located = located.map_err(CommonError::from); | ||
| 341 | + let reply = located | ||
| 342 | + .as_ref() | ||
| 343 | + .map(|(_, length)| *length) | ||
| 344 | + .map_err(Clone::clone); | ||
| 345 | + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; | ||
| 346 | + | ||
| 347 | + if let Ok((path, _)) = located { | ||
| 348 | + let mut file = File::open(path).await?; | ||
| 349 | + let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; | ||
| 350 | + loop { | ||
| 351 | + let read = file.read(&mut buffer).await?; | ||
| 352 | + if read == 0 { | ||
| 353 | + break; | ||
| 354 | + } | ||
| 355 | + send_stream.get().write_all(&buffer[..read]).await?; | ||
| 356 | + } | ||
| 357 | + } | ||
| 358 | + send_stream.finish()?; | ||
| 359 | + | ||
| 360 | + Ok(()) | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +pub async fn collect(db: Db, directory: PathBuf) { | ||
| 364 | + let mut interval = tokio::time::interval(COLLECT_INTERVAL); | ||
| 365 | + loop { | ||
| 366 | + interval.tick().await; | ||
| 367 | + if let Err(error) = sweep(&db, &directory).await { | ||
| 368 | + error!("attachment sweep: {error}"); | ||
| 369 | + } | ||
| 370 | + } | ||
| 371 | +} | ||
| 372 | + | ||
| 373 | +async fn sweep(db: &Db, directory: &Path) -> Result<(), ServerError> { | ||
| 374 | + let stale_ms = now_ms().saturating_sub(HOUR_MILLIS); | ||
| 375 | + let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); | ||
| 376 | + | ||
| 377 | + let files = db | ||
| 378 | + .run(async |conn| { | ||
| 379 | + db::attachment::delete_stale_unbound(stale_ms, conn).await?; | ||
| 380 | + db::attachment::files(conn).await | ||
| 381 | + }) | ||
| 382 | + .await?; | ||
| 383 | + | ||
| 384 | + for entry in std::fs::read_dir(directory)? { | ||
| 385 | + let Ok(entry) = entry else { continue }; | ||
| 386 | + let name = entry.file_name().to_string_lossy().into_owned(); | ||
| 387 | + let file = name.strip_suffix(THUMB_SUFFIX).unwrap_or(&name); | ||
| 388 | + let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { | ||
| 389 | + continue; | ||
| 390 | + }; | ||
| 391 | + | ||
| 392 | + if modified < stale_at && !files.contains(file) { | ||
| 393 | + let _ = std::fs::remove_file(entry.path()); | ||
| 394 | + } | ||
| 395 | + } | ||
| 396 | + | ||
| 397 | + Ok(()) | ||
| 398 | +} | ||
| 399 | + | ||
| 400 | +#[cfg(test)] | ||
| 401 | +mod tests { | ||
| 402 | + use std::io::Cursor; | ||
| 403 | + | ||
| 404 | + use common::{ | ||
| 405 | + constant::AVATAR_SIZE, | ||
| 406 | + error::{Error as CommonError, Field}, | ||
| 407 | + model::{AttachmentKind, Rank, Role}, | ||
| 408 | + open::Upload, | ||
| 409 | + }; | ||
| 410 | + use image::{ImageFormat, RgbImage}; | ||
| 411 | + | ||
| 412 | + use super::{check_avatar, store, thumb_path}; | ||
| 413 | + use crate::{db, error::ServerError, test}; | ||
| 414 | + | ||
| 415 | + fn jpeg(size: u32) -> Vec<u8> { | ||
| 416 | + let mut bytes = Cursor::new(Vec::new()); | ||
| 417 | + RgbImage::new(size, size) | ||
| 418 | + .write_to(&mut bytes, ImageFormat::Jpeg) | ||
| 419 | + .unwrap(); | ||
| 420 | + | ||
| 421 | + bytes.into_inner() | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + #[test] | ||
| 425 | + fn avatar_checks_jpeg_size() { | ||
| 426 | + let small = check_avatar(&jpeg(AVATAR_SIZE / 2)); | ||
| 427 | + let not_jpeg = check_avatar(b"not a jpeg"); | ||
| 428 | + | ||
| 429 | + assert!(matches!( | ||
| 430 | + small, | ||
| 431 | + Err(ServerError::Wire(CommonError::Invalid { | ||
| 432 | + field: Field::Avatar, | ||
| 433 | + .. | ||
| 434 | + })) | ||
| 435 | + )); | ||
| 436 | + assert!(matches!( | ||
| 437 | + not_jpeg, | ||
| 438 | + Err(ServerError::Wire(CommonError::Invalid { | ||
| 439 | + field: Field::Avatar, | ||
| 440 | + .. | ||
| 441 | + })) | ||
| 442 | + )); | ||
| 443 | + assert!(check_avatar(&jpeg(AVATAR_SIZE)).is_ok()); | ||
| 444 | + } | ||
| 445 | + | ||
| 446 | + #[tokio::test] | ||
| 447 | + async fn upload_then_read_in_message() { | ||
| 448 | + let db = test::db().await; | ||
| 449 | + let (user, community) = { | ||
| 450 | + let conn = db.lock().await.unwrap(); | ||
| 451 | + let user = db::user::create("Tahinli", "hash", Role::User, &conn) | ||
| 452 | + .await | ||
| 453 | + .unwrap(); | ||
| 454 | + let community_id = db::community::create(db::community::Kind::Group, "Tahinli", &conn) | ||
| 455 | + .await | ||
| 456 | + .unwrap(); | ||
| 457 | + db::member::join(user.id, community_id, Rank::Member, &conn) | ||
| 458 | + .await | ||
| 459 | + .unwrap(); | ||
| 460 | + | ||
| 461 | + (user, community_id) | ||
| 462 | + }; | ||
| 463 | + | ||
| 464 | + let mut png = Cursor::new(Vec::new()); | ||
| 465 | + RgbImage::new(2, 3) | ||
| 466 | + .write_to(&mut png, ImageFormat::Png) | ||
| 467 | + .unwrap(); | ||
| 468 | + let png = png.into_inner(); | ||
| 469 | + let directory = test::directory(); | ||
| 470 | + let header = Upload { | ||
| 471 | + community_id: community, | ||
| 472 | + name: "pixel.png".to_string(), | ||
| 473 | + size: png.len() as u64, | ||
| 474 | + }; | ||
| 475 | + let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) | ||
| 476 | + .await | ||
| 477 | + .unwrap(); | ||
| 478 | + | ||
| 479 | + let conn = db.lock().await.unwrap(); | ||
| 480 | + db::message::create(user.id, community, "", &[attachment.id], None, &conn) | ||
| 481 | + .await | ||
| 482 | + .unwrap(); | ||
| 483 | + let messages = db::message::read_page(community, None, &conn) | ||
| 484 | + .await | ||
| 485 | + .unwrap(); | ||
| 486 | + assert_eq!(vec![attachment.clone()], messages[0].attachments); | ||
| 487 | + assert_eq!(AttachmentKind::Image, attachment.kind); | ||
| 488 | + assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); | ||
| 489 | + | ||
| 490 | + let file = db::attachment::read(attachment.id, &conn) | ||
| 491 | + .await | ||
| 492 | + .unwrap() | ||
| 493 | + .file; | ||
| 494 | + std::fs::remove_file(directory.join(&file)).unwrap(); | ||
| 495 | + std::fs::remove_file(thumb_path(&directory, &file)).unwrap(); | ||
| 496 | + } | ||
| 497 | +} | ||
crates/server/src/friend.rsdeleted+0 -141
| @@ -1,141 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - error::Error as CommonError, | ||
| 3 | - model::{Friends, User}, | ||
| 4 | -}; | ||
| 5 | -use turso::Connection; | ||
| 6 | - | ||
| 7 | -use crate::{database, error::ServerError, request::ensure_with, user}; | ||
| 8 | - | ||
| 9 | -async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result<Vec<User>, ServerError> { | ||
| 10 | - let mut rows = conn.query(sql, (user_id,)).await?; | ||
| 11 | - | ||
| 12 | - let mut users = Vec::new(); | ||
| 13 | - while let Some(row) = rows.next().await? { | ||
| 14 | - users.push(user::from_row(&row)?); | ||
| 15 | - } | ||
| 16 | - | ||
| 17 | - Ok(users) | ||
| 18 | -} | ||
| 19 | - | ||
| 20 | -async fn pair_exists( | ||
| 21 | - sql: &str, | ||
| 22 | - first: &str, | ||
| 23 | - second: &str, | ||
| 24 | - conn: &Connection, | ||
| 25 | -) -> Result<bool, ServerError> { | ||
| 26 | - database::exists(conn, sql, (first, second)).await | ||
| 27 | -} | ||
| 28 | - | ||
| 29 | -async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 30 | - pair_exists( | ||
| 31 | - "SELECT COUNT(*) FROM friend WHERE user_id = ?1 AND friend_id = ?2", | ||
| 32 | - me, | ||
| 33 | - other, | ||
| 34 | - conn, | ||
| 35 | - ) | ||
| 36 | - .await | ||
| 37 | -} | ||
| 38 | - | ||
| 39 | -async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 40 | - pair_exists( | ||
| 41 | - "SELECT COUNT(*) FROM friend_request WHERE from_id = ?1 AND to_id = ?2", | ||
| 42 | - from, | ||
| 43 | - to, | ||
| 44 | - conn, | ||
| 45 | - ) | ||
| 46 | - .await | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 50 | - conn.execute( | ||
| 51 | - "DELETE FROM friend_request WHERE from_id = ?1 AND to_id = ?2", | ||
| 52 | - (other, me), | ||
| 53 | - ) | ||
| 54 | - .await?; | ||
| 55 | - conn.execute( | ||
| 56 | - "INSERT INTO friend (user_id, friend_id) VALUES (?1, ?2)", | ||
| 57 | - (me, other), | ||
| 58 | - ) | ||
| 59 | - .await?; | ||
| 60 | - conn.execute( | ||
| 61 | - "INSERT INTO friend (user_id, friend_id) VALUES (?1, ?2)", | ||
| 62 | - (other, me), | ||
| 63 | - ) | ||
| 64 | - .await?; | ||
| 65 | - | ||
| 66 | - Ok(()) | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -pub async fn state(user_id: &str, conn: &Connection) -> Result<Friends, ServerError> { | ||
| 70 | - Ok(Friends { | ||
| 71 | - friends: users( | ||
| 72 | - &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")), | ||
| 73 | - user_id, | ||
| 74 | - conn, | ||
| 75 | - ) | ||
| 76 | - .await?, | ||
| 77 | - incoming: users( | ||
| 78 | - &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")), | ||
| 79 | - user_id, | ||
| 80 | - conn, | ||
| 81 | - ) | ||
| 82 | - .await?, | ||
| 83 | - outgoing: users( | ||
| 84 | - &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")), | ||
| 85 | - user_id, | ||
| 86 | - conn, | ||
| 87 | - ) | ||
| 88 | - .await?, | ||
| 89 | - }) | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { | ||
| 93 | - ensure_with(me != other, CommonError::Forbidden)?; | ||
| 94 | - user::read(other, conn).await?; | ||
| 95 | - | ||
| 96 | - let tx = conn.transaction().await?; | ||
| 97 | - ensure_with( | ||
| 98 | - !(is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await?), | ||
| 99 | - CommonError::Taken, | ||
| 100 | - )?; | ||
| 101 | - if is_requested(other, me, &tx).await? { | ||
| 102 | - befriend(me, other, &tx).await?; | ||
| 103 | - } else { | ||
| 104 | - tx.execute( | ||
| 105 | - "INSERT INTO friend_request (from_id, to_id) VALUES (?1, ?2)", | ||
| 106 | - (me, other), | ||
| 107 | - ) | ||
| 108 | - .await?; | ||
| 109 | - } | ||
| 110 | - tx.commit().await?; | ||
| 111 | - | ||
| 112 | - Ok(()) | ||
| 113 | -} | ||
| 114 | - | ||
| 115 | -pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { | ||
| 116 | - let tx = conn.transaction().await?; | ||
| 117 | - if !is_requested(other, me, &tx).await? { | ||
| 118 | - return Err(CommonError::NotFound.into()); | ||
| 119 | - } | ||
| 120 | - befriend(me, other, &tx).await?; | ||
| 121 | - tx.commit().await?; | ||
| 122 | - | ||
| 123 | - Ok(()) | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | -pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), ServerError> { | ||
| 127 | - let tx = conn.transaction().await?; | ||
| 128 | - tx.execute( | ||
| 129 | - "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)", | ||
| 130 | - (me, other), | ||
| 131 | - ) | ||
| 132 | - .await?; | ||
| 133 | - tx.execute( | ||
| 134 | - "DELETE FROM friend_request WHERE (from_id = ?1 AND to_id = ?2) OR (from_id = ?2 AND to_id = ?1)", | ||
| 135 | - (me, other), | ||
| 136 | - ) | ||
| 137 | - .await?; | ||
| 138 | - tx.commit().await?; | ||
| 139 | - | ||
| 140 | - Ok(()) | ||
| 141 | -} | ||
crates/server/src/hub.rsmodified+27 -38
| @@ -7,7 +7,7 @@ use std::{ | |||
| 7 | }; | 7 | }; |
| 8 | 8 | ||
| 9 | use bytes::Bytes; | 9 | use bytes::Bytes; |
| 10 | -use common::transport::Close; | 10 | +use common::{model::Id, transport::Close}; |
| 11 | use quinn::Connection; | 11 | use quinn::Connection; |
| 12 | use tokio::sync::mpsc::{self, error::TrySendError}; | 12 | use tokio::sync::mpsc::{self, error::TrySendError}; |
| 13 | use tracing::warn; | 13 | use tracing::warn; |
| @@ -19,8 +19,8 @@ const QUEUE_LENGTH: usize = 256; | |||
| 19 | static NEXT_ID: AtomicU64 = AtomicU64::new(1); | 19 | static NEXT_ID: AtomicU64 = AtomicU64::new(1); |
| 20 | 20 | ||
| 21 | pub struct Signed { | 21 | pub struct Signed { |
| 22 | - pub user_id: String, | 22 | + pub user_id: Id, |
| 23 | - pub token: String, | 23 | + pub session_id: Id, |
| 24 | } | 24 | } |
| 25 | 25 | ||
| 26 | pub struct Client { | 26 | pub struct Client { |
| @@ -29,8 +29,8 @@ pub struct Client { | |||
| 29 | pub me: Option<Signed>, | 29 | pub me: Option<Signed>, |
| 30 | tx: mpsc::Sender<Bytes>, | 30 | tx: mpsc::Sender<Bytes>, |
| 31 | pub closed: AtomicBool, | 31 | pub closed: AtomicBool, |
| 32 | - watching: Mutex<Option<String>>, | 32 | + watching: Mutex<Option<Id>>, |
| 33 | - ghost_logged: Mutex<HashSet<String>>, | 33 | + ghost_logged: Mutex<HashSet<Id>>, |
| 34 | } | 34 | } |
| 35 | 35 | ||
| 36 | impl Client { | 36 | impl Client { |
| @@ -53,8 +53,8 @@ impl Client { | |||
| 53 | Self::new(None, me).0 | 53 | Self::new(None, me).0 |
| 54 | } | 54 | } |
| 55 | 55 | ||
| 56 | - pub fn user_id(&self) -> Option<&str> { | 56 | + pub fn user_id(&self) -> Option<Id> { |
| 57 | - self.me.as_ref().map(|me| me.user_id.as_str()) | 57 | + self.me.as_ref().map(|me| me.user_id) |
| 58 | } | 58 | } |
| 59 | 59 | ||
| 60 | pub fn close(&self, close: Close) { | 60 | pub fn close(&self, close: Close) { |
| @@ -63,22 +63,19 @@ impl Client { | |||
| 63 | } | 63 | } |
| 64 | } | 64 | } |
| 65 | 65 | ||
| 66 | - pub fn first_visit(&self, community_id: &str) -> bool { | 66 | + pub fn first_visit(&self, community_id: Id) -> bool { |
| 67 | - self.ghost_logged | 67 | + self.ghost_logged.lock().unwrap().insert(community_id) |
| 68 | - .lock() | ||
| 69 | - .unwrap() | ||
| 70 | - .insert(community_id.to_string()) | ||
| 71 | } | 68 | } |
| 72 | 69 | ||
| 73 | - pub fn watch(&self, community_id: Option<&str>) { | 70 | + pub fn watch(&self, community_id: Option<Id>) { |
| 74 | - *self.watching.lock().unwrap() = community_id.map(str::to_string); | 71 | + *self.watching.lock().unwrap() = community_id; |
| 75 | } | 72 | } |
| 76 | } | 73 | } |
| 77 | 74 | ||
| 78 | pub enum Presence { | 75 | pub enum Presence { |
| 79 | None, | 76 | None, |
| 80 | - Online(String), | 77 | + Online(Id), |
| 81 | - Offline(String), | 78 | + Offline(Id), |
| 82 | } | 79 | } |
| 83 | 80 | ||
| 84 | #[derive(Clone, Default)] | 81 | #[derive(Clone, Default)] |
| @@ -87,10 +84,8 @@ pub struct Hub(Arc<Mutex<HashMap<ConnId, Arc<Client>>>>); | |||
| 87 | impl Hub { | 84 | impl Hub { |
| 88 | pub fn add(&self, client: Arc<Client>) -> Presence { | 85 | pub fn add(&self, client: Arc<Client>) -> Presence { |
| 89 | let mut clients = self.0.lock().unwrap(); | 86 | let mut clients = self.0.lock().unwrap(); |
| 90 | - let user_id = client.user_id().map(str::to_string); | 87 | + let user_id = client.user_id(); |
| 91 | - let was_online = user_id | 88 | + let was_online = user_id.is_some_and(|user_id| Self::online_in(&clients, user_id)); |
| 92 | - .as_deref() | ||
| 93 | - .is_some_and(|user_id| Self::online_in(&clients, user_id)); | ||
| 94 | clients.insert(client.id, client); | 89 | clients.insert(client.id, client); |
| 95 | 90 | ||
| 96 | match user_id { | 91 | match user_id { |
| @@ -106,26 +101,24 @@ impl Hub { | |||
| 106 | }; | 101 | }; |
| 107 | 102 | ||
| 108 | match client.user_id() { | 103 | match client.user_id() { |
| 109 | - Some(user_id) if !Self::online_in(&clients, user_id) => { | 104 | + Some(user_id) if !Self::online_in(&clients, user_id) => Presence::Offline(user_id), |
| 110 | - Presence::Offline(user_id.to_string()) | ||
| 111 | - } | ||
| 112 | _ => Presence::None, | 105 | _ => Presence::None, |
| 113 | } | 106 | } |
| 114 | } | 107 | } |
| 115 | 108 | ||
| 116 | - fn online_in(clients: &HashMap<ConnId, Arc<Client>>, user_id: &str) -> bool { | 109 | + fn online_in(clients: &HashMap<ConnId, Arc<Client>>, user_id: Id) -> bool { |
| 117 | clients | 110 | clients |
| 118 | .values() | 111 | .values() |
| 119 | .any(|client| client.user_id() == Some(user_id)) | 112 | .any(|client| client.user_id() == Some(user_id)) |
| 120 | } | 113 | } |
| 121 | 114 | ||
| 122 | - pub fn is_online(&self, user_id: &str) -> bool { | 115 | + pub fn is_online(&self, user_id: Id) -> bool { |
| 123 | Self::online_in(&self.0.lock().unwrap(), user_id) | 116 | Self::online_in(&self.0.lock().unwrap(), user_id) |
| 124 | } | 117 | } |
| 125 | 118 | ||
| 126 | pub fn online(&self) -> usize { | 119 | pub fn online(&self) -> usize { |
| 127 | let clients = self.0.lock().unwrap(); | 120 | let clients = self.0.lock().unwrap(); |
| 128 | - let ids: HashSet<&str> = clients | 121 | + let ids: HashSet<Id> = clients |
| 129 | .values() | 122 | .values() |
| 130 | .filter_map(|client| client.user_id()) | 123 | .filter_map(|client| client.user_id()) |
| 131 | .collect(); | 124 | .collect(); |
| @@ -133,26 +126,22 @@ impl Hub { | |||
| 133 | ids.len() | 126 | ids.len() |
| 134 | } | 127 | } |
| 135 | 128 | ||
| 136 | - pub fn conns_of(&self, user_ids: &[String]) -> Vec<ConnId> { | 129 | + pub fn conns_of(&self, user_ids: &[Id]) -> Vec<ConnId> { |
| 137 | self.0 | 130 | self.0 |
| 138 | .lock() | 131 | .lock() |
| 139 | .unwrap() | 132 | .unwrap() |
| 140 | .values() | 133 | .values() |
| 141 | - .filter(|client| { | 134 | + .filter(|client| client.user_id().is_some_and(|id| user_ids.contains(&id))) |
| 142 | - client | ||
| 143 | - .user_id() | ||
| 144 | - .is_some_and(|id| user_ids.iter().any(|u| u == id)) | ||
| 145 | - }) | ||
| 146 | .map(|client| client.id) | 135 | .map(|client| client.id) |
| 147 | .collect() | 136 | .collect() |
| 148 | } | 137 | } |
| 149 | 138 | ||
| 150 | - pub fn watchers(&self, community_id: &str) -> Vec<ConnId> { | 139 | + pub fn watchers(&self, community_id: Id) -> Vec<ConnId> { |
| 151 | self.0 | 140 | self.0 |
| 152 | .lock() | 141 | .lock() |
| 153 | .unwrap() | 142 | .unwrap() |
| 154 | .values() | 143 | .values() |
| 155 | - .filter(|client| client.watching.lock().unwrap().as_deref() == Some(community_id)) | 144 | + .filter(|client| *client.watching.lock().unwrap() == Some(community_id)) |
| 156 | .map(|client| client.id) | 145 | .map(|client| client.id) |
| 157 | .collect() | 146 | .collect() |
| 158 | } | 147 | } |
| @@ -192,15 +181,15 @@ impl Hub { | |||
| 192 | } | 181 | } |
| 193 | } | 182 | } |
| 194 | 183 | ||
| 195 | - pub fn kick_user(&self, user_id: &str, close: Close) { | 184 | + pub fn kick_user(&self, user_id: Id, close: Close) { |
| 196 | self.kick_where(|me| me.user_id == user_id, close); | 185 | self.kick_where(|me| me.user_id == user_id, close); |
| 197 | } | 186 | } |
| 198 | 187 | ||
| 199 | - pub fn kick_token(&self, token: &str, close: Close) { | 188 | + pub fn kick_session(&self, session_id: Id, close: Close) { |
| 200 | - self.kick_where(|me| me.token == token, close); | 189 | + self.kick_where(|me| me.session_id == session_id, close); |
| 201 | } | 190 | } |
| 202 | 191 | ||
| 203 | - pub fn kick_all_except(&self, keep: &[String], close: Close) { | 192 | + pub fn kick_all_except(&self, keep: &[Id], close: Close) { |
| 204 | self.kick_where(|me| !keep.contains(&me.user_id), close); | 193 | self.kick_where(|me| !keep.contains(&me.user_id), close); |
| 205 | } | 194 | } |
| 206 | } | 195 | } |
crates/server/src/invitation.rsdeleted+0 -72
| @@ -1,72 +0,0 @@ | |||
| 1 | -use common::{error::Error as CommonError, model::Invitation}; | ||
| 2 | -use turso::Connection; | ||
| 3 | - | ||
| 4 | -use crate::{community, database, error::ServerError, user}; | ||
| 5 | - | ||
| 6 | -pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, ServerError> { | ||
| 7 | - let pairs = { | ||
| 8 | - let mut rows = conn | ||
| 9 | - .query( | ||
| 10 | - "SELECT community_id, inviter_id FROM invitation WHERE user_id = ?1 ORDER BY community_id", | ||
| 11 | - (user_id,), | ||
| 12 | - ) | ||
| 13 | - .await?; | ||
| 14 | - | ||
| 15 | - let mut pairs: Vec<(String, String)> = Vec::new(); | ||
| 16 | - while let Some(row) = rows.next().await? { | ||
| 17 | - pairs.push((row.get(0)?, row.get(1)?)); | ||
| 18 | - } | ||
| 19 | - | ||
| 20 | - pairs | ||
| 21 | - }; | ||
| 22 | - | ||
| 23 | - let mut invitations = Vec::new(); | ||
| 24 | - for (community_id, inviter_id) in pairs { | ||
| 25 | - invitations.push(Invitation { | ||
| 26 | - community: community::read(&community_id, user_id, conn).await?, | ||
| 27 | - inviter: user::read(&inviter_id, conn).await?, | ||
| 28 | - }); | ||
| 29 | - } | ||
| 30 | - | ||
| 31 | - Ok(invitations) | ||
| 32 | -} | ||
| 33 | - | ||
| 34 | -pub async fn exists( | ||
| 35 | - community_id: &str, | ||
| 36 | - user_id: &str, | ||
| 37 | - conn: &Connection, | ||
| 38 | -) -> Result<bool, ServerError> { | ||
| 39 | - database::exists( | ||
| 40 | - conn, | ||
| 41 | - "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", | ||
| 42 | - (community_id, user_id), | ||
| 43 | - ) | ||
| 44 | - .await | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -pub async fn insert( | ||
| 48 | - community_id: &str, | ||
| 49 | - user_id: &str, | ||
| 50 | - inviter_id: &str, | ||
| 51 | - conn: &Connection, | ||
| 52 | -) -> Result<(), ServerError> { | ||
| 53 | - conn.execute( | ||
| 54 | - "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", | ||
| 55 | - (community_id, user_id, inviter_id), | ||
| 56 | - ) | ||
| 57 | - .await?; | ||
| 58 | - | ||
| 59 | - Ok(()) | ||
| 60 | -} | ||
| 61 | - | ||
| 62 | -pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 63 | - let mut rows = conn | ||
| 64 | - .query( | ||
| 65 | - "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2 RETURNING community_id", | ||
| 66 | - (community_id, user_id), | ||
| 67 | - ) | ||
| 68 | - .await?; | ||
| 69 | - rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 70 | - | ||
| 71 | - Ok(()) | ||
| 72 | -} | ||
crates/server/src/invite.rsdeleted+0 -89
| @@ -1,89 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - error::Error as CommonError, | ||
| 3 | - model::{InviteCode, User}, | ||
| 4 | - time::{self, HOUR_MILLIS}, | ||
| 5 | -}; | ||
| 6 | -use turso::Connection; | ||
| 7 | - | ||
| 8 | -use crate::{authentication, error::ServerError}; | ||
| 9 | - | ||
| 10 | -const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | ||
| 11 | -const CODE_LENGTH: usize = 8; | ||
| 12 | - | ||
| 13 | -fn generate() -> Result<String, ServerError> { | ||
| 14 | - let bytes = authentication::random_bytes::<CODE_LENGTH>()?; | ||
| 15 | - | ||
| 16 | - Ok(bytes | ||
| 17 | - .iter() | ||
| 18 | - .map(|byte| char::from(ALPHABET[usize::from(*byte) % ALPHABET.len()])) | ||
| 19 | - .collect()) | ||
| 20 | -} | ||
| 21 | - | ||
| 22 | -pub async fn create( | ||
| 23 | - uses: u32, | ||
| 24 | - hours: Option<u32>, | ||
| 25 | - created_by: &User, | ||
| 26 | - conn: &Connection, | ||
| 27 | -) -> Result<InviteCode, ServerError> { | ||
| 28 | - let code = generate()?; | ||
| 29 | - let expires_at = hours.map(|hours| time::now_ms() + u64::from(hours) * HOUR_MILLIS); | ||
| 30 | - conn.execute( | ||
| 31 | - "INSERT INTO invite_code (code, uses_left, expires_at, created_by) VALUES (?1, ?2, ?3, ?4)", | ||
| 32 | - ( | ||
| 33 | - code.as_str(), | ||
| 34 | - i64::from(uses), | ||
| 35 | - expires_at.map(|millis| millis as i64), | ||
| 36 | - created_by.id.as_str(), | ||
| 37 | - ), | ||
| 38 | - ) | ||
| 39 | - .await?; | ||
| 40 | - | ||
| 41 | - Ok(InviteCode { | ||
| 42 | - code, | ||
| 43 | - uses_left: uses, | ||
| 44 | - expires_at, | ||
| 45 | - }) | ||
| 46 | -} | ||
| 47 | - | ||
| 48 | -pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, ServerError> { | ||
| 49 | - let mut rows = conn | ||
| 50 | - .query("SELECT code, uses_left, expires_at FROM invite_code", ()) | ||
| 51 | - .await?; | ||
| 52 | - | ||
| 53 | - let mut codes = Vec::new(); | ||
| 54 | - while let Some(row) = rows.next().await? { | ||
| 55 | - let uses_left: i64 = row.get(1)?; | ||
| 56 | - let expires_at: Option<i64> = row.get(2)?; | ||
| 57 | - codes.push(InviteCode { | ||
| 58 | - code: row.get(0)?, | ||
| 59 | - uses_left: uses_left as u32, | ||
| 60 | - expires_at: expires_at.map(|millis| millis as u64), | ||
| 61 | - }); | ||
| 62 | - } | ||
| 63 | - | ||
| 64 | - Ok(codes) | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -pub async fn delete(code: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 68 | - let mut rows = conn | ||
| 69 | - .query( | ||
| 70 | - "DELETE FROM invite_code WHERE code = ?1 RETURNING code", | ||
| 71 | - (code,), | ||
| 72 | - ) | ||
| 73 | - .await?; | ||
| 74 | - rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 75 | - | ||
| 76 | - Ok(()) | ||
| 77 | -} | ||
| 78 | - | ||
| 79 | -pub async fn consume(code: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 80 | - let mut rows = conn | ||
| 81 | - .query( | ||
| 82 | - "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", | ||
| 83 | - (code, time::now_ms() as i64), | ||
| 84 | - ) | ||
| 85 | - .await?; | ||
| 86 | - rows.next().await?.ok_or(CommonError::RegistrationClosed)?; | ||
| 87 | - | ||
| 88 | - Ok(()) | ||
| 89 | -} | ||
crates/server/src/lib.rsmodified+16 -29
| @@ -1,34 +1,18 @@ | |||
| 1 | -pub mod admin_log; | ||
| 2 | -pub mod attachment; | ||
| 3 | pub mod authentication; | 1 | pub mod authentication; |
| 4 | pub mod backup; | 2 | pub mod backup; |
| 5 | pub mod call; | 3 | pub mod call; |
| 6 | pub mod certificate; | 4 | pub mod certificate; |
| 7 | -pub mod community; | ||
| 8 | -pub mod database; | ||
| 9 | pub mod datagram; | 5 | pub mod datagram; |
| 10 | -pub mod direct; | 6 | +pub mod db; |
| 11 | pub mod error; | 7 | pub mod error; |
| 12 | -pub mod friend; | 8 | +pub mod files; |
| 13 | pub mod hub; | 9 | pub mod hub; |
| 14 | -pub mod invitation; | ||
| 15 | -pub mod invite; | ||
| 16 | -pub mod log; | ||
| 17 | -pub mod message; | ||
| 18 | pub mod network; | 10 | pub mod network; |
| 19 | -pub mod notes; | ||
| 20 | -pub mod overview; | ||
| 21 | pub mod publish; | 11 | pub mod publish; |
| 22 | pub mod rate_limit; | 12 | pub mod rate_limit; |
| 23 | -pub mod report; | ||
| 24 | pub mod request; | 13 | pub mod request; |
| 25 | pub mod retention; | 14 | pub mod retention; |
| 26 | pub mod rooms; | 15 | pub mod rooms; |
| 27 | -pub mod server_ban; | ||
| 28 | -pub mod server_settings; | ||
| 29 | -pub mod stats; | ||
| 30 | -pub mod user; | ||
| 31 | -pub mod user_community; | ||
| 32 | 16 | ||
| 33 | #[cfg(test)] | 17 | #[cfg(test)] |
| 34 | mod test; | 18 | mod test; |
| @@ -37,7 +21,7 @@ use std::path::{Path, PathBuf}; | |||
| 37 | 21 | ||
| 38 | use common::{config::Config, error::Error as CommonError, model::Role}; | 22 | use common::{config::Config, error::Error as CommonError, model::Role}; |
| 39 | 23 | ||
| 40 | -use crate::error::ServerError; | 24 | +use crate::{db::Db, error::ServerError}; |
| 41 | 25 | ||
| 42 | const SERVER_CONFIG_FILE_PATH: &str = concat!( | 26 | const SERVER_CONFIG_FILE_PATH: &str = concat!( |
| 43 | env!("CARGO_MANIFEST_DIR"), | 27 | env!("CARGO_MANIFEST_DIR"), |
| @@ -84,11 +68,11 @@ pub async fn showtime() -> Result<(), ServerError> { | |||
| 84 | 68 | ||
| 85 | let config = load_config()?; | 69 | let config = load_config()?; |
| 86 | 70 | ||
| 87 | - let database = database::open(&config.database_path).await?; | 71 | + let database = Db::open(&config.database_path).await?; |
| 88 | let certificate = certificate::load(&config.certificate_path, &config.key_path)?; | 72 | let certificate = certificate::load(&config.certificate_path, &config.key_path)?; |
| 89 | let attachments = sibling_directory(&config.database_path, "attachments")?; | 73 | let attachments = sibling_directory(&config.database_path, "attachments")?; |
| 90 | let backups = sibling_directory(&config.database_path, "backups")?; | 74 | let backups = sibling_directory(&config.database_path, "backups")?; |
| 91 | - tokio::spawn(attachment::collect(database.clone(), attachments.clone())); | 75 | + tokio::spawn(files::collect(database.clone(), attachments.clone())); |
| 92 | 76 | ||
| 93 | network::serve( | 77 | network::serve( |
| 94 | &config.server_address, | 78 | &config.server_address, |
| @@ -102,12 +86,15 @@ pub async fn showtime() -> Result<(), ServerError> { | |||
| 102 | 86 | ||
| 103 | pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> { | 87 | pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> { |
| 104 | let config = load_config()?; | 88 | let config = load_config()?; |
| 105 | - let database = database::open(&config.database_path).await?; | 89 | + let database = Db::open(&config.database_path).await?; |
| 106 | - let conn = database::connect(&database).await?; | 90 | + database |
| 107 | - let user = user::by_username(username, &conn) | 91 | + .run(async |db| { |
| 108 | - .await? | 92 | + let user = db::user::by_username(username, db) |
| 109 | - .ok_or(CommonError::NotFound)?; | 93 | + .await? |
| 110 | - user::set_role_by_id(&user.id, role, &conn).await?; | 94 | + .ok_or(CommonError::NotFound)?; |
| 111 | - | 95 | + db::user::set_role_by_id(user.id, role, db).await?; |
| 112 | - Ok(()) | 96 | + |
| 97 | + Ok(()) | ||
| 98 | + }) | ||
| 99 | + .await | ||
| 113 | } | 100 | } |
crates/server/src/log.rsdeleted+0 -105
| @@ -1,105 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - constant::LOG_PAGE_LIMIT, | ||
| 3 | - model::{LogAction, LogEntry, Rank}, | ||
| 4 | -}; | ||
| 5 | -use turso::Connection; | ||
| 6 | - | ||
| 7 | -use crate::{database::new_id, error::ServerError, user}; | ||
| 8 | - | ||
| 9 | -common::string_enum! { | ||
| 10 | - #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 11 | - Kind { | ||
| 12 | - Created => "created", | ||
| 13 | - Renamed => "renamed", | ||
| 14 | - AvatarChanged => "avatar_changed", | ||
| 15 | - AvatarRemoved => "avatar_removed", | ||
| 16 | - Invited => "invited", | ||
| 17 | - Joined => "joined", | ||
| 18 | - Left => "left", | ||
| 19 | - Kicked => "kicked", | ||
| 20 | - Banned => "banned", | ||
| 21 | - Unbanned => "unbanned", | ||
| 22 | - RankChanged => "rank_changed", | ||
| 23 | - MessageDeleted => "message_deleted", | ||
| 24 | - } | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -fn parts(action: &LogAction) -> (&'static str, Option<String>) { | ||
| 28 | - let (kind, detail) = match action { | ||
| 29 | - LogAction::Created => (Kind::Created, None), | ||
| 30 | - LogAction::Renamed { name } => (Kind::Renamed, Some(name.clone())), | ||
| 31 | - LogAction::AvatarChanged => (Kind::AvatarChanged, None), | ||
| 32 | - LogAction::AvatarRemoved => (Kind::AvatarRemoved, None), | ||
| 33 | - LogAction::Invited => (Kind::Invited, None), | ||
| 34 | - LogAction::Joined => (Kind::Joined, None), | ||
| 35 | - LogAction::Left => (Kind::Left, None), | ||
| 36 | - LogAction::Kicked { reason } => (Kind::Kicked, reason.clone()), | ||
| 37 | - LogAction::Banned { reason } => (Kind::Banned, reason.clone()), | ||
| 38 | - LogAction::Unbanned => (Kind::Unbanned, None), | ||
| 39 | - LogAction::RankChanged { rank } => (Kind::RankChanged, Some(rank.as_str().to_string())), | ||
| 40 | - LogAction::MessageDeleted => (Kind::MessageDeleted, None), | ||
| 41 | - }; | ||
| 42 | - (kind.as_str(), detail) | ||
| 43 | -} | ||
| 44 | - | ||
| 45 | -fn action_of(text: &str, detail: Option<String>) -> Option<LogAction> { | ||
| 46 | - Some(match Kind::parse(text)? { | ||
| 47 | - Kind::Created => LogAction::Created, | ||
| 48 | - Kind::Renamed => LogAction::Renamed { name: detail? }, | ||
| 49 | - Kind::AvatarChanged => LogAction::AvatarChanged, | ||
| 50 | - Kind::AvatarRemoved => LogAction::AvatarRemoved, | ||
| 51 | - Kind::Invited => LogAction::Invited, | ||
| 52 | - Kind::Joined => LogAction::Joined, | ||
| 53 | - Kind::Left => LogAction::Left, | ||
| 54 | - Kind::Kicked => LogAction::Kicked { reason: detail }, | ||
| 55 | - Kind::Banned => LogAction::Banned { reason: detail }, | ||
| 56 | - Kind::Unbanned => LogAction::Unbanned, | ||
| 57 | - Kind::RankChanged => LogAction::RankChanged { | ||
| 58 | - rank: Rank::parse(&detail?)?, | ||
| 59 | - }, | ||
| 60 | - Kind::MessageDeleted => LogAction::MessageDeleted, | ||
| 61 | - }) | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -pub async fn record( | ||
| 65 | - community_id: &str, | ||
| 66 | - actor_id: Option<&str>, | ||
| 67 | - target_id: Option<&str>, | ||
| 68 | - action: &LogAction, | ||
| 69 | - conn: &Connection, | ||
| 70 | -) -> Result<(), ServerError> { | ||
| 71 | - let id = new_id(); | ||
| 72 | - let (action, detail) = parts(action); | ||
| 73 | - conn.execute( | ||
| 74 | - "INSERT INTO community_log (id, community_id, actor_id, target_id, action, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | ||
| 75 | - (id.as_str(), community_id, actor_id, target_id, action, detail.as_deref()), | ||
| 76 | - ) | ||
| 77 | - .await?; | ||
| 78 | - | ||
| 79 | - Ok(()) | ||
| 80 | -} | ||
| 81 | - | ||
| 82 | -pub async fn list(community_id: &str, conn: &Connection) -> Result<Vec<LogEntry>, ServerError> { | ||
| 83 | - let mut rows = conn | ||
| 84 | - .query( | ||
| 85 | - &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")), | ||
| 86 | - (community_id,), | ||
| 87 | - ) | ||
| 88 | - .await?; | ||
| 89 | - | ||
| 90 | - let mut entries = Vec::new(); | ||
| 91 | - while let Some(row) = rows.next().await? { | ||
| 92 | - let text: String = row.get(1)?; | ||
| 93 | - let Some(action) = action_of(&text, row.get(2)?) else { | ||
| 94 | - continue; | ||
| 95 | - }; | ||
| 96 | - entries.push(LogEntry { | ||
| 97 | - id: row.get(0)?, | ||
| 98 | - actor: user::from_row_at(&row, 3)?, | ||
| 99 | - target: user::from_row_at(&row, 8)?, | ||
| 100 | - action, | ||
| 101 | - }); | ||
| 102 | - } | ||
| 103 | - | ||
| 104 | - Ok(entries) | ||
| 105 | -} | ||
crates/server/src/message.rsdeleted+0 -860
| @@ -1,860 +0,0 @@ | |||
| 1 | -use std::{collections::HashMap, path::Path}; | ||
| 2 | - | ||
| 3 | -use common::{ | ||
| 4 | - constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT}, | ||
| 5 | - error::{Error as CommonError, Field, Problem}, | ||
| 6 | - model::{ | ||
| 7 | - CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage, | ||
| 8 | - User, | ||
| 9 | - }, | ||
| 10 | - time, | ||
| 11 | -}; | ||
| 12 | -use turso::{Connection, Row}; | ||
| 13 | - | ||
| 14 | -use crate::{attachment, community, database, database::new_id, error::ServerError, user}; | ||
| 15 | - | ||
| 16 | -const SEARCH_LIMIT: usize = 200; | ||
| 17 | - | ||
| 18 | -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"; | ||
| 19 | - | ||
| 20 | -fn from_row(row: &Row) -> Result<Message, ServerError> { | ||
| 21 | - let edited: i64 = row.get(4)?; | ||
| 22 | - let call_seconds: i64 = row.get(10)?; | ||
| 23 | - let pinned: i64 = row.get(11)?; | ||
| 24 | - let call = row | ||
| 25 | - .get::<Option<String>>(9)? | ||
| 26 | - .and_then(|text| CallLog::parse(&text, call_seconds as u64)); | ||
| 27 | - let reply = match row.get::<Option<String>>(5)? { | ||
| 28 | - Some(message_id) => { | ||
| 29 | - let body: String = row.get(7)?; | ||
| 30 | - let attachments: i64 = row.get(8)?; | ||
| 31 | - Some(Quote { | ||
| 32 | - message_id, | ||
| 33 | - user_id: row.get(6)?, | ||
| 34 | - body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(), | ||
| 35 | - attachments: attachments as usize, | ||
| 36 | - }) | ||
| 37 | - } | ||
| 38 | - None => None, | ||
| 39 | - }; | ||
| 40 | - | ||
| 41 | - Ok(Message { | ||
| 42 | - id: row.get(0)?, | ||
| 43 | - user_id: row.get(1)?, | ||
| 44 | - community_id: row.get(2)?, | ||
| 45 | - body: row.get(3)?, | ||
| 46 | - attachments: Vec::new(), | ||
| 47 | - reactions: Vec::new(), | ||
| 48 | - reply, | ||
| 49 | - snippet: None, | ||
| 50 | - poll: None, | ||
| 51 | - edited: edited != 0, | ||
| 52 | - pinned: pinned != 0, | ||
| 53 | - call, | ||
| 54 | - }) | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -fn placeholders(count: usize) -> String { | ||
| 58 | - (1..=count) | ||
| 59 | - .map(|index| format!("?{index}")) | ||
| 60 | - .collect::<Vec<_>>() | ||
| 61 | - .join(", ") | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -async fn reactions_of( | ||
| 65 | - message_ids: &[String], | ||
| 66 | - conn: &Connection, | ||
| 67 | -) -> Result<HashMap<String, Vec<Reaction>>, ServerError> { | ||
| 68 | - let mut reactions: HashMap<String, Vec<Reaction>> = HashMap::new(); | ||
| 69 | - if message_ids.is_empty() { | ||
| 70 | - return Ok(reactions); | ||
| 71 | - } | ||
| 72 | - | ||
| 73 | - let placeholders = placeholders(message_ids.len()); | ||
| 74 | - let mut rows = conn | ||
| 75 | - .query( | ||
| 76 | - &format!( | ||
| 77 | - "SELECT message_id, emoji, user_id FROM reaction WHERE message_id IN ({placeholders}) ORDER BY message_id, emoji, user_id" | ||
| 78 | - ), | ||
| 79 | - message_ids.to_vec(), | ||
| 80 | - ) | ||
| 81 | - .await?; | ||
| 82 | - | ||
| 83 | - while let Some(row) = rows.next().await? { | ||
| 84 | - let message_id: String = row.get(0)?; | ||
| 85 | - let emoji: String = row.get(1)?; | ||
| 86 | - let user_id: String = row.get(2)?; | ||
| 87 | - let entries = reactions.entry(message_id).or_default(); | ||
| 88 | - match entries | ||
| 89 | - .last_mut() | ||
| 90 | - .filter(|reaction| reaction.emoji == emoji) | ||
| 91 | - { | ||
| 92 | - Some(reaction) => reaction.user_ids.push(user_id), | ||
| 93 | - None => entries.push(Reaction { | ||
| 94 | - emoji, | ||
| 95 | - user_ids: vec![user_id], | ||
| 96 | - }), | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - | ||
| 100 | - Ok(reactions) | ||
| 101 | -} | ||
| 102 | - | ||
| 103 | -async fn polls_of( | ||
| 104 | - message_ids: &[String], | ||
| 105 | - conn: &Connection, | ||
| 106 | -) -> Result<HashMap<String, Poll>, ServerError> { | ||
| 107 | - let mut polls: HashMap<String, Poll> = HashMap::new(); | ||
| 108 | - if message_ids.is_empty() { | ||
| 109 | - return Ok(polls); | ||
| 110 | - } | ||
| 111 | - | ||
| 112 | - let placeholders = placeholders(message_ids.len()); | ||
| 113 | - let mut rows = conn | ||
| 114 | - .query( | ||
| 115 | - &format!( | ||
| 116 | - "SELECT message_id, question, multiple, closed FROM poll WHERE message_id IN ({placeholders})" | ||
| 117 | - ), | ||
| 118 | - message_ids.to_vec(), | ||
| 119 | - ) | ||
| 120 | - .await?; | ||
| 121 | - while let Some(row) = rows.next().await? { | ||
| 122 | - let multiple: i64 = row.get(2)?; | ||
| 123 | - let closed: i64 = row.get(3)?; | ||
| 124 | - polls.insert( | ||
| 125 | - row.get(0)?, | ||
| 126 | - Poll { | ||
| 127 | - question: row.get(1)?, | ||
| 128 | - options: Vec::new(), | ||
| 129 | - multiple: multiple != 0, | ||
| 130 | - closed: closed != 0, | ||
| 131 | - }, | ||
| 132 | - ); | ||
| 133 | - } | ||
| 134 | - drop(rows); | ||
| 135 | - | ||
| 136 | - let mut rows = conn | ||
| 137 | - .query( | ||
| 138 | - &format!( | ||
| 139 | - "SELECT message_id, text FROM poll_option WHERE message_id IN ({placeholders}) ORDER BY message_id, position" | ||
| 140 | - ), | ||
| 141 | - message_ids.to_vec(), | ||
| 142 | - ) | ||
| 143 | - .await?; | ||
| 144 | - while let Some(row) = rows.next().await? { | ||
| 145 | - let message_id: String = row.get(0)?; | ||
| 146 | - if let Some(poll) = polls.get_mut(&message_id) { | ||
| 147 | - poll.options.push(PollOption { | ||
| 148 | - text: row.get(1)?, | ||
| 149 | - voter_ids: Vec::new(), | ||
| 150 | - }); | ||
| 151 | - } | ||
| 152 | - } | ||
| 153 | - drop(rows); | ||
| 154 | - | ||
| 155 | - let mut rows = conn | ||
| 156 | - .query( | ||
| 157 | - &format!( | ||
| 158 | - "SELECT message_id, position, user_id FROM poll_vote WHERE message_id IN ({placeholders}) ORDER BY message_id, position, user_id" | ||
| 159 | - ), | ||
| 160 | - message_ids.to_vec(), | ||
| 161 | - ) | ||
| 162 | - .await?; | ||
| 163 | - while let Some(row) = rows.next().await? { | ||
| 164 | - let message_id: String = row.get(0)?; | ||
| 165 | - let position: i64 = row.get(1)?; | ||
| 166 | - let option = polls | ||
| 167 | - .get_mut(&message_id) | ||
| 168 | - .and_then(|poll| poll.options.get_mut(position as usize)); | ||
| 169 | - if let Some(option) = option { | ||
| 170 | - option.voter_ids.push(row.get(2)?); | ||
| 171 | - } | ||
| 172 | - } | ||
| 173 | - | ||
| 174 | - Ok(polls) | ||
| 175 | -} | ||
| 176 | - | ||
| 177 | -async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippet>, ServerError> { | ||
| 178 | - let mut rows = conn | ||
| 179 | - .query( | ||
| 180 | - "SELECT origin FROM snippet WHERE message_id = ?1", | ||
| 181 | - (message_id,), | ||
| 182 | - ) | ||
| 183 | - .await?; | ||
| 184 | - let Some(row) = rows.next().await? else { | ||
| 185 | - return Ok(None); | ||
| 186 | - }; | ||
| 187 | - let origin: Option<String> = row.get(0)?; | ||
| 188 | - drop(rows); | ||
| 189 | - | ||
| 190 | - let mut rows = conn | ||
| 191 | - .query( | ||
| 192 | - "SELECT position, original_id, user_id, username, avatar_id, body, poll FROM snippet_message WHERE message_id = ?1 ORDER BY position", | ||
| 193 | - (message_id,), | ||
| 194 | - ) | ||
| 195 | - .await?; | ||
| 196 | - let mut entries = Vec::new(); | ||
| 197 | - while let Some(row) = rows.next().await? { | ||
| 198 | - let position: i64 = row.get(0)?; | ||
| 199 | - entries.push(( | ||
| 200 | - position, | ||
| 201 | - SnippetMessage { | ||
| 202 | - id: row.get(1)?, | ||
| 203 | - user_id: row.get(2)?, | ||
| 204 | - username: row.get(3)?, | ||
| 205 | - avatar_id: row.get(4)?, | ||
| 206 | - body: row.get(5)?, | ||
| 207 | - attachments: Vec::new(), | ||
| 208 | - poll: row | ||
| 209 | - .get::<Option<Vec<u8>>>(6)? | ||
| 210 | - .and_then(|bytes| bitcode::decode(&bytes).ok()), | ||
| 211 | - }, | ||
| 212 | - )); | ||
| 213 | - } | ||
| 214 | - drop(rows); | ||
| 215 | - | ||
| 216 | - let mut messages = Vec::new(); | ||
| 217 | - for (position, mut entry) in entries { | ||
| 218 | - entry.attachments = attachment::of_message(message_id, Some(position), conn).await?; | ||
| 219 | - messages.push(entry); | ||
| 220 | - } | ||
| 221 | - | ||
| 222 | - Ok(Some(Snippet { origin, messages })) | ||
| 223 | -} | ||
| 224 | - | ||
| 225 | -async fn hydrate(messages: Vec<Message>, conn: &Connection) -> Result<Vec<Message>, ServerError> { | ||
| 226 | - let ids: Vec<String> = messages.iter().map(|message| message.id.clone()).collect(); | ||
| 227 | - let mut reactions = reactions_of(&ids, conn).await?; | ||
| 228 | - let mut polls = polls_of(&ids, conn).await?; | ||
| 229 | - | ||
| 230 | - let mut hydrated = Vec::new(); | ||
| 231 | - for mut message in messages { | ||
| 232 | - message.reactions = reactions.remove(&message.id).unwrap_or_default(); | ||
| 233 | - message.poll = polls.remove(&message.id); | ||
| 234 | - message.attachments = attachment::of_message(&message.id, None, conn).await?; | ||
| 235 | - message.snippet = snippet_of(&message.id, conn).await?; | ||
| 236 | - hydrated.push(message); | ||
| 237 | - } | ||
| 238 | - | ||
| 239 | - Ok(hydrated) | ||
| 240 | -} | ||
| 241 | - | ||
| 242 | -async fn insert( | ||
| 243 | - user_id: &str, | ||
| 244 | - community_id: &str, | ||
| 245 | - body: &str, | ||
| 246 | - reply_to: Option<&str>, | ||
| 247 | - conn: &Connection, | ||
| 248 | -) -> Result<String, ServerError> { | ||
| 249 | - let message_id = new_id(); | ||
| 250 | - conn.execute( | ||
| 251 | - "INSERT INTO message (id, user_id, community_id, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 252 | - (message_id.as_str(), user_id, community_id, body, reply_to), | ||
| 253 | - ) | ||
| 254 | - .await?; | ||
| 255 | - | ||
| 256 | - Ok(message_id) | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -pub async fn ensure_in_community( | ||
| 260 | - message_id: &str, | ||
| 261 | - community_id: &str, | ||
| 262 | - conn: &Connection, | ||
| 263 | -) -> Result<(), ServerError> { | ||
| 264 | - let mut rows = conn | ||
| 265 | - .query( | ||
| 266 | - "SELECT id FROM message WHERE id = ?1 AND community_id = ?2", | ||
| 267 | - (message_id, community_id), | ||
| 268 | - ) | ||
| 269 | - .await?; | ||
| 270 | - if rows.next().await?.is_none() { | ||
| 271 | - return Err(CommonError::NotFound.into()); | ||
| 272 | - } | ||
| 273 | - | ||
| 274 | - Ok(()) | ||
| 275 | -} | ||
| 276 | - | ||
| 277 | -pub async fn create_call_log( | ||
| 278 | - community_id: &str, | ||
| 279 | - user_id: &str, | ||
| 280 | - call: CallLog, | ||
| 281 | - conn: &Connection, | ||
| 282 | -) -> Result<Message, ServerError> { | ||
| 283 | - let message_id = new_id(); | ||
| 284 | - conn.execute( | ||
| 285 | - "INSERT INTO message (id, user_id, community_id, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5)", | ||
| 286 | - ( | ||
| 287 | - message_id.as_str(), | ||
| 288 | - user_id, | ||
| 289 | - community_id, | ||
| 290 | - call.as_str(), | ||
| 291 | - call.seconds() as i64, | ||
| 292 | - ), | ||
| 293 | - ) | ||
| 294 | - .await?; | ||
| 295 | - | ||
| 296 | - read(&message_id, conn).await | ||
| 297 | -} | ||
| 298 | - | ||
| 299 | -pub async fn create( | ||
| 300 | - user_id: &str, | ||
| 301 | - community_id: &str, | ||
| 302 | - body: &str, | ||
| 303 | - attachments: &[String], | ||
| 304 | - reply_to: Option<&str>, | ||
| 305 | - conn: &Connection, | ||
| 306 | -) -> Result<Message, ServerError> { | ||
| 307 | - if let Some(reply_to) = reply_to { | ||
| 308 | - ensure_in_community(reply_to, community_id, conn).await?; | ||
| 309 | - } | ||
| 310 | - | ||
| 311 | - let message_id = insert(user_id, community_id, body, reply_to, conn).await?; | ||
| 312 | - attachment::bind(&message_id, user_id, community_id, attachments, conn).await?; | ||
| 313 | - | ||
| 314 | - read(&message_id, conn).await | ||
| 315 | -} | ||
| 316 | - | ||
| 317 | -pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, ServerError> { | ||
| 318 | - let mut rows = conn | ||
| 319 | - .query(&format!("{SELECT} WHERE m.id = ?1"), (message_id,)) | ||
| 320 | - .await?; | ||
| 321 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 322 | - let message = from_row(&row)?; | ||
| 323 | - drop(rows); | ||
| 324 | - | ||
| 325 | - hydrate(vec![message], conn) | ||
| 326 | - .await? | ||
| 327 | - .pop() | ||
| 328 | - .ok_or(CommonError::NotFound.into()) | ||
| 329 | -} | ||
| 330 | - | ||
| 331 | -pub async fn read_page( | ||
| 332 | - community_id: &str, | ||
| 333 | - before: Option<&str>, | ||
| 334 | - conn: &Connection, | ||
| 335 | -) -> Result<Vec<Message>, ServerError> { | ||
| 336 | - let mut rows = conn | ||
| 337 | - .query( | ||
| 338 | - &format!( | ||
| 339 | - "{SELECT} WHERE m.community_id = ?1 AND (?2 IS NULL OR m.id < ?2) ORDER BY m.id DESC LIMIT ?3" | ||
| 340 | - ), | ||
| 341 | - (community_id, before, MESSAGE_PAGE_LIMIT as i64), | ||
| 342 | - ) | ||
| 343 | - .await?; | ||
| 344 | - | ||
| 345 | - let mut messages = Vec::new(); | ||
| 346 | - while let Some(row) = rows.next().await? { | ||
| 347 | - messages.push(from_row(&row)?); | ||
| 348 | - } | ||
| 349 | - drop(rows); | ||
| 350 | - messages.reverse(); | ||
| 351 | - | ||
| 352 | - hydrate(messages, conn).await | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -pub async fn create_poll( | ||
| 356 | - user_id: &str, | ||
| 357 | - community_id: &str, | ||
| 358 | - question: &str, | ||
| 359 | - options: &[String], | ||
| 360 | - multiple: bool, | ||
| 361 | - conn: &Connection, | ||
| 362 | -) -> Result<Message, ServerError> { | ||
| 363 | - let message_id = insert(user_id, community_id, "", None, conn).await?; | ||
| 364 | - conn.execute( | ||
| 365 | - "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", | ||
| 366 | - (message_id.as_str(), question, multiple as i64), | ||
| 367 | - ) | ||
| 368 | - .await?; | ||
| 369 | - for (position, text) in options.iter().enumerate() { | ||
| 370 | - conn.execute( | ||
| 371 | - "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)", | ||
| 372 | - (message_id.as_str(), position as i64, text.as_str()), | ||
| 373 | - ) | ||
| 374 | - .await?; | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - read(&message_id, conn).await | ||
| 378 | -} | ||
| 379 | - | ||
| 380 | -pub async fn vote( | ||
| 381 | - message_id: &str, | ||
| 382 | - user_id: &str, | ||
| 383 | - positions: &[u32], | ||
| 384 | - conn: &Connection, | ||
| 385 | -) -> Result<Message, ServerError> { | ||
| 386 | - conn.execute( | ||
| 387 | - "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", | ||
| 388 | - (message_id, user_id), | ||
| 389 | - ) | ||
| 390 | - .await?; | ||
| 391 | - for position in positions { | ||
| 392 | - conn.execute( | ||
| 393 | - "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)", | ||
| 394 | - (message_id, *position as i64, user_id), | ||
| 395 | - ) | ||
| 396 | - .await?; | ||
| 397 | - } | ||
| 398 | - | ||
| 399 | - read(message_id, conn).await | ||
| 400 | -} | ||
| 401 | - | ||
| 402 | -pub async fn close_poll(message_id: &str, conn: &Connection) -> Result<Message, ServerError> { | ||
| 403 | - let updated = conn | ||
| 404 | - .execute( | ||
| 405 | - "UPDATE poll SET closed = 1 WHERE message_id = ?1", | ||
| 406 | - (message_id,), | ||
| 407 | - ) | ||
| 408 | - .await?; | ||
| 409 | - database::expect_one(updated)?; | ||
| 410 | - | ||
| 411 | - read(message_id, conn).await | ||
| 412 | -} | ||
| 413 | - | ||
| 414 | -pub async fn react( | ||
| 415 | - message_id: &str, | ||
| 416 | - user_id: &str, | ||
| 417 | - emoji: &str, | ||
| 418 | - conn: &Connection, | ||
| 419 | -) -> Result<Message, ServerError> { | ||
| 420 | - let removed = conn | ||
| 421 | - .execute( | ||
| 422 | - "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", | ||
| 423 | - (message_id, user_id, emoji), | ||
| 424 | - ) | ||
| 425 | - .await?; | ||
| 426 | - if removed == 0 { | ||
| 427 | - conn.execute( | ||
| 428 | - "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)", | ||
| 429 | - (message_id, user_id, emoji), | ||
| 430 | - ) | ||
| 431 | - .await?; | ||
| 432 | - } | ||
| 433 | - | ||
| 434 | - read(message_id, conn).await | ||
| 435 | -} | ||
| 436 | - | ||
| 437 | -pub async fn pin( | ||
| 438 | - message_id: &str, | ||
| 439 | - pinned: bool, | ||
| 440 | - conn: &Connection, | ||
| 441 | -) -> Result<Message, ServerError> { | ||
| 442 | - conn.execute( | ||
| 443 | - "UPDATE message SET pinned = ?2 WHERE id = ?1", | ||
| 444 | - (message_id, pinned as i64), | ||
| 445 | - ) | ||
| 446 | - .await?; | ||
| 447 | - | ||
| 448 | - read(message_id, conn).await | ||
| 449 | -} | ||
| 450 | - | ||
| 451 | -pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message>, ServerError> { | ||
| 452 | - let mut rows = conn | ||
| 453 | - .query( | ||
| 454 | - &format!("{SELECT} WHERE m.community_id = ?1 AND m.pinned = 1 ORDER BY m.id DESC"), | ||
| 455 | - (community_id,), | ||
| 456 | - ) | ||
| 457 | - .await?; | ||
| 458 | - | ||
| 459 | - let mut messages = Vec::new(); | ||
| 460 | - while let Some(row) = rows.next().await? { | ||
| 461 | - messages.push(from_row(&row)?); | ||
| 462 | - } | ||
| 463 | - drop(rows); | ||
| 464 | - | ||
| 465 | - hydrate(messages, conn).await | ||
| 466 | -} | ||
| 467 | - | ||
| 468 | -pub async fn update( | ||
| 469 | - message_id: &str, | ||
| 470 | - body: &str, | ||
| 471 | - conn: &Connection, | ||
| 472 | -) -> Result<Message, ServerError> { | ||
| 473 | - let updated = conn | ||
| 474 | - .execute( | ||
| 475 | - "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1", | ||
| 476 | - (message_id, body), | ||
| 477 | - ) | ||
| 478 | - .await?; | ||
| 479 | - database::expect_one(updated)?; | ||
| 480 | - | ||
| 481 | - read(message_id, conn).await | ||
| 482 | -} | ||
| 483 | - | ||
| 484 | -pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, ServerError> { | ||
| 485 | - let message = read(message_id, conn).await?; | ||
| 486 | - conn.execute("DELETE FROM message WHERE id = ?1", (message_id,)) | ||
| 487 | - .await?; | ||
| 488 | - | ||
| 489 | - Ok(message) | ||
| 490 | -} | ||
| 491 | - | ||
| 492 | -pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 493 | - database::ids( | ||
| 494 | - conn, | ||
| 495 | - "SELECT id FROM message WHERE user_id = ?1", | ||
| 496 | - (user_id,), | ||
| 497 | - ) | ||
| 498 | - .await | ||
| 499 | -} | ||
| 500 | - | ||
| 501 | -pub async fn search( | ||
| 502 | - text: Option<&str>, | ||
| 503 | - user_id: Option<&str>, | ||
| 504 | - community_id: Option<&str>, | ||
| 505 | - after_ms: Option<u64>, | ||
| 506 | - before_ms: Option<u64>, | ||
| 507 | - conn: &Connection, | ||
| 508 | -) -> Result<Vec<MessageHit>, ServerError> { | ||
| 509 | - let (after, before) = time::range_bounds(after_ms, before_ms); | ||
| 510 | - let mut rows = conn | ||
| 511 | - .query( | ||
| 512 | - "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", | ||
| 513 | - ( | ||
| 514 | - text, | ||
| 515 | - user_id, | ||
| 516 | - community_id, | ||
| 517 | - after, | ||
| 518 | - before, | ||
| 519 | - SEARCH_LIMIT as i64, | ||
| 520 | - ), | ||
| 521 | - ) | ||
| 522 | - .await?; | ||
| 523 | - | ||
| 524 | - let mut ids = Vec::new(); | ||
| 525 | - while let Some(row) = rows.next().await? { | ||
| 526 | - ids.push(row.get::<String>(0)?); | ||
| 527 | - } | ||
| 528 | - drop(rows); | ||
| 529 | - | ||
| 530 | - let mut hits = Vec::new(); | ||
| 531 | - for id in ids { | ||
| 532 | - let message = read(&id, conn).await?; | ||
| 533 | - let community = community::label(&message.community_id, conn).await?; | ||
| 534 | - let author = user::read(&message.user_id, conn).await?; | ||
| 535 | - hits.push(MessageHit { | ||
| 536 | - message, | ||
| 537 | - community, | ||
| 538 | - author: Some(author), | ||
| 539 | - }); | ||
| 540 | - } | ||
| 541 | - | ||
| 542 | - Ok(hits) | ||
| 543 | -} | ||
| 544 | - | ||
| 545 | -async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, ServerError> { | ||
| 546 | - let Some(first) = sources.first() else { | ||
| 547 | - return Ok(None); | ||
| 548 | - }; | ||
| 549 | - let community_id = &first.community_id; | ||
| 550 | - if sources | ||
| 551 | - .iter() | ||
| 552 | - .any(|source| &source.community_id != community_id) | ||
| 553 | - { | ||
| 554 | - return Ok(None); | ||
| 555 | - } | ||
| 556 | - | ||
| 557 | - let mut rows = conn | ||
| 558 | - .query( | ||
| 559 | - "SELECT name FROM community WHERE id = ?1 AND kind = ?2", | ||
| 560 | - (community_id.as_str(), community::Kind::Group.as_str()), | ||
| 561 | - ) | ||
| 562 | - .await?; | ||
| 563 | - Ok(match rows.next().await? { | ||
| 564 | - Some(row) => Some(row.get(0)?), | ||
| 565 | - None => None, | ||
| 566 | - }) | ||
| 567 | -} | ||
| 568 | - | ||
| 569 | -async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, ServerError> { | ||
| 570 | - let author: User = user::read(&source.user_id, conn).await?; | ||
| 571 | - | ||
| 572 | - Ok(SnippetMessage { | ||
| 573 | - id: source.id.clone(), | ||
| 574 | - user_id: author.id, | ||
| 575 | - username: author.username, | ||
| 576 | - avatar_id: author.avatar_id, | ||
| 577 | - body: source.body.clone(), | ||
| 578 | - attachments: source.attachments.clone(), | ||
| 579 | - poll: source.poll.clone(), | ||
| 580 | - }) | ||
| 581 | -} | ||
| 582 | - | ||
| 583 | -async fn write_snippet( | ||
| 584 | - message_id: &str, | ||
| 585 | - user_id: &str, | ||
| 586 | - community_id: &str, | ||
| 587 | - origin: Option<&str>, | ||
| 588 | - entries: &[SnippetMessage], | ||
| 589 | - directory: &Path, | ||
| 590 | - conn: &Connection, | ||
| 591 | -) -> Result<(), ServerError> { | ||
| 592 | - conn.execute( | ||
| 593 | - "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)", | ||
| 594 | - (message_id, origin), | ||
| 595 | - ) | ||
| 596 | - .await?; | ||
| 597 | - | ||
| 598 | - for (position, entry) in entries.iter().enumerate() { | ||
| 599 | - let position = position as i64; | ||
| 600 | - let poll = entry.poll.as_ref().map(bitcode::encode); | ||
| 601 | - conn.execute( | ||
| 602 | - "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)", | ||
| 603 | - ( | ||
| 604 | - message_id, | ||
| 605 | - position, | ||
| 606 | - entry.id.as_str(), | ||
| 607 | - entry.user_id.as_str(), | ||
| 608 | - entry.username.as_str(), | ||
| 609 | - entry.avatar_id.as_deref(), | ||
| 610 | - entry.body.as_str(), | ||
| 611 | - poll, | ||
| 612 | - ), | ||
| 613 | - ) | ||
| 614 | - .await?; | ||
| 615 | - for attachment in &entry.attachments { | ||
| 616 | - attachment::copy( | ||
| 617 | - attachment, | ||
| 618 | - message_id, | ||
| 619 | - user_id, | ||
| 620 | - community_id, | ||
| 621 | - Some(position), | ||
| 622 | - directory, | ||
| 623 | - conn, | ||
| 624 | - ) | ||
| 625 | - .await?; | ||
| 626 | - } | ||
| 627 | - } | ||
| 628 | - | ||
| 629 | - Ok(()) | ||
| 630 | -} | ||
| 631 | - | ||
| 632 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 633 | -pub enum ForwardMode { | ||
| 634 | - Copy, | ||
| 635 | - Snippet, | ||
| 636 | -} | ||
| 637 | - | ||
| 638 | -pub async fn forward( | ||
| 639 | - user: &User, | ||
| 640 | - community_id: &str, | ||
| 641 | - sources: &[Message], | ||
| 642 | - mode: ForwardMode, | ||
| 643 | - directory: &Path, | ||
| 644 | - conn: &Connection, | ||
| 645 | -) -> Result<Vec<Message>, ServerError> { | ||
| 646 | - if mode == ForwardMode::Copy { | ||
| 647 | - let mut created = Vec::new(); | ||
| 648 | - for source in sources { | ||
| 649 | - let message_id = insert(&user.id, community_id, &source.body, None, conn).await?; | ||
| 650 | - for attachment in &source.attachments { | ||
| 651 | - attachment::copy( | ||
| 652 | - attachment, | ||
| 653 | - &message_id, | ||
| 654 | - &user.id, | ||
| 655 | - community_id, | ||
| 656 | - None, | ||
| 657 | - directory, | ||
| 658 | - conn, | ||
| 659 | - ) | ||
| 660 | - .await?; | ||
| 661 | - } | ||
| 662 | - if let Some(inner) = &source.snippet { | ||
| 663 | - write_snippet( | ||
| 664 | - &message_id, | ||
| 665 | - &user.id, | ||
| 666 | - community_id, | ||
| 667 | - inner.origin.as_deref(), | ||
| 668 | - &inner.messages, | ||
| 669 | - directory, | ||
| 670 | - conn, | ||
| 671 | - ) | ||
| 672 | - .await?; | ||
| 673 | - } | ||
| 674 | - created.push(read(&message_id, conn).await?); | ||
| 675 | - } | ||
| 676 | - | ||
| 677 | - return Ok(created); | ||
| 678 | - } | ||
| 679 | - | ||
| 680 | - let mut entries = Vec::new(); | ||
| 681 | - for source in sources { | ||
| 682 | - match &source.snippet { | ||
| 683 | - Some(inner) => entries.extend(inner.messages.iter().cloned()), | ||
| 684 | - None => entries.push(entry(source, conn).await?), | ||
| 685 | - } | ||
| 686 | - } | ||
| 687 | - if entries.len() > MAXIMUM_FORWARD_MESSAGES { | ||
| 688 | - return Err(CommonError::Invalid { | ||
| 689 | - field: Field::Forward, | ||
| 690 | - problem: Problem::Length { | ||
| 691 | - min: 1, | ||
| 692 | - max: MAXIMUM_FORWARD_MESSAGES as u64, | ||
| 693 | - actual: entries.len() as u64, | ||
| 694 | - }, | ||
| 695 | - } | ||
| 696 | - .into()); | ||
| 697 | - } | ||
| 698 | - | ||
| 699 | - let origin = origin(sources, conn).await?; | ||
| 700 | - let message_id = insert(&user.id, community_id, "", None, conn).await?; | ||
| 701 | - write_snippet( | ||
| 702 | - &message_id, | ||
| 703 | - &user.id, | ||
| 704 | - community_id, | ||
| 705 | - origin.as_deref(), | ||
| 706 | - &entries, | ||
| 707 | - directory, | ||
| 708 | - conn, | ||
| 709 | - ) | ||
| 710 | - .await?; | ||
| 711 | - | ||
| 712 | - Ok(vec![read(&message_id, conn).await?]) | ||
| 713 | -} | ||
| 714 | - | ||
| 715 | -#[cfg(test)] | ||
| 716 | -mod tests { | ||
| 717 | - use common::error::Error as CommonError; | ||
| 718 | - | ||
| 719 | - use crate::{community, database, error::ServerError, message, test, user}; | ||
| 720 | - | ||
| 721 | - #[tokio::test] | ||
| 722 | - async fn create() { | ||
| 723 | - let db = test::get_database().await; | ||
| 724 | - let conn = database::connect(&db).await.unwrap(); | ||
| 725 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 726 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 727 | - | ||
| 728 | - let message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 729 | - .await | ||
| 730 | - .unwrap(); | ||
| 731 | - | ||
| 732 | - assert_eq!(community.id, message.community_id); | ||
| 733 | - assert_eq!(user.id, message.user_id); | ||
| 734 | - assert_eq!("Tahinli", message.body); | ||
| 735 | - } | ||
| 736 | - | ||
| 737 | - #[tokio::test] | ||
| 738 | - async fn read() { | ||
| 739 | - let db = test::get_database().await; | ||
| 740 | - let conn = database::connect(&db).await.unwrap(); | ||
| 741 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 742 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 743 | - let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 744 | - .await | ||
| 745 | - .unwrap(); | ||
| 746 | - | ||
| 747 | - let searched_message = message::read(&created_message.id, &conn).await.unwrap(); | ||
| 748 | - | ||
| 749 | - assert_eq!(created_message, searched_message); | ||
| 750 | - } | ||
| 751 | - | ||
| 752 | - #[tokio::test] | ||
| 753 | - async fn read_page() { | ||
| 754 | - let db = test::get_database().await; | ||
| 755 | - let conn = database::connect(&db).await.unwrap(); | ||
| 756 | - let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 757 | - let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 758 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 759 | - | ||
| 760 | - let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 761 | - .await | ||
| 762 | - .unwrap(); | ||
| 763 | - let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 764 | - .await | ||
| 765 | - .unwrap(); | ||
| 766 | - let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 767 | - .await | ||
| 768 | - .unwrap(); | ||
| 769 | - | ||
| 770 | - let newest = message::read_page(&community.id, None, &conn) | ||
| 771 | - .await | ||
| 772 | - .unwrap(); | ||
| 773 | - let older = message::read_page(&community.id, Some(&message_3.id), &conn) | ||
| 774 | - .await | ||
| 775 | - .unwrap(); | ||
| 776 | - | ||
| 777 | - assert_eq!( | ||
| 778 | - vec![message_1.clone(), message_2.clone(), message_3], | ||
| 779 | - newest | ||
| 780 | - ); | ||
| 781 | - assert_eq!(vec![message_1, message_2], older); | ||
| 782 | - } | ||
| 783 | - | ||
| 784 | - #[tokio::test] | ||
| 785 | - async fn update() { | ||
| 786 | - let db = test::get_database().await; | ||
| 787 | - let conn = database::connect(&db).await.unwrap(); | ||
| 788 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 789 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 790 | - let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 791 | - .await | ||
| 792 | - .unwrap(); | ||
| 793 | - | ||
| 794 | - let updated_message = message::update(&created_message.id, "Not Tahinli", &conn) | ||
| 795 | - .await | ||
| 796 | - .unwrap(); | ||
| 797 | - let searched_message = message::read(&created_message.id, &conn).await.unwrap(); | ||
| 798 | - | ||
| 799 | - assert_eq!(created_message.user_id, updated_message.user_id); | ||
| 800 | - assert_eq!(created_message.community_id, updated_message.community_id); | ||
| 801 | - assert_eq!(updated_message, searched_message); | ||
| 802 | - assert_eq!("Not Tahinli", searched_message.body); | ||
| 803 | - } | ||
| 804 | - | ||
| 805 | - #[tokio::test] | ||
| 806 | - async fn update_on_missing_message() { | ||
| 807 | - let db = test::get_database().await; | ||
| 808 | - let conn = database::connect(&db).await.unwrap(); | ||
| 809 | - | ||
| 810 | - let updated_message = message::update("missing", "Tahinli", &conn).await; | ||
| 811 | - | ||
| 812 | - assert!(matches!( | ||
| 813 | - updated_message, | ||
| 814 | - Err(ServerError::Wire(CommonError::NotFound)) | ||
| 815 | - )); | ||
| 816 | - } | ||
| 817 | - | ||
| 818 | - #[tokio::test] | ||
| 819 | - async fn delete() { | ||
| 820 | - let db = test::get_database().await; | ||
| 821 | - let conn = database::connect(&db).await.unwrap(); | ||
| 822 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 823 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 824 | - let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn) | ||
| 825 | - .await | ||
| 826 | - .unwrap(); | ||
| 827 | - | ||
| 828 | - let deleted_message = message::delete(&created_message.id, &conn).await.unwrap(); | ||
| 829 | - | ||
| 830 | - assert_eq!(created_message, deleted_message); | ||
| 831 | - } | ||
| 832 | - | ||
| 833 | - #[tokio::test] | ||
| 834 | - async fn forward_two_as_snippet() { | ||
| 835 | - let db = test::get_database().await; | ||
| 836 | - let conn = database::connect(&db).await.unwrap(); | ||
| 837 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 838 | - let community = community::create("Tahinli", &conn).await.unwrap(); | ||
| 839 | - let first = message::create(&user.id, &community.id, "First", &[], None, &conn) | ||
| 840 | - .await | ||
| 841 | - .unwrap(); | ||
| 842 | - let second = message::create(&user.id, &community.id, "Second", &[], None, &conn) | ||
| 843 | - .await | ||
| 844 | - .unwrap(); | ||
| 845 | - | ||
| 846 | - let created = message::forward( | ||
| 847 | - &user, | ||
| 848 | - &community.id, | ||
| 849 | - &[first, second], | ||
| 850 | - message::ForwardMode::Snippet, | ||
| 851 | - &test::directory(), | ||
| 852 | - &conn, | ||
| 853 | - ) | ||
| 854 | - .await | ||
| 855 | - .unwrap(); | ||
| 856 | - | ||
| 857 | - assert_eq!(1, created.len()); | ||
| 858 | - assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len()); | ||
| 859 | - } | ||
| 860 | -} | ||
crates/server/src/network.rsmodified+83 -53
| @@ -2,29 +2,30 @@ use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; | |||
| 2 | 2 | ||
| 3 | use bytes::Bytes; | 3 | use bytes::Bytes; |
| 4 | use common::{ | 4 | use common::{ |
| 5 | - call::Request, | 5 | + call::{Login, Register, Request}, |
| 6 | frame::{self, DOWN_MAX, Sending, UP_MAX}, | 6 | frame::{self, DOWN_MAX, Sending, UP_MAX}, |
| 7 | model::User, | 7 | model::User, |
| 8 | open::Open, | 8 | open::Open, |
| 9 | session::{Hello, Welcome}, | 9 | session::{Hello, Welcome}, |
| 10 | transport::Close, | 10 | transport::Close, |
| 11 | + validate::validate_device, | ||
| 11 | }; | 12 | }; |
| 12 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; | 13 | use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; |
| 13 | use tokio::sync::mpsc; | 14 | use tokio::sync::mpsc; |
| 14 | use tracing::{info, warn}; | 15 | use tracing::{info, warn}; |
| 15 | 16 | ||
| 16 | use crate::{ | 17 | use crate::{ |
| 17 | - attachment, authentication, | 18 | + authentication, |
| 18 | call::{self, Cx}, | 19 | call::{self, Cx}, |
| 19 | - database::{self, DB}, | ||
| 20 | datagram, | 20 | datagram, |
| 21 | + db::{self, Db}, | ||
| 21 | error::ServerError, | 22 | error::ServerError, |
| 23 | + files, | ||
| 22 | hub::{Client, Hub, Presence, Signed}, | 24 | hub::{Client, Hub, Presence, Signed}, |
| 23 | - publish::publish, | 25 | + publish, |
| 24 | rate_limit::RateLimit, | 26 | rate_limit::RateLimit, |
| 25 | request, retention, | 27 | request, retention, |
| 26 | rooms::Rooms, | 28 | rooms::Rooms, |
| 27 | - server_ban, stats, user, | ||
| 28 | }; | 29 | }; |
| 29 | 30 | ||
| 30 | const HELLO_DEADLINE: Duration = Duration::from_secs(5); | 31 | const HELLO_DEADLINE: Duration = Duration::from_secs(5); |
| @@ -38,7 +39,7 @@ pub struct Services { | |||
| 38 | 39 | ||
| 39 | #[derive(Clone)] | 40 | #[derive(Clone)] |
| 40 | pub(crate) struct Shared { | 41 | pub(crate) struct Shared { |
| 41 | - pub(crate) db: DB, | 42 | + pub(crate) db: Db, |
| 42 | pub(crate) services: Services, | 43 | pub(crate) services: Services, |
| 43 | pub(crate) directory: PathBuf, | 44 | pub(crate) directory: PathBuf, |
| 44 | pub(crate) backups: PathBuf, | 45 | pub(crate) backups: PathBuf, |
| @@ -54,7 +55,7 @@ struct Pending { | |||
| 54 | pub async fn serve( | 55 | pub async fn serve( |
| 55 | server_address: &str, | 56 | server_address: &str, |
| 56 | server_config: quinn::ServerConfig, | 57 | server_config: quinn::ServerConfig, |
| 57 | - db: DB, | 58 | + db: Db, |
| 58 | directory: PathBuf, | 59 | directory: PathBuf, |
| 59 | backups: PathBuf, | 60 | backups: PathBuf, |
| 60 | ) -> Result<(), ServerError> { | 61 | ) -> Result<(), ServerError> { |
| @@ -85,8 +86,11 @@ async fn handle_connection(incoming: Incoming, shared: Shared) { | |||
| 85 | 86 | ||
| 86 | async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> { | 87 | async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), ServerError> { |
| 87 | let ip = incoming.remote_address().ip().to_string(); | 88 | let ip = incoming.remote_address().ip().to_string(); |
| 88 | - let conn = database::connect(&shared.db).await?; | 89 | + let banned = shared |
| 89 | - if server_ban::ip_banned(&ip, &conn).await? { | 90 | + .db |
| 91 | + .run(async |db| db::server_ban::ip_banned(&ip, db).await) | ||
| 92 | + .await?; | ||
| 93 | + if banned { | ||
| 90 | incoming | 94 | incoming |
| 91 | .accept()? | 95 | .accept()? |
| 92 | .await? | 96 | .await? |
| @@ -157,16 +161,19 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv | |||
| 157 | let presence = hub.remove(client.id); | 161 | let presence = hub.remove(client.id); |
| 158 | 162 | ||
| 159 | if let Some(me) = &client.me { | 163 | if let Some(me) = &client.me { |
| 160 | - let conn = database::connect(&shared.db).await?; | 164 | + publish::job(&shared, async |db| { |
| 161 | - let mut broadcasts = match shared.services.rooms.leave(client.id) { | 165 | + let mut broadcasts = match shared.services.rooms.leave(client.id) { |
| 162 | - Some(departure) => request::departed(departure, &conn).await?, | 166 | + Some(departure) => request::departed(departure, db).await?, |
| 163 | - None => Vec::new(), | 167 | + None => Vec::new(), |
| 164 | - }; | 168 | + }; |
| 165 | - if let Presence::Offline(user_id) = &presence { | 169 | + if let Presence::Offline(user_id) = presence { |
| 166 | - broadcasts.extend(request::presence_changed(hub, user_id, &conn).await?); | 170 | + broadcasts.extend(request::presence_changed(hub, user_id, db).await?); |
| 167 | - } | 171 | + } |
| 168 | - publish(&shared, broadcasts).await; | 172 | + db::session::seen(me.session_id, db).await?; |
| 169 | - authentication::seen(&me.user_id, &me.token, &conn).await?; | 173 | + |
| 174 | + Ok(broadcasts) | ||
| 175 | + }) | ||
| 176 | + .await?; | ||
| 170 | } | 177 | } |
| 171 | 178 | ||
| 172 | Ok(()) | 179 | Ok(()) |
| @@ -211,21 +218,28 @@ async fn admit( | |||
| 211 | let Some(token) = hello.token else { | 218 | let Some(token) = hello.token else { |
| 212 | return Ok((None, None)); | 219 | return Ok((None, None)); |
| 213 | }; | 220 | }; |
| 214 | - let conn = database::connect(&shared.db).await?; | 221 | + let ip = connection.remote_address().ip().to_string(); |
| 215 | - let user = authentication::resume(&token, &conn).await?; | 222 | + let (session_id, user) = shared |
| 216 | - stats::mark_active(&user.id, &conn).await?; | 223 | + .db |
| 217 | - user::set_last_ip( | 224 | + .run(async |db| { |
| 218 | - &user.id, | 225 | + let (session_id, user) = authentication::resume(&token, db).await?; |
| 219 | - &connection.remote_address().ip().to_string(), | 226 | + db::stats::mark_active(user.id, db).await?; |
| 220 | - &conn, | 227 | + db::user::set_last_ip(user.id, &ip, db).await?; |
| 221 | - ) | 228 | + let device = async { |
| 222 | - .await?; | 229 | + validate_device(&hello.device)?; |
| 223 | - if let Err(error) = authentication::set_device(&token, &hello.device, &conn).await { | 230 | + db::session::set_device(session_id, &hello.device, db).await |
| 224 | - warn!("device: {error}"); | 231 | + } |
| 225 | - } | 232 | + .await; |
| 233 | + if let Err(error) = device { | ||
| 234 | + warn!("device: {error}"); | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + Ok((session_id, user)) | ||
| 238 | + }) | ||
| 239 | + .await?; | ||
| 226 | let me = Signed { | 240 | let me = Signed { |
| 227 | - user_id: user.id.clone(), | 241 | + user_id: user.id, |
| 228 | - token, | 242 | + session_id, |
| 229 | }; | 243 | }; |
| 230 | 244 | ||
| 231 | Ok((Some(me), Some(user))) | 245 | Ok((Some(me), Some(user))) |
| @@ -238,10 +252,11 @@ async fn welcome( | |||
| 238 | shared: &Shared, | 252 | shared: &Shared, |
| 239 | ) -> Result<bool, ServerError> { | 253 | ) -> Result<bool, ServerError> { |
| 240 | let checked = match &client.me { | 254 | let checked = match &client.me { |
| 241 | - Some(me) => { | 255 | + Some(me) => shared |
| 242 | - let conn = database::connect(&shared.db).await?; | 256 | + .db |
| 243 | - authentication::resume(&me.token, &conn).await.map(Some) | 257 | + .run(async |db| authentication::recheck(me.session_id, db).await) |
| 244 | - } | 258 | + .await |
| 259 | + .map(Some), | ||
| 245 | None => Ok(user.clone()), | 260 | None => Ok(user.clone()), |
| 246 | }; | 261 | }; |
| 247 | let accepted = checked.is_ok(); | 262 | let accepted = checked.is_ok(); |
| @@ -266,7 +281,7 @@ async fn route( | |||
| 266 | Open::Call(request) => answer(client, request, send_stream, shared).await, | 281 | Open::Call(request) => answer(client, request, send_stream, shared).await, |
| 267 | Open::Upload(upload) => { | 282 | Open::Upload(upload) => { |
| 268 | let user = signed_user(&client, &shared).await?; | 283 | let user = signed_user(&client, &shared).await?; |
| 269 | - attachment::upload( | 284 | + files::upload( |
| 270 | user.as_ref(), | 285 | user.as_ref(), |
| 271 | upload, | 286 | upload, |
| 272 | receive_stream, | 287 | receive_stream, |
| @@ -278,7 +293,7 @@ async fn route( | |||
| 278 | } | 293 | } |
| 279 | Open::Fetch(blob) => { | 294 | Open::Fetch(blob) => { |
| 280 | let user = signed_user(&client, &shared).await?; | 295 | let user = signed_user(&client, &shared).await?; |
| 281 | - attachment::fetch( | 296 | + files::fetch( |
| 282 | user.as_ref(), | 297 | user.as_ref(), |
| 283 | blob, | 298 | blob, |
| 284 | send_stream, | 299 | send_stream, |
| @@ -292,12 +307,15 @@ async fn route( | |||
| 292 | } | 307 | } |
| 293 | 308 | ||
| 294 | async fn signed_user(client: &Client, shared: &Shared) -> Result<Option<User>, ServerError> { | 309 | async fn signed_user(client: &Client, shared: &Shared) -> Result<Option<User>, ServerError> { |
| 295 | - let Some(me) = &client.me else { | 310 | + if client.me.is_none() { |
| 296 | return Ok(None); | 311 | return Ok(None); |
| 297 | - }; | 312 | + } |
| 298 | - let conn = database::connect(&shared.db).await?; | 313 | + let user = shared |
| 314 | + .db | ||
| 315 | + .run(async |db| request::authenticated(client, db).await) | ||
| 316 | + .await?; | ||
| 299 | 317 | ||
| 300 | - Ok(Some(user::read(&me.user_id, &conn).await?)) | 318 | + Ok(Some(user)) |
| 301 | } | 319 | } |
| 302 | 320 | ||
| 303 | async fn answer( | 321 | async fn answer( |
| @@ -306,9 +324,21 @@ async fn answer( | |||
| 306 | mut send_stream: Sending, | 324 | mut send_stream: Sending, |
| 307 | shared: Shared, | 325 | shared: Shared, |
| 308 | ) -> Result<(), ServerError> { | 326 | ) -> Result<(), ServerError> { |
| 309 | - let db = database::connect(&shared.db).await?; | 327 | + let reply = match request { |
| 310 | - let mut cx = Cx::new(&client, &shared, db); | 328 | + Request::Register(call) => { |
| 311 | - let reply = call::dispatch(request, &mut cx).await; | 329 | + call::encode::<Register>(authentication::register(call, &client, &shared).await) |
| 330 | + } | ||
| 331 | + Request::Login(call) => { | ||
| 332 | + call::encode::<Login>(authentication::login(call, &client, &shared).await) | ||
| 333 | + } | ||
| 334 | + request => { | ||
| 335 | + let db = shared.db.lock().await?; | ||
| 336 | + let mut cx = Cx::new(&client, &shared, &db); | ||
| 337 | + let reply = call::dispatch(request, &mut cx).await; | ||
| 338 | + publish::publish(&shared, &db, std::mem::take(&mut cx.out)).await; | ||
| 339 | + reply | ||
| 340 | + } | ||
| 341 | + }; | ||
| 312 | 342 | ||
| 313 | send_stream.get().write_all(&reply).await?; | 343 | send_stream.get().write_all(&reply).await?; |
| 314 | send_stream.finish()?; | 344 | send_stream.finish()?; |
| @@ -327,13 +357,13 @@ async fn publish_presence(shared: &Shared, presence: Presence) { | |||
| 327 | let (Presence::Online(user_id) | Presence::Offline(user_id)) = presence else { | 357 | let (Presence::Online(user_id) | Presence::Offline(user_id)) = presence else { |
| 328 | return; | 358 | return; |
| 329 | }; | 359 | }; |
| 330 | - let broadcasts = match database::connect(&shared.db).await { | 360 | + let hub = &shared.services.hub; |
| 331 | - Ok(conn) => request::presence_changed(&shared.services.hub, &user_id, &conn).await, | 361 | + if let Err(error) = publish::job(shared, async |db| { |
| 332 | - Err(error) => Err(error), | 362 | + request::presence_changed(hub, user_id, db).await |
| 333 | - }; | 363 | + }) |
| 334 | - match broadcasts { | 364 | + .await |
| 335 | - Ok(broadcasts) => publish(shared, broadcasts).await, | 365 | + { |
| 336 | - Err(error) => warn!("presence: {error}"), | 366 | + warn!("presence: {error}"); |
| 337 | } | 367 | } |
| 338 | } | 368 | } |
| 339 | 369 | ||
crates/server/src/notes.rsdeleted+0 -36
| @@ -1,36 +0,0 @@ | |||
| 1 | -use common::model::{Community, Rank}; | ||
| 2 | -use turso::Connection; | ||
| 3 | - | ||
| 4 | -use crate::{community, error::ServerError, user_community}; | ||
| 5 | - | ||
| 6 | -async fn find(user_id: &str, conn: &Connection) -> Result<Option<String>, ServerError> { | ||
| 7 | - let mut rows = conn | ||
| 8 | - .query( | ||
| 9 | - "SELECT community_id FROM notes WHERE user_id = ?1", | ||
| 10 | - (user_id,), | ||
| 11 | - ) | ||
| 12 | - .await?; | ||
| 13 | - | ||
| 14 | - Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) | ||
| 15 | -} | ||
| 16 | - | ||
| 17 | -pub async fn open(me: &str, conn: &mut Connection) -> Result<Community, ServerError> { | ||
| 18 | - let tx = conn.transaction().await?; | ||
| 19 | - let community_id = match find(me, &tx).await? { | ||
| 20 | - Some(community_id) => community_id, | ||
| 21 | - None => { | ||
| 22 | - let community_id = community::create_fixed(community::Kind::Notes, &tx).await?; | ||
| 23 | - user_community::join(me, &community_id, Rank::Owner, &tx).await?; | ||
| 24 | - tx.execute( | ||
| 25 | - "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)", | ||
| 26 | - (me, community_id.as_str()), | ||
| 27 | - ) | ||
| 28 | - .await?; | ||
| 29 | - community_id | ||
| 30 | - } | ||
| 31 | - }; | ||
| 32 | - let community = community::read(&community_id, me, &tx).await?; | ||
| 33 | - tx.commit().await?; | ||
| 34 | - | ||
| 35 | - Ok(community) | ||
| 36 | -} | ||
crates/server/src/overview.rsdeleted+0 -36
| @@ -1,36 +0,0 @@ | |||
| 1 | -use common::model::{Overview, Role}; | ||
| 2 | -use turso::Connection; | ||
| 3 | - | ||
| 4 | -use crate::{community::Kind, error::ServerError, hub::Hub, rooms::Rooms}; | ||
| 5 | - | ||
| 6 | -pub async fn read(hub: &Hub, rooms: &Rooms, conn: &Connection) -> Result<Overview, ServerError> { | ||
| 7 | - let mut rows = conn | ||
| 8 | - .query( | ||
| 9 | - "SELECT | ||
| 10 | - (SELECT COUNT(*) FROM user), | ||
| 11 | - (SELECT COUNT(*) FROM user WHERE role = ?1), | ||
| 12 | - (SELECT COUNT(*) FROM community WHERE kind = ?2), | ||
| 13 | - (SELECT COALESCE(SUM(size), 0) FROM attachment) | ||
| 14 | - + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar) | ||
| 15 | - + (SELECT COALESCE(SUM(length(data)), 0) FROM community_avatar)", | ||
| 16 | - (Role::Builder.as_str(), Kind::Group.as_str()), | ||
| 17 | - ) | ||
| 18 | - .await?; | ||
| 19 | - let row = rows | ||
| 20 | - .next() | ||
| 21 | - .await? | ||
| 22 | - .ok_or(turso::Error::QueryReturnedNoRows)?; | ||
| 23 | - let count = |index: usize| -> Result<u64, ServerError> { | ||
| 24 | - let value: i64 = row.get(index)?; | ||
| 25 | - Ok(value as u64) | ||
| 26 | - }; | ||
| 27 | - | ||
| 28 | - Ok(Overview { | ||
| 29 | - users: count(0)?, | ||
| 30 | - builders: count(1)?, | ||
| 31 | - communities: count(2)?, | ||
| 32 | - online: hub.online() as u64, | ||
| 33 | - voice: rooms.count() as u64, | ||
| 34 | - storage_bytes: count(3)?, | ||
| 35 | - }) | ||
| 36 | -} | ||
crates/server/src/publish.rsmodified+40 -31
| @@ -4,20 +4,23 @@ use bytes::Bytes; | |||
| 4 | use common::{ | 4 | use common::{ |
| 5 | event::{Down, Event, Media}, | 5 | event::{Down, Event, Media}, |
| 6 | frame::{self, DOWN_MAX}, | 6 | frame::{self, DOWN_MAX}, |
| 7 | + model::Id, | ||
| 7 | }; | 8 | }; |
| 8 | use tracing::warn; | 9 | use tracing::warn; |
| 9 | 10 | ||
| 10 | use crate::{ | 11 | use crate::{ |
| 11 | - community, database, error::ServerError, friend, hub::ConnId, network::Shared, user, | 12 | + db::{self, Connection}, |
| 12 | - user_community, | 13 | + error::ServerError, |
| 14 | + hub::ConnId, | ||
| 15 | + network::Shared, | ||
| 13 | }; | 16 | }; |
| 14 | 17 | ||
| 15 | pub enum To { | 18 | pub enum To { |
| 16 | - User(String), | 19 | + User(Id), |
| 17 | - Users(Vec<String>), | 20 | + Users(Vec<Id>), |
| 18 | - Community(String), | 21 | + Community(Id), |
| 19 | - CommunityExcept(String, String), | 22 | + CommunityExcept(Id, Id), |
| 20 | - Related(String), | 23 | + Related(Id), |
| 21 | Builders, | 24 | Builders, |
| 22 | Everyone, | 25 | Everyone, |
| 23 | Conn(ConnId), | 26 | Conn(ConnId), |
| @@ -44,9 +47,9 @@ impl Broadcast { | |||
| 44 | } | 47 | } |
| 45 | } | 48 | } |
| 46 | 49 | ||
| 47 | -pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) { | 50 | +pub(crate) async fn publish(shared: &Shared, db: &Connection, broadcasts: Vec<Broadcast>) { |
| 48 | for broadcast in broadcasts { | 51 | for broadcast in broadcasts { |
| 49 | - let ids = match resolve(shared, &broadcast.to).await { | 52 | + let ids = match resolve(shared, &broadcast.to, db).await { |
| 50 | Ok(ids) => ids, | 53 | Ok(ids) => ids, |
| 51 | Err(error) => { | 54 | Err(error) => { |
| 52 | warn!("resolve: {error}"); | 55 | warn!("resolve: {error}"); |
| @@ -63,52 +66,58 @@ pub(crate) async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) { | |||
| 63 | } | 66 | } |
| 64 | } | 67 | } |
| 65 | 68 | ||
| 66 | -async fn resolve(shared: &Shared, to: &To) -> Result<Vec<ConnId>, ServerError> { | 69 | +pub(crate) async fn job( |
| 70 | + shared: &Shared, | ||
| 71 | + work: impl AsyncFnOnce(&Connection) -> Result<Vec<Broadcast>, ServerError>, | ||
| 72 | +) -> Result<(), ServerError> { | ||
| 73 | + let db = shared.db.lock().await?; | ||
| 74 | + let out = db::atomic(&db, work(&db)).await?; | ||
| 75 | + publish(shared, &db, out).await; | ||
| 76 | + | ||
| 77 | + Ok(()) | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +async fn resolve(shared: &Shared, to: &To, db: &Connection) -> Result<Vec<ConnId>, ServerError> { | ||
| 67 | let hub = &shared.services.hub; | 81 | let hub = &shared.services.hub; |
| 68 | let ids = match to { | 82 | let ids = match to { |
| 69 | To::Conn(id) => vec![*id], | 83 | To::Conn(id) => vec![*id], |
| 70 | To::Everyone => hub.all(), | 84 | To::Everyone => hub.all(), |
| 71 | To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), | 85 | To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), |
| 72 | To::Users(user_ids) => hub.conns_of(user_ids), | 86 | To::Users(user_ids) => hub.conns_of(user_ids), |
| 73 | - To::Builders => { | 87 | + To::Builders => hub.conns_of(&db::user::builder_ids(db).await?), |
| 74 | - let conn = database::connect(&shared.db).await?; | 88 | + To::Community(community_id) => community_conns(shared, *community_id, db).await?, |
| 75 | - hub.conns_of(&user::builder_ids(&conn).await?) | ||
| 76 | - } | ||
| 77 | - To::Community(community_id) => community_conns(shared, community_id).await?, | ||
| 78 | To::CommunityExcept(community_id, user_id) => { | 89 | To::CommunityExcept(community_id, user_id) => { |
| 79 | - let mut ids = community_conns(shared, community_id).await?; | 90 | + let mut ids = community_conns(shared, *community_id, db).await?; |
| 80 | let own = hub.conns_of(std::slice::from_ref(user_id)); | 91 | let own = hub.conns_of(std::slice::from_ref(user_id)); |
| 81 | ids.retain(|id| !own.contains(id)); | 92 | ids.retain(|id| !own.contains(id)); |
| 82 | ids | 93 | ids |
| 83 | } | 94 | } |
| 84 | - To::Related(user_id) => { | 95 | + To::Related(user_id) => hub.conns_of(&related_user_ids(*user_id, db).await?), |
| 85 | - let conn = database::connect(&shared.db).await?; | ||
| 86 | - hub.conns_of(&related_user_ids(user_id, &conn).await?) | ||
| 87 | - } | ||
| 88 | }; | 96 | }; |
| 89 | 97 | ||
| 90 | Ok(ids) | 98 | Ok(ids) |
| 91 | } | 99 | } |
| 92 | 100 | ||
| 93 | -async fn community_conns(shared: &Shared, community_id: &str) -> Result<Vec<ConnId>, ServerError> { | 101 | +async fn community_conns( |
| 102 | + shared: &Shared, | ||
| 103 | + community_id: Id, | ||
| 104 | + db: &Connection, | ||
| 105 | +) -> Result<Vec<ConnId>, ServerError> { | ||
| 94 | let hub = &shared.services.hub; | 106 | let hub = &shared.services.hub; |
| 95 | - let conn = database::connect(&shared.db).await?; | 107 | + let mut ids = hub.conns_of(&db::member::member_ids(community_id, db).await?); |
| 96 | - let mut ids = hub.conns_of(&user_community::member_ids(community_id, &conn).await?); | ||
| 97 | ids.extend(hub.watchers(community_id)); | 108 | ids.extend(hub.watchers(community_id)); |
| 98 | ids.sort_unstable(); | 109 | ids.sort_unstable(); |
| 99 | ids.dedup(); | 110 | ids.dedup(); |
| 111 | + | ||
| 100 | Ok(ids) | 112 | Ok(ids) |
| 101 | } | 113 | } |
| 102 | 114 | ||
| 103 | -pub(crate) async fn related_user_ids( | 115 | +pub(crate) async fn related_user_ids(user_id: Id, db: &Connection) -> Result<Vec<Id>, ServerError> { |
| 104 | - user_id: &str, | 116 | + let mut user_ids = BTreeSet::from([user_id]); |
| 105 | - conn: &turso::Connection, | 117 | + for community in db::community::communities_of(user_id, db).await? { |
| 106 | -) -> Result<Vec<String>, ServerError> { | 118 | + user_ids.extend(db::member::member_ids(community.id, db).await?); |
| 107 | - let mut user_ids = BTreeSet::from([user_id.to_string()]); | ||
| 108 | - for community in community::communities_of(user_id, conn).await? { | ||
| 109 | - user_ids.extend(user_community::member_ids(&community.id, conn).await?); | ||
| 110 | } | 119 | } |
| 111 | - for friend in friend::state(user_id, conn).await?.friends { | 120 | + for friend in db::friend::state(user_id, db).await?.friends { |
| 112 | user_ids.insert(friend.id); | 121 | user_ids.insert(friend.id); |
| 113 | } | 122 | } |
| 114 | 123 | ||
crates/server/src/report.rsdeleted+0 -92
| @@ -1,92 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - constant::LOG_PAGE_LIMIT, | ||
| 3 | - error::Error as CommonError, | ||
| 4 | - model::{Report, ReportStatus}, | ||
| 5 | -}; | ||
| 6 | -use turso::Connection; | ||
| 7 | - | ||
| 8 | -use crate::{ | ||
| 9 | - database::{self, new_id}, | ||
| 10 | - error::ServerError, | ||
| 11 | - user, | ||
| 12 | -}; | ||
| 13 | - | ||
| 14 | -pub async fn is_open( | ||
| 15 | - reporter_id: &str, | ||
| 16 | - target_id: &str, | ||
| 17 | - message_id: Option<&str>, | ||
| 18 | - conn: &Connection, | ||
| 19 | -) -> Result<bool, ServerError> { | ||
| 20 | - database::exists( | ||
| 21 | - conn, | ||
| 22 | - "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", | ||
| 23 | - (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), | ||
| 24 | - ) | ||
| 25 | - .await | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | -pub async fn insert( | ||
| 29 | - reporter_id: &str, | ||
| 30 | - target_id: &str, | ||
| 31 | - message_id: Option<&str>, | ||
| 32 | - community_id: Option<&str>, | ||
| 33 | - body: Option<&str>, | ||
| 34 | - reason: &str, | ||
| 35 | - conn: &Connection, | ||
| 36 | -) -> Result<(), ServerError> { | ||
| 37 | - conn.execute( | ||
| 38 | - "INSERT INTO report (id, reporter_id, target_id, message_id, community_id, body, reason) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | ||
| 39 | - (new_id(), reporter_id, target_id, message_id, community_id, body, reason), | ||
| 40 | - ) | ||
| 41 | - .await?; | ||
| 42 | - | ||
| 43 | - Ok(()) | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -pub async fn list( | ||
| 47 | - status: Option<ReportStatus>, | ||
| 48 | - conn: &Connection, | ||
| 49 | -) -> Result<Vec<Report>, ServerError> { | ||
| 50 | - let mut rows = conn | ||
| 51 | - .query( | ||
| 52 | - &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")), | ||
| 53 | - (status.map(ReportStatus::as_str),), | ||
| 54 | - ) | ||
| 55 | - .await?; | ||
| 56 | - | ||
| 57 | - let mut reports = Vec::new(); | ||
| 58 | - while let Some(row) = rows.next().await? { | ||
| 59 | - let text: String = row.get(16)?; | ||
| 60 | - reports.push(Report { | ||
| 61 | - id: row.get(0)?, | ||
| 62 | - reporter: user::from_row_at(&row, 1)?, | ||
| 63 | - target: user::from_row_at(&row, 6)?, | ||
| 64 | - community: row.get(11)?, | ||
| 65 | - message_id: row.get(12)?, | ||
| 66 | - community_id: row.get(13)?, | ||
| 67 | - body: row.get(14)?, | ||
| 68 | - reason: row.get(15)?, | ||
| 69 | - status: ReportStatus::parse(&text).ok_or(CommonError::Server)?, | ||
| 70 | - handled_by: user::from_row_at(&row, 17)?, | ||
| 71 | - }); | ||
| 72 | - } | ||
| 73 | - | ||
| 74 | - Ok(reports) | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -pub async fn handle( | ||
| 78 | - report_id: &str, | ||
| 79 | - status: ReportStatus, | ||
| 80 | - handled_by: &str, | ||
| 81 | - conn: &Connection, | ||
| 82 | -) -> Result<Option<String>, ServerError> { | ||
| 83 | - let mut rows = conn | ||
| 84 | - .query( | ||
| 85 | - "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", | ||
| 86 | - (report_id, status.as_str(), handled_by, ReportStatus::Open.as_str()), | ||
| 87 | - ) | ||
| 88 | - .await?; | ||
| 89 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 90 | - | ||
| 91 | - Ok(row.get(0)?) | ||
| 92 | -} | ||
crates/server/src/request.rsmodified+152 -167
| @@ -1,29 +1,29 @@ | |||
| 1 | +use std::collections::BTreeMap; | ||
| 2 | + | ||
| 1 | use common::{ | 3 | use common::{ |
| 2 | error::Error as CommonError, | 4 | error::Error as CommonError, |
| 3 | event::Event, | 5 | event::Event, |
| 4 | - model::{AdminAction, CallLog, Message, Presence, Rank, User}, | 6 | + model::{AdminAction, CallLog, Id, Message, Presence, Rank, User}, |
| 5 | permission, | 7 | permission, |
| 6 | - share::Kind, | 8 | + share::Kind as ShareKind, |
| 7 | }; | 9 | }; |
| 8 | -use turso::Connection; | ||
| 9 | 10 | ||
| 10 | use crate::{ | 11 | use crate::{ |
| 11 | - admin_log, community, | 12 | + call::Cx, |
| 12 | - error::ServerError, | 13 | + db::{self, Connection, community::Kind}, |
| 14 | + error::{ServerError, ensure}, | ||
| 13 | hub::{Client, Hub}, | 15 | hub::{Client, Hub}, |
| 14 | - message, | ||
| 15 | publish::{Broadcast, To}, | 16 | publish::{Broadcast, To}, |
| 16 | rate_limit::RateLimit, | 17 | rate_limit::RateLimit, |
| 17 | rooms::{Departure, Rooms}, | 18 | rooms::{Departure, Rooms}, |
| 18 | - server_settings, user, user_community, | ||
| 19 | }; | 19 | }; |
| 20 | 20 | ||
| 21 | pub(crate) async fn limit_logins( | 21 | pub(crate) async fn limit_logins( |
| 22 | rate_limit: &RateLimit, | 22 | rate_limit: &RateLimit, |
| 23 | connection: Option<&quinn::Connection>, | 23 | connection: Option<&quinn::Connection>, |
| 24 | - conn: &Connection, | 24 | + db: &Connection, |
| 25 | ) -> Result<(), ServerError> { | 25 | ) -> Result<(), ServerError> { |
| 26 | - let limit = server_settings::read(conn).await?.logins_per_minute; | 26 | + let limit = db::settings::read(db).await?.logins_per_minute; |
| 27 | 27 | ||
| 28 | let ip = connection | 28 | let ip = connection |
| 29 | .map(|connection| connection.remote_address().ip().to_string()) | 29 | .map(|connection| connection.remote_address().ip().to_string()) |
| @@ -34,72 +34,65 @@ pub(crate) async fn limit_logins( | |||
| 34 | 34 | ||
| 35 | pub(crate) async fn effective_presence( | 35 | pub(crate) async fn effective_presence( |
| 36 | hub: &Hub, | 36 | hub: &Hub, |
| 37 | - user_id: &str, | 37 | + user_id: Id, |
| 38 | - conn: &Connection, | 38 | + db: &Connection, |
| 39 | ) -> Result<Presence, ServerError> { | 39 | ) -> Result<Presence, ServerError> { |
| 40 | if !hub.is_online(user_id) { | 40 | if !hub.is_online(user_id) { |
| 41 | return Ok(Presence::Offline); | 41 | return Ok(Presence::Offline); |
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | - user::presence(user_id, conn).await | 44 | + db::user::presence(user_id, db).await |
| 45 | } | 45 | } |
| 46 | 46 | ||
| 47 | pub async fn presence_changed( | 47 | pub async fn presence_changed( |
| 48 | hub: &Hub, | 48 | hub: &Hub, |
| 49 | - user_id: &str, | 49 | + user_id: Id, |
| 50 | - conn: &Connection, | 50 | + db: &Connection, |
| 51 | ) -> Result<Vec<Broadcast>, ServerError> { | 51 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 52 | - let presence = effective_presence(hub, user_id, conn).await?; | 52 | + let presence = effective_presence(hub, user_id, db).await?; |
| 53 | - | 53 | + let event = Event::PresenceChanged { user_id, presence }; |
| 54 | - let event = Event::PresenceChanged { | ||
| 55 | - user_id: user_id.to_string(), | ||
| 56 | - presence, | ||
| 57 | - }; | ||
| 58 | 54 | ||
| 59 | - Ok(vec![Broadcast::new( | 55 | + Ok(vec![Broadcast::new(To::Related(user_id), event)]) |
| 60 | - To::Related(user_id.to_string()), | ||
| 61 | - event, | ||
| 62 | - )]) | ||
| 63 | } | 56 | } |
| 64 | 57 | ||
| 65 | pub(crate) async fn leave_user_voice( | 58 | pub(crate) async fn leave_user_voice( |
| 66 | rooms: &Rooms, | 59 | rooms: &Rooms, |
| 67 | - user_id: &str, | 60 | + user_id: Id, |
| 68 | - conn: &Connection, | 61 | + db: &Connection, |
| 69 | ) -> Result<Vec<Broadcast>, ServerError> { | 62 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 70 | match rooms.leave_user(user_id) { | 63 | match rooms.leave_user(user_id) { |
| 71 | - Some(departure) => departed(departure, conn).await, | 64 | + Some(departure) => departed(departure, db).await, |
| 72 | None => Ok(Vec::new()), | 65 | None => Ok(Vec::new()), |
| 73 | } | 66 | } |
| 74 | } | 67 | } |
| 75 | 68 | ||
| 76 | pub(crate) async fn leave_room_voice( | 69 | pub(crate) async fn leave_room_voice( |
| 77 | rooms: &Rooms, | 70 | rooms: &Rooms, |
| 78 | - community_id: &str, | 71 | + community_id: Id, |
| 79 | - user_id: &str, | 72 | + user_id: Id, |
| 80 | - conn: &Connection, | 73 | + db: &Connection, |
| 81 | ) -> Result<Vec<Broadcast>, ServerError> { | 74 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 82 | match rooms.leave_room(community_id, user_id) { | 75 | match rooms.leave_room(community_id, user_id) { |
| 83 | - Some(departure) => departed(departure, conn).await, | 76 | + Some(departure) => departed(departure, db).await, |
| 84 | None => Ok(Vec::new()), | 77 | None => Ok(Vec::new()), |
| 85 | } | 78 | } |
| 86 | } | 79 | } |
| 87 | 80 | ||
| 88 | pub(crate) async fn voice_muted( | 81 | pub(crate) async fn voice_muted( |
| 89 | - community_id: Option<String>, | 82 | + community_id: Option<Id>, |
| 90 | - user_id: &str, | 83 | + user_id: Id, |
| 91 | muted: bool, | 84 | muted: bool, |
| 92 | - conn: &Connection, | 85 | + db: &Connection, |
| 93 | ) -> Result<Broadcast, ServerError> { | 86 | ) -> Result<Broadcast, ServerError> { |
| 94 | - let mut user_ids = vec![user_id.to_string()]; | 87 | + let mut user_ids = vec![user_id]; |
| 95 | - if let Some(community_id) = &community_id | 88 | + if let Some(community_id) = community_id |
| 96 | - && !user::is_ghost(user_id, conn).await? | 89 | + && !db::user::is_ghost(user_id, db).await? |
| 97 | { | 90 | { |
| 98 | - user_ids.extend(user_community::member_ids(community_id, conn).await?); | 91 | + user_ids.extend(db::member::member_ids(community_id, db).await?); |
| 99 | } | 92 | } |
| 100 | let event = Event::VoiceMuted { | 93 | let event = Event::VoiceMuted { |
| 101 | community_id, | 94 | community_id, |
| 102 | - user_id: user_id.to_string(), | 95 | + user_id, |
| 103 | muted, | 96 | muted, |
| 104 | }; | 97 | }; |
| 105 | 98 | ||
| @@ -108,37 +101,45 @@ pub(crate) async fn voice_muted( | |||
| 108 | 101 | ||
| 109 | pub(crate) async fn voice_closed( | 102 | pub(crate) async fn voice_closed( |
| 110 | rooms: &Rooms, | 103 | rooms: &Rooms, |
| 111 | - community_id: &str, | 104 | + community_id: Id, |
| 112 | - conn: &Connection, | 105 | + db: &Connection, |
| 113 | ) -> Result<Vec<Broadcast>, ServerError> { | 106 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 114 | let mut broadcasts = Vec::new(); | 107 | let mut broadcasts = Vec::new(); |
| 115 | for departure in rooms.close_room(community_id) { | 108 | for departure in rooms.close_room(community_id) { |
| 116 | - broadcasts.extend(departed(departure, conn).await?); | 109 | + broadcasts.extend(departed(departure, db).await?); |
| 117 | } | 110 | } |
| 118 | 111 | ||
| 119 | Ok(broadcasts) | 112 | Ok(broadcasts) |
| 120 | } | 113 | } |
| 121 | 114 | ||
| 115 | +pub(crate) async fn delete_community(community_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { | ||
| 116 | + let closed = voice_closed(&cx.sh.services.rooms, community_id, cx.db).await?; | ||
| 117 | + cx.out.extend(closed); | ||
| 118 | + db::community::delete(community_id, cx.db).await?; | ||
| 119 | + | ||
| 120 | + Ok(()) | ||
| 121 | +} | ||
| 122 | + | ||
| 122 | pub(crate) async fn call_ended( | 123 | pub(crate) async fn call_ended( |
| 123 | - community_id: &str, | 124 | + community_id: Id, |
| 124 | - user_id: &str, | 125 | + user_id: Id, |
| 125 | call: Option<CallLog>, | 126 | call: Option<CallLog>, |
| 126 | - conn: &Connection, | 127 | + db: &Connection, |
| 127 | ) -> Result<Vec<Broadcast>, ServerError> { | 128 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 128 | let Some(call) = call else { | 129 | let Some(call) = call else { |
| 129 | return Ok(Vec::new()); | 130 | return Ok(Vec::new()); |
| 130 | }; | 131 | }; |
| 131 | - if !community::is_direct(community_id, conn).await? { | 132 | + if db::community::kind_of(community_id, db).await? != Some(Kind::Direct) { |
| 132 | return Ok(Vec::new()); | 133 | return Ok(Vec::new()); |
| 133 | } | 134 | } |
| 134 | - let created = message::create_call_log(community_id, user_id, call, conn).await?; | 135 | + let created = db::message::create_call_log(community_id, user_id, call, db).await?; |
| 135 | 136 | ||
| 136 | Ok(vec![message_event(&created, Event::MessageCreated)]) | 137 | Ok(vec![message_event(&created, Event::MessageCreated)]) |
| 137 | } | 138 | } |
| 138 | 139 | ||
| 139 | pub async fn departed( | 140 | pub async fn departed( |
| 140 | mut departure: Departure, | 141 | mut departure: Departure, |
| 141 | - conn: &Connection, | 142 | + db: &Connection, |
| 142 | ) -> Result<Vec<Broadcast>, ServerError> { | 143 | ) -> Result<Vec<Broadcast>, ServerError> { |
| 143 | let mut broadcasts = shares_ended(&mut departure); | 144 | let mut broadcasts = shares_ended(&mut departure); |
| 144 | if departure.quiet { | 145 | if departure.quiet { |
| @@ -152,63 +153,76 @@ pub async fn departed( | |||
| 152 | .. | 153 | .. |
| 153 | } = departure; | 154 | } = departure; |
| 154 | let Some(seconds) = ghost_seconds else { | 155 | let Some(seconds) = ghost_seconds else { |
| 155 | - broadcasts.extend(call_ended(&community_id, &user_id, call_log, conn).await?); | 156 | + broadcasts.extend(call_ended(community_id, user_id, call_log, db).await?); |
| 156 | let event = Event::VoiceLeft { | 157 | let event = Event::VoiceLeft { |
| 157 | - community_id: community_id.clone(), | 158 | + community_id, |
| 158 | user_id, | 159 | user_id, |
| 159 | }; | 160 | }; |
| 160 | broadcasts.push(Broadcast::new(To::Community(community_id), event)); | 161 | broadcasts.push(Broadcast::new(To::Community(community_id), event)); |
| 161 | 162 | ||
| 162 | return Ok(broadcasts); | 163 | return Ok(broadcasts); |
| 163 | }; | 164 | }; |
| 164 | - record_ghost_voice(&user_id, &community_id, seconds, conn).await?; | 165 | + record_ghost_voice(user_id, community_id, seconds, db).await?; |
| 165 | 166 | ||
| 166 | Ok(broadcasts) | 167 | Ok(broadcasts) |
| 167 | } | 168 | } |
| 168 | 169 | ||
| 169 | -pub(crate) fn share_ended(community_id: &str, user_id: &str, kind: Kind) -> Broadcast { | 170 | +pub(crate) fn share_ended(community_id: Id, user_id: Id, kind: ShareKind) -> Broadcast { |
| 170 | let event = Event::ShareStopped { | 171 | let event = Event::ShareStopped { |
| 171 | - community_id: community_id.to_string(), | 172 | + community_id, |
| 172 | - user_id: user_id.to_string(), | 173 | + user_id, |
| 173 | kind, | 174 | kind, |
| 174 | }; | 175 | }; |
| 175 | 176 | ||
| 176 | - Broadcast::new(To::Community(community_id.to_string()), event) | 177 | + Broadcast::new(To::Community(community_id), event) |
| 177 | } | 178 | } |
| 178 | 179 | ||
| 179 | pub(crate) fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> { | 180 | pub(crate) fn shares_ended(departure: &mut Departure) -> Vec<Broadcast> { |
| 180 | let mut broadcasts: Vec<Broadcast> = departure | 181 | let mut broadcasts: Vec<Broadcast> = departure |
| 181 | .shares | 182 | .shares |
| 182 | .iter() | 183 | .iter() |
| 183 | - .map(|kind| share_ended(&departure.community_id, &departure.user_id, *kind)) | 184 | + .map(|kind| share_ended(departure.community_id, departure.user_id, *kind)) |
| 184 | .collect(); | 185 | .collect(); |
| 185 | broadcasts.append(&mut departure.media); | 186 | broadcasts.append(&mut departure.media); |
| 186 | 187 | ||
| 187 | broadcasts | 188 | broadcasts |
| 188 | } | 189 | } |
| 189 | 190 | ||
| 190 | -pub(crate) async fn authenticated(client: &Client, conn: &Connection) -> Result<User, ServerError> { | 191 | +pub(crate) fn messages_deleted(rows: Vec<(Id, Id)>) -> Vec<Broadcast> { |
| 191 | - let user_id = client.user_id().ok_or(CommonError::Unauthenticated)?; | 192 | + let mut deleted: BTreeMap<Id, Vec<Id>> = BTreeMap::new(); |
| 193 | + for (community_id, message_id) in rows { | ||
| 194 | + deleted.entry(community_id).or_default().push(message_id); | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + deleted | ||
| 198 | + .into_iter() | ||
| 199 | + .map(|(community_id, ids)| { | ||
| 200 | + let event = Event::MessagesDeleted { community_id, ids }; | ||
| 201 | + Broadcast::new(To::Community(community_id), event) | ||
| 202 | + }) | ||
| 203 | + .collect() | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +pub(crate) async fn authenticated(client: &Client, db: &Connection) -> Result<User, ServerError> { | ||
| 207 | + let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; | ||
| 192 | 208 | ||
| 193 | - user::read(user_id, conn).await | 209 | + Ok(db::session::user_of(me.session_id, db) |
| 210 | + .await? | ||
| 211 | + .ok_or(CommonError::Unauthenticated)?) | ||
| 194 | } | 212 | } |
| 195 | 213 | ||
| 196 | pub async fn actor_rank( | 214 | pub async fn actor_rank( |
| 197 | me: &User, | 215 | me: &User, |
| 198 | - community_id: &str, | 216 | + community_id: Id, |
| 199 | - conn: &Connection, | 217 | + db: &Connection, |
| 200 | ) -> Result<Option<Rank>, ServerError> { | 218 | ) -> Result<Option<Rank>, ServerError> { |
| 201 | - let rank = user_community::rank(&me.id, community_id, conn).await?; | 219 | + let rank = db::member::rank(me.id, community_id, db).await?; |
| 202 | 220 | ||
| 203 | Ok(permission::effective_rank(me.role, rank)) | 221 | Ok(permission::effective_rank(me.role, rank)) |
| 204 | } | 222 | } |
| 205 | 223 | ||
| 206 | -pub(crate) async fn managed( | 224 | +pub(crate) async fn managed(me: &User, user_id: Id, db: &Connection) -> Result<User, ServerError> { |
| 207 | - me: &User, | 225 | + let target = db::user::read(user_id, db).await?; |
| 208 | - user_id: &str, | ||
| 209 | - conn: &Connection, | ||
| 210 | -) -> Result<User, ServerError> { | ||
| 211 | - let target = user::read(user_id, conn).await?; | ||
| 212 | ensure(permission::can_manage_user( | 226 | ensure(permission::can_manage_user( |
| 213 | me.role, | 227 | me.role, |
| 214 | me.id == user_id, | 228 | me.id == user_id, |
| @@ -218,66 +232,49 @@ pub(crate) async fn managed( | |||
| 218 | Ok(target) | 232 | Ok(target) |
| 219 | } | 233 | } |
| 220 | 234 | ||
| 221 | -pub fn ensure(allowed: bool) -> Result<(), ServerError> { | ||
| 222 | - ensure_with(allowed, CommonError::Forbidden) | ||
| 223 | -} | ||
| 224 | - | ||
| 225 | -pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), ServerError> { | ||
| 226 | - if !allowed { | ||
| 227 | - return Err(error.into()); | ||
| 228 | - } | ||
| 229 | - | ||
| 230 | - Ok(()) | ||
| 231 | -} | ||
| 232 | - | ||
| 233 | pub(crate) async fn allowed( | 235 | pub(crate) async fn allowed( |
| 234 | me: &User, | 236 | me: &User, |
| 235 | - community_id: &str, | 237 | + community_id: Id, |
| 236 | - conn: &Connection, | 238 | + db: &Connection, |
| 237 | check: fn(Option<Rank>) -> bool, | 239 | check: fn(Option<Rank>) -> bool, |
| 238 | ) -> Result<(), ServerError> { | 240 | ) -> Result<(), ServerError> { |
| 239 | - ensure(check(actor_rank(me, community_id, conn).await?)) | 241 | + ensure(check(actor_rank(me, community_id, db).await?)) |
| 240 | } | 242 | } |
| 241 | 243 | ||
| 242 | pub(crate) async fn is_outsider( | 244 | pub(crate) async fn is_outsider( |
| 243 | - user_id: &str, | 245 | + user_id: Id, |
| 244 | - community_id: &str, | 246 | + community_id: Id, |
| 245 | - conn: &Connection, | 247 | + db: &Connection, |
| 246 | ) -> Result<bool, ServerError> { | 248 | ) -> Result<bool, ServerError> { |
| 247 | - Ok(user_community::rank(user_id, community_id, conn) | 249 | + Ok(db::member::rank(user_id, community_id, db).await?.is_none()) |
| 248 | - .await? | ||
| 249 | - .is_none()) | ||
| 250 | } | 250 | } |
| 251 | 251 | ||
| 252 | -pub(crate) async fn ensure_editable( | 252 | +pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result<(), ServerError> { |
| 253 | - community_id: &str, | 253 | + let kind = db::community::kind_of(community_id, db) |
| 254 | - conn: &Connection, | 254 | + .await? |
| 255 | -) -> Result<(), ServerError> { | 255 | + .ok_or(CommonError::NotFound)?; |
| 256 | - ensure(!community::is_fixed(community_id, conn).await?) | 256 | + |
| 257 | + ensure(kind == Kind::Group) | ||
| 257 | } | 258 | } |
| 258 | 259 | ||
| 259 | pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { | 260 | pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { |
| 260 | - Broadcast::new( | 261 | + Broadcast::new(To::Community(message.community_id), event(message.clone())) |
| 261 | - To::Community(message.community_id.clone()), | ||
| 262 | - event(message.clone()), | ||
| 263 | - ) | ||
| 264 | } | 262 | } |
| 265 | 263 | ||
| 266 | -pub(crate) fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Vec<Broadcast> { | 264 | +pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec<Broadcast> { |
| 267 | - let to = || To::Community(community_id.to_string()); | ||
| 268 | let mut broadcasts = vec![Broadcast::new( | 265 | let mut broadcasts = vec![Broadcast::new( |
| 269 | - to(), | 266 | + To::Community(community_id), |
| 270 | Event::VoiceJoined { | 267 | Event::VoiceJoined { |
| 271 | - community_id: community_id.to_string(), | 268 | + community_id, |
| 272 | - user_id: user_id.to_string(), | 269 | + user_id, |
| 273 | }, | 270 | }, |
| 274 | )]; | 271 | )]; |
| 275 | if muted { | 272 | if muted { |
| 276 | broadcasts.push(Broadcast::new( | 273 | broadcasts.push(Broadcast::new( |
| 277 | - to(), | 274 | + To::Community(community_id), |
| 278 | Event::VoiceMuted { | 275 | Event::VoiceMuted { |
| 279 | - community_id: Some(community_id.to_string()), | 276 | + community_id: Some(community_id), |
| 280 | - user_id: user_id.to_string(), | 277 | + user_id, |
| 281 | muted, | 278 | muted, |
| 282 | }, | 279 | }, |
| 283 | )); | 280 | )); |
| @@ -287,18 +284,18 @@ pub(crate) fn voice_joined(community_id: &str, user_id: &str, muted: bool) -> Ve | |||
| 287 | } | 284 | } |
| 288 | 285 | ||
| 289 | pub(crate) async fn record_ghost_voice( | 286 | pub(crate) async fn record_ghost_voice( |
| 290 | - user_id: &str, | 287 | + user_id: Id, |
| 291 | - community_id: &str, | 288 | + community_id: Id, |
| 292 | seconds: u64, | 289 | seconds: u64, |
| 293 | - conn: &Connection, | 290 | + db: &Connection, |
| 294 | ) -> Result<(), ServerError> { | 291 | ) -> Result<(), ServerError> { |
| 295 | - let community = community::label(community_id, conn).await?; | 292 | + let community = db::community::label(community_id, db).await?; |
| 296 | - admin_log::record( | 293 | + db::log::record_admin( |
| 297 | Some(user_id), | 294 | Some(user_id), |
| 298 | None, | 295 | None, |
| 299 | Some(&community), | 296 | Some(&community), |
| 300 | &AdminAction::GhostVoice { seconds }, | 297 | &AdminAction::GhostVoice { seconds }, |
| 301 | - conn, | 298 | + db, |
| 302 | ) | 299 | ) |
| 303 | .await | 300 | .await |
| 304 | } | 301 | } |
| @@ -310,23 +307,23 @@ mod tests { | |||
| 310 | use common::{ | 307 | use common::{ |
| 311 | call::{ | 308 | call::{ |
| 312 | AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, | 309 | AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, |
| 313 | - DeleteCommunity, FindUser, Invite, ListCommunities, ListFriends, Register, | 310 | + DeleteCommunity, FindUser, Invite, ListCommunities, ListFriends, UpdateCommunity, |
| 314 | - UpdateCommunity, | ||
| 315 | }, | 311 | }, |
| 316 | error::Error as CommonError, | 312 | error::Error as CommonError, |
| 313 | + model::{Id, Role}, | ||
| 317 | }; | 314 | }; |
| 318 | 315 | ||
| 319 | use crate::{ | 316 | use crate::{ |
| 317 | + authentication::token_hash, | ||
| 320 | call::{Cx, Handle, Me}, | 318 | call::{Cx, Handle, Me}, |
| 321 | - database::{self, DB}, | 319 | + db::{self, Db}, |
| 322 | hub::{Client, Signed}, | 320 | hub::{Client, Signed}, |
| 323 | - message, | ||
| 324 | network::{Services, Shared}, | 321 | network::{Services, Shared}, |
| 325 | request::authenticated, | 322 | request::authenticated, |
| 326 | test, | 323 | test, |
| 327 | }; | 324 | }; |
| 328 | 325 | ||
| 329 | - fn shared(db: &DB, services: &Services) -> Shared { | 326 | + fn shared(db: &Db, services: &Services) -> Shared { |
| 330 | Shared { | 327 | Shared { |
| 331 | db: db.clone(), | 328 | db: db.clone(), |
| 332 | services: services.clone(), | 329 | services: services.clone(), |
| @@ -338,43 +335,38 @@ mod tests { | |||
| 338 | async fn call<C: Handle>( | 335 | async fn call<C: Handle>( |
| 339 | call: C, | 336 | call: C, |
| 340 | client: &Arc<Client>, | 337 | client: &Arc<Client>, |
| 341 | - db: &DB, | 338 | + db: &Db, |
| 342 | services: &Services, | 339 | services: &Services, |
| 343 | ) -> Result<C::Reply, CommonError> { | 340 | ) -> Result<C::Reply, CommonError> { |
| 344 | let shared = shared(db, services); | 341 | let shared = shared(db, services); |
| 345 | - let conn = database::connect(db).await.unwrap(); | 342 | + let conn = db.lock().await.unwrap(); |
| 346 | let me = authenticated(client, &conn).await?; | 343 | let me = authenticated(client, &conn).await?; |
| 347 | - let mut cx = Cx::new(client, &shared, conn); | 344 | + let mut cx = Cx::new(client, &shared, &conn); |
| 348 | 345 | ||
| 349 | Ok(call.handle(Me::User(me), &mut cx).await?) | 346 | Ok(call.handle(Me::User(me), &mut cx).await?) |
| 350 | } | 347 | } |
| 351 | 348 | ||
| 352 | - async fn signed_in(username: &str, db: &DB, services: &Services) -> Arc<Client> { | 349 | + async fn signed_in(username: &str, db: &Db) -> Arc<Client> { |
| 353 | - let guest = Client::detached(None); | 350 | + let conn = db.lock().await.unwrap(); |
| 354 | - let shared = shared(db, services); | 351 | + let user = db::user::create(username, "hash", Role::User, &conn) |
| 355 | - let conn = database::connect(db).await.unwrap(); | 352 | + .await |
| 356 | - let mut cx = Cx::new(&guest, &shared, conn); | 353 | + .unwrap(); |
| 357 | - let session = Register { | 354 | + let session_id = db::session::insert(&token_hash(username), user.id, &conn) |
| 358 | - username: username.to_string(), | 355 | + .await |
| 359 | - password: "password".to_string(), | 356 | + .unwrap(); |
| 360 | - invite: None, | ||
| 361 | - } | ||
| 362 | - .handle(Me::Guest, &mut cx) | ||
| 363 | - .await | ||
| 364 | - .unwrap(); | ||
| 365 | 357 | ||
| 366 | Client::detached(Some(Signed { | 358 | Client::detached(Some(Signed { |
| 367 | - user_id: session.user.id, | 359 | + user_id: user.id, |
| 368 | - token: session.token, | 360 | + session_id, |
| 369 | })) | 361 | })) |
| 370 | } | 362 | } |
| 371 | 363 | ||
| 372 | async fn invite_and_accept( | 364 | async fn invite_and_accept( |
| 373 | - community_id: &str, | 365 | + community_id: Id, |
| 374 | owner: &Arc<Client>, | 366 | owner: &Arc<Client>, |
| 375 | member: &Arc<Client>, | 367 | member: &Arc<Client>, |
| 376 | username: &str, | 368 | username: &str, |
| 377 | - db: &DB, | 369 | + db: &Db, |
| 378 | services: &Services, | 370 | services: &Services, |
| 379 | ) { | 371 | ) { |
| 380 | let member_user = call( | 372 | let member_user = call( |
| @@ -389,7 +381,7 @@ mod tests { | |||
| 389 | .unwrap(); | 381 | .unwrap(); |
| 390 | call( | 382 | call( |
| 391 | Invite { | 383 | Invite { |
| 392 | - community_id: community_id.to_string(), | 384 | + community_id, |
| 393 | user_id: member_user.id, | 385 | user_id: member_user.id, |
| 394 | }, | 386 | }, |
| 395 | owner, | 387 | owner, |
| @@ -398,24 +390,17 @@ mod tests { | |||
| 398 | ) | 390 | ) |
| 399 | .await | 391 | .await |
| 400 | .unwrap(); | 392 | .unwrap(); |
| 401 | - call( | 393 | + call(AcceptInvitation { community_id }, member, db, services) |
| 402 | - AcceptInvitation { | 394 | + .await |
| 403 | - community_id: community_id.to_string(), | 395 | + .unwrap(); |
| 404 | - }, | ||
| 405 | - member, | ||
| 406 | - db, | ||
| 407 | - services, | ||
| 408 | - ) | ||
| 409 | - .await | ||
| 410 | - .unwrap(); | ||
| 411 | } | 396 | } |
| 412 | 397 | ||
| 413 | #[tokio::test] | 398 | #[tokio::test] |
| 414 | async fn plain_member_cannot_rename() { | 399 | async fn plain_member_cannot_rename() { |
| 415 | - let db = test::get_database().await; | 400 | + let db = test::db().await; |
| 416 | let services = Services::default(); | 401 | let services = Services::default(); |
| 417 | - let owner = signed_in("Owner", &db, &services).await; | 402 | + let owner = signed_in("Owner", &db).await; |
| 418 | - let member = signed_in("Member", &db, &services).await; | 403 | + let member = signed_in("Member", &db).await; |
| 419 | let community = call( | 404 | let community = call( |
| 420 | CreateCommunity { | 405 | CreateCommunity { |
| 421 | name: "The Community".to_string(), | 406 | name: "The Community".to_string(), |
| @@ -426,7 +411,7 @@ mod tests { | |||
| 426 | ) | 411 | ) |
| 427 | .await | 412 | .await |
| 428 | .unwrap(); | 413 | .unwrap(); |
| 429 | - invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; | 414 | + invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; |
| 430 | 415 | ||
| 431 | let response = call( | 416 | let response = call( |
| 432 | UpdateCommunity { | 417 | UpdateCommunity { |
| @@ -444,10 +429,10 @@ mod tests { | |||
| 444 | 429 | ||
| 445 | #[tokio::test] | 430 | #[tokio::test] |
| 446 | async fn accepted_friend_request_befriends_both() { | 431 | async fn accepted_friend_request_befriends_both() { |
| 447 | - let db = test::get_database().await; | 432 | + let db = test::db().await; |
| 448 | let services = Services::default(); | 433 | let services = Services::default(); |
| 449 | - let first = signed_in("First", &db, &services).await; | 434 | + let first = signed_in("First", &db).await; |
| 450 | - let second = signed_in("Second", &db, &services).await; | 435 | + let second = signed_in("Second", &db).await; |
| 451 | let first_user = call( | 436 | let first_user = call( |
| 452 | FindUser { | 437 | FindUser { |
| 453 | username: "First".to_string(), | 438 | username: "First".to_string(), |
| @@ -470,7 +455,7 @@ mod tests { | |||
| 470 | .unwrap(); | 455 | .unwrap(); |
| 471 | call( | 456 | call( |
| 472 | AddFriend { | 457 | AddFriend { |
| 473 | - user_id: second_user.id.clone(), | 458 | + user_id: second_user.id, |
| 474 | }, | 459 | }, |
| 475 | &first, | 460 | &first, |
| 476 | &db, | 461 | &db, |
| @@ -480,7 +465,7 @@ mod tests { | |||
| 480 | .unwrap(); | 465 | .unwrap(); |
| 481 | call( | 466 | call( |
| 482 | AcceptFriend { | 467 | AcceptFriend { |
| 483 | - user_id: first_user.id.clone(), | 468 | + user_id: first_user.id, |
| 484 | }, | 469 | }, |
| 485 | &second, | 470 | &second, |
| 486 | &db, | 471 | &db, |
| @@ -498,10 +483,10 @@ mod tests { | |||
| 498 | 483 | ||
| 499 | #[tokio::test] | 484 | #[tokio::test] |
| 500 | async fn invite_and_accept_makes_member() { | 485 | async fn invite_and_accept_makes_member() { |
| 501 | - let db = test::get_database().await; | 486 | + let db = test::db().await; |
| 502 | let services = Services::default(); | 487 | let services = Services::default(); |
| 503 | - let owner = signed_in("Owner", &db, &services).await; | 488 | + let owner = signed_in("Owner", &db).await; |
| 504 | - let member = signed_in("Member", &db, &services).await; | 489 | + let member = signed_in("Member", &db).await; |
| 505 | let community = call( | 490 | let community = call( |
| 506 | CreateCommunity { | 491 | CreateCommunity { |
| 507 | name: "The Community".to_string(), | 492 | name: "The Community".to_string(), |
| @@ -513,7 +498,7 @@ mod tests { | |||
| 513 | .await | 498 | .await |
| 514 | .unwrap(); | 499 | .unwrap(); |
| 515 | 500 | ||
| 516 | - invite_and_accept(&community.id, &owner, &member, "Member", &db, &services).await; | 501 | + invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; |
| 517 | 502 | ||
| 518 | let communities = call(ListCommunities, &member, &db, &services) | 503 | let communities = call(ListCommunities, &member, &db, &services) |
| 519 | .await | 504 | .await |
| @@ -523,9 +508,9 @@ mod tests { | |||
| 523 | 508 | ||
| 524 | #[tokio::test] | 509 | #[tokio::test] |
| 525 | async fn delete_community_removes_messages() { | 510 | async fn delete_community_removes_messages() { |
| 526 | - let db = test::get_database().await; | 511 | + let db = test::db().await; |
| 527 | let services = Services::default(); | 512 | let services = Services::default(); |
| 528 | - let owner = signed_in("Owner", &db, &services).await; | 513 | + let owner = signed_in("Owner", &db).await; |
| 529 | let community = call( | 514 | let community = call( |
| 530 | CreateCommunity { | 515 | CreateCommunity { |
| 531 | name: "The Community".to_string(), | 516 | name: "The Community".to_string(), |
| @@ -538,7 +523,7 @@ mod tests { | |||
| 538 | .unwrap(); | 523 | .unwrap(); |
| 539 | call( | 524 | call( |
| 540 | CreateMessage { | 525 | CreateMessage { |
| 541 | - community_id: community.id.clone(), | 526 | + community_id: community.id, |
| 542 | body: "Tahinli".to_string(), | 527 | body: "Tahinli".to_string(), |
| 543 | attachments: Vec::new(), | 528 | attachments: Vec::new(), |
| 544 | reply_to: None, | 529 | reply_to: None, |
| @@ -552,7 +537,7 @@ mod tests { | |||
| 552 | 537 | ||
| 553 | call( | 538 | call( |
| 554 | DeleteCommunity { | 539 | DeleteCommunity { |
| 555 | - community_id: community.id.clone(), | 540 | + community_id: community.id, |
| 556 | }, | 541 | }, |
| 557 | &owner, | 542 | &owner, |
| 558 | &db, | 543 | &db, |
| @@ -561,8 +546,8 @@ mod tests { | |||
| 561 | .await | 546 | .await |
| 562 | .unwrap(); | 547 | .unwrap(); |
| 563 | 548 | ||
| 564 | - let conn = database::connect(&db).await.unwrap(); | 549 | + let conn = db.lock().await.unwrap(); |
| 565 | - let remaining = message::read_page(&community.id, None, &conn) | 550 | + let remaining = db::message::read_page(community.id, None, &conn) |
| 566 | .await | 551 | .await |
| 567 | .unwrap(); | 552 | .unwrap(); |
| 568 | 553 | ||
crates/server/src/retention.rsmodified+30 -82
| @@ -1,20 +1,12 @@ | |||
| 1 | -use std::{collections::BTreeMap, path::Path, time::Duration}; | 1 | +use std::time::Duration; |
| 2 | 2 | ||
| 3 | -use common::{event::Event, time}; | 3 | +use common::time; |
| 4 | use tracing::{error, info}; | 4 | use tracing::{error, info}; |
| 5 | -use turso::Connection; | ||
| 6 | 5 | ||
| 7 | -use crate::{ | 6 | +use crate::{db, error::ServerError, network::Shared, publish::job, request::messages_deleted}; |
| 8 | - attachment, database, | ||
| 9 | - error::ServerError, | ||
| 10 | - message, | ||
| 11 | - network::Shared, | ||
| 12 | - publish::{Broadcast, To, publish}, | ||
| 13 | - server_settings, | ||
| 14 | -}; | ||
| 15 | 7 | ||
| 16 | const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); | 8 | const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); |
| 17 | -const BATCH_SIZE: i64 = 500; | 9 | +const BATCH_SIZE: u32 = 500; |
| 18 | 10 | ||
| 19 | pub(crate) async fn collect(shared: Shared) { | 11 | pub(crate) async fn collect(shared: Shared) { |
| 20 | let mut interval = tokio::time::interval(SWEEP_INTERVAL); | 12 | let mut interval = tokio::time::interval(SWEEP_INTERVAL); |
| @@ -26,99 +18,55 @@ pub(crate) async fn collect(shared: Shared) { | |||
| 26 | } | 18 | } |
| 27 | } | 19 | } |
| 28 | 20 | ||
| 29 | -fn cutoff(now: u64, days: u32) -> String { | 21 | +fn cutoff(days: u32) -> u64 { |
| 30 | - time::id_bound(now.saturating_sub(u64::from(days) * time::DAY_MILLIS)) | 22 | + time::now_ms().saturating_sub(u64::from(days) * time::DAY_MILLIS) |
| 31 | } | 23 | } |
| 32 | 24 | ||
| 33 | -async fn expired(table: &str, cutoff: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | 25 | +async fn purge_messages(cutoff: u64, shared: &Shared) -> Result<u64, ServerError> { |
| 34 | - let mut rows = conn | ||
| 35 | - .query( | ||
| 36 | - &format!("SELECT id FROM {table} WHERE id < ?1 ORDER BY id LIMIT ?2"), | ||
| 37 | - (cutoff, BATCH_SIZE), | ||
| 38 | - ) | ||
| 39 | - .await?; | ||
| 40 | - | ||
| 41 | - let mut ids = Vec::new(); | ||
| 42 | - while let Some(row) = rows.next().await? { | ||
| 43 | - ids.push(row.get(0)?); | ||
| 44 | - } | ||
| 45 | - | ||
| 46 | - Ok(ids) | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -async fn purge_messages( | ||
| 50 | - cutoff: &str, | ||
| 51 | - conn: &mut Connection, | ||
| 52 | - shared: &Shared, | ||
| 53 | -) -> Result<u64, ServerError> { | ||
| 54 | let mut purged = 0; | 26 | let mut purged = 0; |
| 55 | loop { | 27 | loop { |
| 56 | - let ids = expired("message", cutoff, conn).await?; | 28 | + let mut deleted = 0; |
| 57 | - if ids.is_empty() { | 29 | + job(shared, async |db| { |
| 58 | - return Ok(purged); | 30 | + let rows = db::message::delete_before(cutoff, BATCH_SIZE, db).await?; |
| 59 | - } | 31 | + deleted = rows.len() as u64; |
| 60 | 32 | ||
| 61 | - let tx = conn.transaction().await?; | 33 | + Ok(messages_deleted(rows)) |
| 62 | - let mut files = Vec::new(); | 34 | + }) |
| 63 | - let mut deleted: BTreeMap<String, Vec<String>> = BTreeMap::new(); | 35 | + .await?; |
| 64 | - for id in &ids { | 36 | + if deleted == 0 { |
| 65 | - files.extend(attachment::ids_of_message(id, &tx).await?); | 37 | + return Ok(purged); |
| 66 | - let message = message::delete(id, &tx).await?; | ||
| 67 | - deleted | ||
| 68 | - .entry(message.community_id) | ||
| 69 | - .or_default() | ||
| 70 | - .push(message.id); | ||
| 71 | } | 38 | } |
| 72 | - tx.commit().await?; | 39 | + purged += deleted; |
| 73 | - attachment::remove_files(&files, &shared.directory); | ||
| 74 | - let broadcasts = deleted | ||
| 75 | - .into_iter() | ||
| 76 | - .map(|(community_id, ids)| { | ||
| 77 | - let event = Event::MessagesDeleted { | ||
| 78 | - community_id: community_id.clone(), | ||
| 79 | - ids, | ||
| 80 | - }; | ||
| 81 | - Broadcast::new(To::Community(community_id), event) | ||
| 82 | - }) | ||
| 83 | - .collect(); | ||
| 84 | - publish(shared, broadcasts).await; | ||
| 85 | - purged += ids.len() as u64; | ||
| 86 | } | 40 | } |
| 87 | } | 41 | } |
| 88 | 42 | ||
| 89 | -async fn purge_attachments( | 43 | +async fn purge_attachments(cutoff: u64, shared: &Shared) -> Result<u64, ServerError> { |
| 90 | - cutoff: &str, | ||
| 91 | - conn: &mut Connection, | ||
| 92 | - directory: &Path, | ||
| 93 | -) -> Result<u64, ServerError> { | ||
| 94 | let mut purged = 0; | 44 | let mut purged = 0; |
| 95 | loop { | 45 | loop { |
| 96 | - let ids = expired("attachment", cutoff, conn).await?; | 46 | + let mut deleted = 0; |
| 97 | - if ids.is_empty() { | 47 | + job(shared, async |db| { |
| 98 | - return Ok(purged); | 48 | + deleted = db::attachment::delete_before(cutoff, BATCH_SIZE, db).await?; |
| 99 | - } | ||
| 100 | 49 | ||
| 101 | - for id in &ids { | 50 | + Ok(Vec::new()) |
| 102 | - attachment::delete(id, conn).await?; | 51 | + }) |
| 52 | + .await?; | ||
| 53 | + if deleted == 0 { | ||
| 54 | + return Ok(purged); | ||
| 103 | } | 55 | } |
| 104 | - attachment::remove_files(&ids, directory); | 56 | + purged += deleted; |
| 105 | - purged += ids.len() as u64; | ||
| 106 | } | 57 | } |
| 107 | } | 58 | } |
| 108 | 59 | ||
| 109 | async fn sweep(shared: &Shared) -> Result<(), ServerError> { | 60 | async fn sweep(shared: &Shared) -> Result<(), ServerError> { |
| 110 | - let directory = &shared.directory; | 61 | + let settings = shared.db.run(db::settings::read).await?; |
| 111 | - let mut conn = database::connect(&shared.db).await?; | ||
| 112 | - let settings = server_settings::read(&conn).await?; | ||
| 113 | - let now = time::now_ms(); | ||
| 114 | 62 | ||
| 115 | let messages = match settings.message_retention_days { | 63 | let messages = match settings.message_retention_days { |
| 116 | 0 => 0, | 64 | 0 => 0, |
| 117 | - days => purge_messages(&cutoff(now, days), &mut conn, shared).await?, | 65 | + days => purge_messages(cutoff(days), shared).await?, |
| 118 | }; | 66 | }; |
| 119 | let attachments = match settings.attachment_retention_days { | 67 | let attachments = match settings.attachment_retention_days { |
| 120 | 0 => 0, | 68 | 0 => 0, |
| 121 | - days => purge_attachments(&cutoff(now, days), &mut conn, directory).await?, | 69 | + days => purge_attachments(cutoff(days), shared).await?, |
| 122 | }; | 70 | }; |
| 123 | 71 | ||
| 124 | if messages + attachments > 0 { | 72 | if messages + attachments > 0 { |
crates/server/src/rooms.rsmodified+75 -80
| @@ -8,7 +8,7 @@ use common::{ | |||
| 8 | datagram::{self, Packet, RELAY_PREFIX, relayed}, | 8 | datagram::{self, Packet, RELAY_PREFIX, relayed}, |
| 9 | error::Error, | 9 | error::Error, |
| 10 | event::{Event, Media}, | 10 | event::{Event, Media}, |
| 11 | - model::CallLog, | 11 | + model::{CallLog, Id}, |
| 12 | share::{Codec, Kind, Layer, Quality, Share, Source, choose}, | 12 | share::{Codec, Kind, Layer, Quality, Share, Source, choose}, |
| 13 | time, | 13 | time, |
| 14 | }; | 14 | }; |
| @@ -67,7 +67,7 @@ impl Forward { | |||
| 67 | } | 67 | } |
| 68 | 68 | ||
| 69 | struct Viewer { | 69 | struct Viewer { |
| 70 | - user_id: String, | 70 | + user_id: Id, |
| 71 | connection: Connection, | 71 | connection: Connection, |
| 72 | quality: Quality, | 72 | quality: Quality, |
| 73 | decode: Vec<Codec>, | 73 | decode: Vec<Codec>, |
| @@ -87,7 +87,7 @@ impl Sharing { | |||
| 87 | .collect() | 87 | .collect() |
| 88 | } | 88 | } |
| 89 | 89 | ||
| 90 | - fn viewer(&self, user_id: &str) -> Option<&Viewer> { | 90 | + fn viewer(&self, user_id: Id) -> Option<&Viewer> { |
| 91 | self.viewers.iter().find(|viewer| viewer.user_id == user_id) | 91 | self.viewers.iter().find(|viewer| viewer.user_id == user_id) |
| 92 | } | 92 | } |
| 93 | } | 93 | } |
| @@ -111,10 +111,10 @@ fn layers_changed( | |||
| 111 | }) | 111 | }) |
| 112 | } | 112 | } |
| 113 | 113 | ||
| 114 | -struct Sharer<'a> { | 114 | +struct Sharer { |
| 115 | conn: ConnId, | 115 | conn: ConnId, |
| 116 | - user_id: &'a str, | 116 | + user_id: Id, |
| 117 | - community_id: &'a str, | 117 | + community_id: Id, |
| 118 | kind: Kind, | 118 | kind: Kind, |
| 119 | } | 119 | } |
| 120 | 120 | ||
| @@ -127,10 +127,10 @@ fn reroute(sharer: &Sharer, sharing: &mut Sharing) -> Vec<Broadcast> { | |||
| 127 | viewers.retain_mut(|viewer| { | 127 | viewers.retain_mut(|viewer| { |
| 128 | let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { | 128 | let Some(layer) = choose(source, viewer.quality, &viewer.decode, &used) else { |
| 129 | stopped.push(Broadcast::new( | 129 | stopped.push(Broadcast::new( |
| 130 | - To::User(viewer.user_id.clone()), | 130 | + To::User(viewer.user_id), |
| 131 | Event::ShareStopped { | 131 | Event::ShareStopped { |
| 132 | - community_id: sharer.community_id.to_string(), | 132 | + community_id: sharer.community_id, |
| 133 | - user_id: sharer.user_id.to_string(), | 133 | + user_id: sharer.user_id, |
| 134 | kind: sharer.kind, | 134 | kind: sharer.kind, |
| 135 | }, | 135 | }, |
| 136 | )); | 136 | )); |
| @@ -164,7 +164,7 @@ fn remove_viewer( | |||
| 164 | sharer: ConnId, | 164 | sharer: ConnId, |
| 165 | kind: Kind, | 165 | kind: Kind, |
| 166 | sharing: &mut Sharing, | 166 | sharing: &mut Sharing, |
| 167 | - viewer_id: &str, | 167 | + viewer_id: Id, |
| 168 | ) -> Option<Broadcast> { | 168 | ) -> Option<Broadcast> { |
| 169 | let before = sharing.layers(); | 169 | let before = sharing.layers(); |
| 170 | sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | 170 | sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); |
| @@ -173,8 +173,8 @@ fn remove_viewer( | |||
| 173 | } | 173 | } |
| 174 | 174 | ||
| 175 | struct Seat { | 175 | struct Seat { |
| 176 | - user_id: String, | 176 | + user_id: Id, |
| 177 | - uuid: [u8; RELAY_PREFIX], | 177 | + prefix: [u8; RELAY_PREFIX], |
| 178 | connection: Connection, | 178 | connection: Connection, |
| 179 | muted: bool, | 179 | muted: bool, |
| 180 | ghost: bool, | 180 | ghost: bool, |
| @@ -207,11 +207,11 @@ impl Room { | |||
| 207 | self.seats.values().any(|seat| !seat.ghost) | 207 | self.seats.values().any(|seat| !seat.ghost) |
| 208 | } | 208 | } |
| 209 | 209 | ||
| 210 | - fn user_ids(&self, keep: impl Fn(&Seat) -> bool) -> Vec<String> { | 210 | + fn user_ids(&self, keep: impl Fn(&Seat) -> bool) -> Vec<Id> { |
| 211 | self.seats | 211 | self.seats |
| 212 | .values() | 212 | .values() |
| 213 | .filter(|seat| keep(seat)) | 213 | .filter(|seat| keep(seat)) |
| 214 | - .map(|seat| seat.user_id.clone()) | 214 | + .map(|seat| seat.user_id) |
| 215 | .collect() | 215 | .collect() |
| 216 | } | 216 | } |
| 217 | 217 | ||
| @@ -234,7 +234,7 @@ impl Room { | |||
| 234 | } | 234 | } |
| 235 | } | 235 | } |
| 236 | 236 | ||
| 237 | - fn drop_viewer(&mut self, user_id: &str) -> Vec<Broadcast> { | 237 | + fn drop_viewer(&mut self, user_id: Id) -> Vec<Broadcast> { |
| 238 | let mut broadcasts = Vec::new(); | 238 | let mut broadcasts = Vec::new(); |
| 239 | for (conn, seat) in &mut self.seats { | 239 | for (conn, seat) in &mut self.seats { |
| 240 | for (kind, sharing) in &mut seat.shares { | 240 | for (kind, sharing) in &mut seat.shares { |
| @@ -247,8 +247,8 @@ impl Room { | |||
| 247 | } | 247 | } |
| 248 | 248 | ||
| 249 | pub struct Departure { | 249 | pub struct Departure { |
| 250 | - pub community_id: String, | 250 | + pub community_id: Id, |
| 251 | - pub user_id: String, | 251 | + pub user_id: Id, |
| 252 | pub ghost_seconds: Option<u64>, | 252 | pub ghost_seconds: Option<u64>, |
| 253 | pub call_log: Option<CallLog>, | 253 | pub call_log: Option<CallLog>, |
| 254 | pub shares: Vec<Kind>, | 254 | pub shares: Vec<Kind>, |
| @@ -263,20 +263,20 @@ pub struct Joined { | |||
| 263 | 263 | ||
| 264 | #[derive(Default)] | 264 | #[derive(Default)] |
| 265 | struct Inner { | 265 | struct Inner { |
| 266 | - rooms: HashMap<String, Room>, | 266 | + rooms: HashMap<Id, Room>, |
| 267 | - seat_of: HashMap<ConnId, String>, | 267 | + seat_of: HashMap<ConnId, Id>, |
| 268 | - conn_of_user: HashMap<String, ConnId>, | 268 | + conn_of_user: HashMap<Id, ConnId>, |
| 269 | } | 269 | } |
| 270 | 270 | ||
| 271 | impl Inner { | 271 | impl Inner { |
| 272 | - fn seat_conn(&self, user_id: &str) -> Option<ConnId> { | 272 | + fn seat_conn(&self, user_id: Id) -> Option<ConnId> { |
| 273 | - self.conn_of_user.get(user_id).copied() | 273 | + self.conn_of_user.get(&user_id).copied() |
| 274 | } | 274 | } |
| 275 | 275 | ||
| 276 | - fn seat_mut(&mut self, id: ConnId) -> Option<(&str, &mut Room)> { | 276 | + fn seat_mut(&mut self, id: ConnId) -> Option<(Id, &mut Room)> { |
| 277 | - let community_id = self.seat_of.get(&id)?; | 277 | + let community_id = *self.seat_of.get(&id)?; |
| 278 | 278 | ||
| 279 | - Some((community_id.as_str(), self.rooms.get_mut(community_id)?)) | 279 | + Some((community_id, self.rooms.get_mut(&community_id)?)) |
| 280 | } | 280 | } |
| 281 | 281 | ||
| 282 | fn take(&mut self, id: ConnId, notify: bool, quiet: bool) -> Option<Departure> { | 282 | fn take(&mut self, id: ConnId, notify: bool, quiet: bool) -> Option<Departure> { |
| @@ -286,7 +286,7 @@ impl Inner { | |||
| 286 | if self.conn_of_user.get(&seat.user_id) == Some(&id) { | 286 | if self.conn_of_user.get(&seat.user_id) == Some(&id) { |
| 287 | self.conn_of_user.remove(&seat.user_id); | 287 | self.conn_of_user.remove(&seat.user_id); |
| 288 | } | 288 | } |
| 289 | - let mut media = room.drop_viewer(&seat.user_id); | 289 | + let mut media = room.drop_viewer(seat.user_id); |
| 290 | let call_log = (!quiet && !seat.ghost && !room.occupied()) | 290 | let call_log = (!quiet && !seat.ghost && !room.occupied()) |
| 291 | .then(|| room.call_log()) | 291 | .then(|| room.call_log()) |
| 292 | .flatten(); | 292 | .flatten(); |
| @@ -316,15 +316,13 @@ impl Rooms { | |||
| 316 | pub fn join( | 316 | pub fn join( |
| 317 | &self, | 317 | &self, |
| 318 | client: &Client, | 318 | client: &Client, |
| 319 | - community_id: &str, | 319 | + community_id: Id, |
| 320 | muted: bool, | 320 | muted: bool, |
| 321 | ghost: bool, | 321 | ghost: bool, |
| 322 | ) -> Result<Joined, Error> { | 322 | ) -> Result<Joined, Error> { |
| 323 | let connection = client.conn.clone().ok_or(Error::Server)?; | 323 | let connection = client.conn.clone().ok_or(Error::Server)?; |
| 324 | let user_id = client.user_id().ok_or(Error::Unauthenticated)?; | 324 | let user_id = client.user_id().ok_or(Error::Unauthenticated)?; |
| 325 | - let uuid = *uuid::Uuid::parse_str(user_id) | 325 | + let prefix = user_id.to_be_bytes(); |
| 326 | - .map_err(|_| Error::Server)? | ||
| 327 | - .as_bytes(); | ||
| 328 | let mut inner = self.0.lock().unwrap(); | 326 | let mut inner = self.0.lock().unwrap(); |
| 329 | if client.closed.load(Ordering::Acquire) { | 327 | if client.closed.load(Ordering::Acquire) { |
| 330 | return Err(Error::Server); | 328 | return Err(Error::Server); |
| @@ -335,7 +333,7 @@ impl Rooms { | |||
| 335 | if let Some(previous) = inner.seat_conn(user_id) { | 333 | if let Some(previous) = inner.seat_conn(user_id) { |
| 336 | let kept = inner | 334 | let kept = inner |
| 337 | .rooms | 335 | .rooms |
| 338 | - .get(community_id) | 336 | + .get(&community_id) |
| 339 | .and_then(|room| room.seats.get(&previous)) | 337 | .and_then(|room| room.seats.get(&previous)) |
| 340 | .filter(|seat| seat.ghost == ghost) | 338 | .filter(|seat| seat.ghost == ghost) |
| 341 | .map(|seat| seat.joined_at); | 339 | .map(|seat| seat.joined_at); |
| @@ -343,18 +341,15 @@ impl Rooms { | |||
| 343 | joined_at = kept.unwrap_or(joined_at); | 341 | joined_at = kept.unwrap_or(joined_at); |
| 344 | departure = inner.take(previous, previous != client.id, transferred); | 342 | departure = inner.take(previous, previous != client.id, transferred); |
| 345 | } | 343 | } |
| 346 | - let room = inner | 344 | + let room = inner.rooms.entry(community_id).or_insert_with(Room::new); |
| 347 | - .rooms | ||
| 348 | - .entry(community_id.to_string()) | ||
| 349 | - .or_insert_with(Room::new); | ||
| 350 | if !ghost && !transferred { | 345 | if !ghost && !transferred { |
| 351 | room.admit(); | 346 | room.admit(); |
| 352 | } | 347 | } |
| 353 | room.seats.insert( | 348 | room.seats.insert( |
| 354 | client.id, | 349 | client.id, |
| 355 | Seat { | 350 | Seat { |
| 356 | - user_id: user_id.to_string(), | 351 | + user_id, |
| 357 | - uuid, | 352 | + prefix, |
| 358 | connection, | 353 | connection, |
| 359 | muted, | 354 | muted, |
| 360 | ghost, | 355 | ghost, |
| @@ -362,8 +357,8 @@ impl Rooms { | |||
| 362 | shares: BTreeMap::new(), | 357 | shares: BTreeMap::new(), |
| 363 | }, | 358 | }, |
| 364 | ); | 359 | ); |
| 365 | - inner.seat_of.insert(client.id, community_id.to_string()); | 360 | + inner.seat_of.insert(client.id, community_id); |
| 366 | - inner.conn_of_user.insert(user_id.to_string(), client.id); | 361 | + inner.conn_of_user.insert(user_id, client.id); |
| 367 | 362 | ||
| 368 | Ok(Joined { | 363 | Ok(Joined { |
| 369 | departure, | 364 | departure, |
| @@ -375,28 +370,28 @@ impl Rooms { | |||
| 375 | self.0.lock().unwrap().take(id, false, false) | 370 | self.0.lock().unwrap().take(id, false, false) |
| 376 | } | 371 | } |
| 377 | 372 | ||
| 378 | - pub fn leave_user(&self, user_id: &str) -> Option<Departure> { | 373 | + pub fn leave_user(&self, user_id: Id) -> Option<Departure> { |
| 379 | let mut inner = self.0.lock().unwrap(); | 374 | let mut inner = self.0.lock().unwrap(); |
| 380 | let id = inner.seat_conn(user_id)?; | 375 | let id = inner.seat_conn(user_id)?; |
| 381 | 376 | ||
| 382 | inner.take(id, true, false) | 377 | inner.take(id, true, false) |
| 383 | } | 378 | } |
| 384 | 379 | ||
| 385 | - pub fn leave_room(&self, community_id: &str, user_id: &str) -> Option<Departure> { | 380 | + pub fn leave_room(&self, community_id: Id, user_id: Id) -> Option<Departure> { |
| 386 | let mut inner = self.0.lock().unwrap(); | 381 | let mut inner = self.0.lock().unwrap(); |
| 387 | let id = inner.seat_conn(user_id)?; | 382 | let id = inner.seat_conn(user_id)?; |
| 388 | - if inner.seat_of.get(&id).map(String::as_str) != Some(community_id) { | 383 | + if inner.seat_of.get(&id) != Some(&community_id) { |
| 389 | return None; | 384 | return None; |
| 390 | } | 385 | } |
| 391 | 386 | ||
| 392 | inner.take(id, true, false) | 387 | inner.take(id, true, false) |
| 393 | } | 388 | } |
| 394 | 389 | ||
| 395 | - pub fn close_room(&self, community_id: &str) -> Vec<Departure> { | 390 | + pub fn close_room(&self, community_id: Id) -> Vec<Departure> { |
| 396 | let mut inner = self.0.lock().unwrap(); | 391 | let mut inner = self.0.lock().unwrap(); |
| 397 | let ids: Vec<ConnId> = inner | 392 | let ids: Vec<ConnId> = inner |
| 398 | .rooms | 393 | .rooms |
| 399 | - .get(community_id) | 394 | + .get(&community_id) |
| 400 | .map(|room| room.seats.keys().copied().collect()) | 395 | .map(|room| room.seats.keys().copied().collect()) |
| 401 | .unwrap_or_default(); | 396 | .unwrap_or_default(); |
| 402 | 397 | ||
| @@ -409,24 +404,24 @@ impl Rooms { | |||
| 409 | .collect() | 404 | .collect() |
| 410 | } | 405 | } |
| 411 | 406 | ||
| 412 | - pub fn decline(&self, community_id: &str) { | 407 | + pub fn decline(&self, community_id: Id) { |
| 413 | - if let Some(room) = self.0.lock().unwrap().rooms.get_mut(community_id) | 408 | + if let Some(room) = self.0.lock().unwrap().rooms.get_mut(&community_id) |
| 414 | && matches!(room.outcome, Outcome::Ringing) | 409 | && matches!(room.outcome, Outcome::Ringing) |
| 415 | { | 410 | { |
| 416 | room.outcome = Outcome::Declined; | 411 | room.outcome = Outcome::Declined; |
| 417 | } | 412 | } |
| 418 | } | 413 | } |
| 419 | 414 | ||
| 420 | - pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> { | 415 | + pub fn set_muted(&self, user_id: Id, muted: bool) -> Option<Id> { |
| 421 | let mut inner = self.0.lock().unwrap(); | 416 | let mut inner = self.0.lock().unwrap(); |
| 422 | let id = inner.seat_conn(user_id)?; | 417 | let id = inner.seat_conn(user_id)?; |
| 423 | let (community_id, room) = inner.seat_mut(id)?; | 418 | let (community_id, room) = inner.seat_mut(id)?; |
| 424 | room.seats.get_mut(&id)?.muted = muted; | 419 | room.seats.get_mut(&id)?.muted = muted; |
| 425 | 420 | ||
| 426 | - Some(community_id.to_string()) | 421 | + Some(community_id) |
| 427 | } | 422 | } |
| 428 | 423 | ||
| 429 | - pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<Departure> { | 424 | + pub fn set_ghost(&self, user_id: Id, ghost: bool) -> Option<Departure> { |
| 430 | let mut inner = self.0.lock().unwrap(); | 425 | let mut inner = self.0.lock().unwrap(); |
| 431 | let id = inner.seat_conn(user_id)?; | 426 | let id = inner.seat_conn(user_id)?; |
| 432 | let (community_id, room) = inner.seat_mut(id)?; | 427 | let (community_id, room) = inner.seat_mut(id)?; |
| @@ -453,8 +448,8 @@ impl Rooms { | |||
| 453 | .flatten(); | 448 | .flatten(); |
| 454 | 449 | ||
| 455 | Some(Departure { | 450 | Some(Departure { |
| 456 | - community_id: community_id.to_string(), | 451 | + community_id, |
| 457 | - user_id: user_id.to_string(), | 452 | + user_id, |
| 458 | ghost_seconds, | 453 | ghost_seconds, |
| 459 | call_log, | 454 | call_log, |
| 460 | shares, | 455 | shares, |
| @@ -463,32 +458,32 @@ impl Rooms { | |||
| 463 | }) | 458 | }) |
| 464 | } | 459 | } |
| 465 | 460 | ||
| 466 | - pub fn room_of(&self, user_id: &str) -> Option<String> { | 461 | + pub fn room_of(&self, user_id: Id) -> Option<Id> { |
| 467 | let inner = self.0.lock().unwrap(); | 462 | let inner = self.0.lock().unwrap(); |
| 468 | 463 | ||
| 469 | - inner.seat_of.get(&inner.seat_conn(user_id)?).cloned() | 464 | + inner.seat_of.get(&inner.seat_conn(user_id)?).copied() |
| 470 | } | 465 | } |
| 471 | 466 | ||
| 472 | - pub fn room_of_conn(&self, id: ConnId) -> Option<String> { | 467 | + pub fn room_of_conn(&self, id: ConnId) -> Option<Id> { |
| 473 | - self.0.lock().unwrap().seat_of.get(&id).cloned() | 468 | + self.0.lock().unwrap().seat_of.get(&id).copied() |
| 474 | } | 469 | } |
| 475 | 470 | ||
| 476 | - pub fn room_users(&self, community_id: &str) -> Vec<String> { | 471 | + pub fn room_users(&self, community_id: Id) -> Vec<Id> { |
| 477 | self.0 | 472 | self.0 |
| 478 | .lock() | 473 | .lock() |
| 479 | .unwrap() | 474 | .unwrap() |
| 480 | .rooms | 475 | .rooms |
| 481 | - .get(community_id) | 476 | + .get(&community_id) |
| 482 | .map(|room| room.user_ids(|_| true)) | 477 | .map(|room| room.user_ids(|_| true)) |
| 483 | .unwrap_or_default() | 478 | .unwrap_or_default() |
| 484 | } | 479 | } |
| 485 | 480 | ||
| 486 | - pub fn participants(&self, community_id: &str) -> Vec<String> { | 481 | + pub fn participants(&self, community_id: Id) -> Vec<Id> { |
| 487 | self.0 | 482 | self.0 |
| 488 | .lock() | 483 | .lock() |
| 489 | .unwrap() | 484 | .unwrap() |
| 490 | .rooms | 485 | .rooms |
| 491 | - .get(community_id) | 486 | + .get(&community_id) |
| 492 | .map(|room| room.user_ids(|seat| !seat.ghost)) | 487 | .map(|room| room.user_ids(|seat| !seat.ghost)) |
| 493 | .unwrap_or_default() | 488 | .unwrap_or_default() |
| 494 | } | 489 | } |
| @@ -497,7 +492,7 @@ impl Rooms { | |||
| 497 | self.0.lock().unwrap().seat_of.len() | 492 | self.0.lock().unwrap().seat_of.len() |
| 498 | } | 493 | } |
| 499 | 494 | ||
| 500 | - pub fn list(&self) -> Vec<(String, Vec<String>, Vec<String>)> { | 495 | + pub fn list(&self) -> Vec<(Id, Vec<Id>, Vec<Id>)> { |
| 501 | self.0 | 496 | self.0 |
| 502 | .lock() | 497 | .lock() |
| 503 | .unwrap() | 498 | .unwrap() |
| @@ -505,7 +500,7 @@ impl Rooms { | |||
| 505 | .iter() | 500 | .iter() |
| 506 | .map(|(community_id, room)| { | 501 | .map(|(community_id, room)| { |
| 507 | ( | 502 | ( |
| 508 | - community_id.clone(), | 503 | + *community_id, |
| 509 | room.user_ids(|_| true), | 504 | room.user_ids(|_| true), |
| 510 | room.user_ids(|seat| seat.ghost), | 505 | room.user_ids(|seat| seat.ghost), |
| 511 | ) | 506 | ) |
| @@ -513,9 +508,9 @@ impl Rooms { | |||
| 513 | .collect() | 508 | .collect() |
| 514 | } | 509 | } |
| 515 | 510 | ||
| 516 | - pub fn shares(&self, community_id: &str) -> Vec<Share> { | 511 | + pub fn shares(&self, community_id: Id) -> Vec<Share> { |
| 517 | let inner = self.0.lock().unwrap(); | 512 | let inner = self.0.lock().unwrap(); |
| 518 | - let Some(room) = inner.rooms.get(community_id) else { | 513 | + let Some(room) = inner.rooms.get(&community_id) else { |
| 519 | return Vec::new(); | 514 | return Vec::new(); |
| 520 | }; | 515 | }; |
| 521 | 516 | ||
| @@ -523,7 +518,7 @@ impl Rooms { | |||
| 523 | .values() | 518 | .values() |
| 524 | .flat_map(|seat| { | 519 | .flat_map(|seat| { |
| 525 | seat.shares.iter().map(|(kind, sharing)| Share { | 520 | seat.shares.iter().map(|(kind, sharing)| Share { |
| 526 | - user_id: seat.user_id.clone(), | 521 | + user_id: seat.user_id, |
| 527 | kind: *kind, | 522 | kind: *kind, |
| 528 | source: sharing.source.clone(), | 523 | source: sharing.source.clone(), |
| 529 | }) | 524 | }) |
| @@ -537,7 +532,7 @@ impl Rooms { | |||
| 537 | let seat = room.seats.get_mut(&id)?; | 532 | let seat = room.seats.get_mut(&id)?; |
| 538 | let sharer = Sharer { | 533 | let sharer = Sharer { |
| 539 | conn: id, | 534 | conn: id, |
| 540 | - user_id: &seat.user_id, | 535 | + user_id: seat.user_id, |
| 541 | community_id, | 536 | community_id, |
| 542 | kind, | 537 | kind, |
| 543 | }; | 538 | }; |
| @@ -550,18 +545,18 @@ impl Rooms { | |||
| 550 | Some(reroute(&sharer, sharing)) | 545 | Some(reroute(&sharer, sharing)) |
| 551 | } | 546 | } |
| 552 | 547 | ||
| 553 | - pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option<String> { | 548 | + pub fn stop_share(&self, id: ConnId, kind: Kind) -> Option<Id> { |
| 554 | let mut inner = self.0.lock().unwrap(); | 549 | let mut inner = self.0.lock().unwrap(); |
| 555 | let (community_id, room) = inner.seat_mut(id)?; | 550 | let (community_id, room) = inner.seat_mut(id)?; |
| 556 | room.seats.get_mut(&id)?.shares.remove(&kind)?; | 551 | room.seats.get_mut(&id)?.shares.remove(&kind)?; |
| 557 | 552 | ||
| 558 | - Some(community_id.to_string()) | 553 | + Some(community_id) |
| 559 | } | 554 | } |
| 560 | 555 | ||
| 561 | pub fn watch( | 556 | pub fn watch( |
| 562 | &self, | 557 | &self, |
| 563 | id: ConnId, | 558 | id: ConnId, |
| 564 | - sharer_id: &str, | 559 | + sharer_id: Id, |
| 565 | kind: Kind, | 560 | kind: Kind, |
| 566 | quality: Quality, | 561 | quality: Quality, |
| 567 | decode: &[Codec], | 562 | decode: &[Codec], |
| @@ -570,13 +565,13 @@ impl Rooms { | |||
| 570 | let sharer_conn = inner.seat_conn(sharer_id)?; | 565 | let sharer_conn = inner.seat_conn(sharer_id)?; |
| 571 | let (_, room) = inner.seat_mut(id)?; | 566 | let (_, room) = inner.seat_mut(id)?; |
| 572 | let viewer_seat = room.seats.get(&id)?; | 567 | let viewer_seat = room.seats.get(&id)?; |
| 573 | - let (viewer_id, connection) = (viewer_seat.user_id.clone(), viewer_seat.connection.clone()); | 568 | + let (viewer_id, connection) = (viewer_seat.user_id, viewer_seat.connection.clone()); |
| 574 | let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; | 569 | let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; |
| 575 | let before = sharing.layers(); | 570 | let before = sharing.layers(); |
| 576 | let used: Vec<Layer> = before.iter().copied().collect(); | 571 | let used: Vec<Layer> = before.iter().copied().collect(); |
| 577 | let layer = choose(&sharing.source, quality, decode, &used)?; | 572 | let layer = choose(&sharing.source, quality, decode, &used)?; |
| 578 | let forward = sharing | 573 | let forward = sharing |
| 579 | - .viewer(&viewer_id) | 574 | + .viewer(viewer_id) |
| 580 | .map_or(Forward::Waiting(layer), |viewer| { | 575 | .map_or(Forward::Waiting(layer), |viewer| { |
| 581 | viewer.forward.retarget(layer) | 576 | viewer.forward.retarget(layer) |
| 582 | }); | 577 | }); |
| @@ -597,27 +592,27 @@ impl Rooms { | |||
| 597 | Some(broadcasts) | 592 | Some(broadcasts) |
| 598 | } | 593 | } |
| 599 | 594 | ||
| 600 | - pub fn unwatch(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option<Broadcast> { | 595 | + pub fn unwatch(&self, id: ConnId, sharer_id: Id, kind: Kind) -> Option<Broadcast> { |
| 601 | let mut inner = self.0.lock().unwrap(); | 596 | let mut inner = self.0.lock().unwrap(); |
| 602 | let sharer_conn = inner.seat_conn(sharer_id)?; | 597 | let sharer_conn = inner.seat_conn(sharer_id)?; |
| 603 | let (_, room) = inner.seat_mut(id)?; | 598 | let (_, room) = inner.seat_mut(id)?; |
| 604 | - let viewer_id = room.seats.get(&id)?.user_id.clone(); | 599 | + let viewer_id = room.seats.get(&id)?.user_id; |
| 605 | let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; | 600 | let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; |
| 606 | 601 | ||
| 607 | - remove_viewer(sharer_conn, kind, sharing, &viewer_id) | 602 | + remove_viewer(sharer_conn, kind, sharing, viewer_id) |
| 608 | } | 603 | } |
| 609 | 604 | ||
| 610 | - pub fn keyframe(&self, id: ConnId, sharer_id: &str, kind: Kind) -> Option<Broadcast> { | 605 | + pub fn keyframe(&self, id: ConnId, sharer_id: Id, kind: Kind) -> Option<Broadcast> { |
| 611 | let mut inner = self.0.lock().unwrap(); | 606 | let mut inner = self.0.lock().unwrap(); |
| 612 | let sharer_conn = inner.seat_conn(sharer_id)?; | 607 | let sharer_conn = inner.seat_conn(sharer_id)?; |
| 613 | let (_, room) = inner.seat_mut(id)?; | 608 | let (_, room) = inner.seat_mut(id)?; |
| 614 | - let viewer_id = room.seats.get(&id)?.user_id.clone(); | 609 | + let viewer_id = room.seats.get(&id)?.user_id; |
| 615 | let viewer = room | 610 | let viewer = room |
| 616 | .seats | 611 | .seats |
| 617 | .get(&sharer_conn)? | 612 | .get(&sharer_conn)? |
| 618 | .shares | 613 | .shares |
| 619 | .get(&kind)? | 614 | .get(&kind)? |
| 620 | - .viewer(&viewer_id)?; | 615 | + .viewer(viewer_id)?; |
| 621 | 616 | ||
| 622 | Some(Broadcast::media( | 617 | Some(Broadcast::media( |
| 623 | sharer_conn, | 618 | sharer_conn, |
| @@ -655,8 +650,8 @@ fn relay_voice(room: &Room, id: ConnId, seq: u32, packet: &[u8]) { | |||
| 655 | } | 650 | } |
| 656 | let mut echo = Vec::new(); | 651 | let mut echo = Vec::new(); |
| 657 | Packet::Voice { seq, opus: &[] }.encode(&mut echo); | 652 | Packet::Voice { seq, opus: &[] }.encode(&mut echo); |
| 658 | - datagram::send(&sender.connection, relayed(&sender.uuid, &echo)); | 653 | + datagram::send(&sender.connection, relayed(&sender.prefix, &echo)); |
| 659 | - let bytes = relayed(&sender.uuid, packet); | 654 | + let bytes = relayed(&sender.prefix, packet); |
| 660 | for (other_id, seat) in &room.seats { | 655 | for (other_id, seat) in &room.seats { |
| 661 | if *other_id != id { | 656 | if *other_id != id { |
| 662 | datagram::send(&seat.connection, bytes.clone()); | 657 | datagram::send(&seat.connection, bytes.clone()); |
| @@ -671,7 +666,7 @@ fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) { | |||
| 671 | let Some(sharing) = seat.shares.get(&Kind::Screen) else { | 666 | let Some(sharing) = seat.shares.get(&Kind::Screen) else { |
| 672 | return; | 667 | return; |
| 673 | }; | 668 | }; |
| 674 | - let bytes = relayed(&seat.uuid, packet); | 669 | + let bytes = relayed(&seat.prefix, packet); |
| 675 | for viewer in &sharing.viewers { | 670 | for viewer in &sharing.viewers { |
| 676 | datagram::send(&viewer.connection, bytes.clone()); | 671 | datagram::send(&viewer.connection, bytes.clone()); |
| 677 | } | 672 | } |
| @@ -691,7 +686,7 @@ fn relay_video( | |||
| 691 | let Some(sharing) = seat.shares.get_mut(&kind) else { | 686 | let Some(sharing) = seat.shares.get_mut(&kind) else { |
| 692 | return Vec::new(); | 687 | return Vec::new(); |
| 693 | }; | 688 | }; |
| 694 | - let bytes = relayed(&seat.uuid, packet); | 689 | + let bytes = relayed(&seat.prefix, packet); |
| 695 | let before = keyframe.then(|| sharing.layers()); | 690 | let before = keyframe.then(|| sharing.layers()); |
| 696 | for viewer in &mut sharing.viewers { | 691 | for viewer in &mut sharing.viewers { |
| 697 | if keyframe { | 692 | if keyframe { |
crates/server/src/server_ban.rsdeleted+0 -80
| @@ -1,80 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - error::Error as CommonError, | ||
| 3 | - model::{ServerBan, ServerBanKind}, | ||
| 4 | -}; | ||
| 5 | -use turso::Connection; | ||
| 6 | - | ||
| 7 | -use crate::{ | ||
| 8 | - database::{self, new_id}, | ||
| 9 | - error::ServerError, | ||
| 10 | -}; | ||
| 11 | - | ||
| 12 | -pub async fn insert( | ||
| 13 | - kind: ServerBanKind, | ||
| 14 | - value: &str, | ||
| 15 | - reason: Option<&str>, | ||
| 16 | - created_by: &str, | ||
| 17 | - conn: &Connection, | ||
| 18 | -) -> Result<(), ServerError> { | ||
| 19 | - conn.execute( | ||
| 20 | - "INSERT INTO server_ban (id, kind, value, reason, created_by) | ||
| 21 | - SELECT ?1, ?2, ?3, ?4, ?5 WHERE NOT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?2 AND value = ?3)", | ||
| 22 | - (new_id(), kind.as_str(), value, reason, created_by), | ||
| 23 | - ) | ||
| 24 | - .await?; | ||
| 25 | - | ||
| 26 | - Ok(()) | ||
| 27 | -} | ||
| 28 | - | ||
| 29 | -pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, ServerError> { | ||
| 30 | - let mut rows = conn | ||
| 31 | - .query( | ||
| 32 | - "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", | ||
| 33 | - (), | ||
| 34 | - ) | ||
| 35 | - .await?; | ||
| 36 | - | ||
| 37 | - let mut bans = Vec::new(); | ||
| 38 | - while let Some(row) = rows.next().await? { | ||
| 39 | - let text: String = row.get(1)?; | ||
| 40 | - bans.push(ServerBan { | ||
| 41 | - id: row.get(0)?, | ||
| 42 | - kind: ServerBanKind::parse(&text).ok_or(CommonError::Server)?, | ||
| 43 | - value: row.get(2)?, | ||
| 44 | - reason: row.get(3)?, | ||
| 45 | - }); | ||
| 46 | - } | ||
| 47 | - | ||
| 48 | - Ok(bans) | ||
| 49 | -} | ||
| 50 | - | ||
| 51 | -async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 52 | - database::exists( | ||
| 53 | - conn, | ||
| 54 | - "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", | ||
| 55 | - (kind.as_str(), value), | ||
| 56 | - ) | ||
| 57 | - .await | ||
| 58 | -} | ||
| 59 | - | ||
| 60 | -pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 61 | - exists( | ||
| 62 | - ServerBanKind::Username, | ||
| 63 | - &username.to_ascii_lowercase(), | ||
| 64 | - conn, | ||
| 65 | - ) | ||
| 66 | - .await | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -pub async fn ip_banned(ip: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 70 | - exists(ServerBanKind::Ip, ip, conn).await | ||
| 71 | -} | ||
| 72 | - | ||
| 73 | -pub async fn remove(id: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 74 | - let mut rows = conn | ||
| 75 | - .query("DELETE FROM server_ban WHERE id = ?1 RETURNING id", (id,)) | ||
| 76 | - .await?; | ||
| 77 | - rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 78 | - | ||
| 79 | - Ok(()) | ||
| 80 | -} | ||
crates/server/src/server_settings.rsdeleted+0 -71
| @@ -1,71 +0,0 @@ | |||
| 1 | -use common::model::ServerSettings; | ||
| 2 | -use turso::Connection; | ||
| 3 | - | ||
| 4 | -use crate::{error::ServerError, user}; | ||
| 5 | - | ||
| 6 | -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"; | ||
| 7 | - | ||
| 8 | -fn assignments() -> String { | ||
| 9 | - COLUMNS | ||
| 10 | - .split(", ") | ||
| 11 | - .enumerate() | ||
| 12 | - .map(|(index, column)| format!("{column} = ?{}", index + 1)) | ||
| 13 | - .collect::<Vec<_>>() | ||
| 14 | - .join(", ") | ||
| 15 | -} | ||
| 16 | - | ||
| 17 | -pub async fn read(conn: &Connection) -> Result<ServerSettings, ServerError> { | ||
| 18 | - let mut rows = conn | ||
| 19 | - .query( | ||
| 20 | - &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"), | ||
| 21 | - (), | ||
| 22 | - ) | ||
| 23 | - .await?; | ||
| 24 | - let row = rows | ||
| 25 | - .next() | ||
| 26 | - .await? | ||
| 27 | - .ok_or(turso::Error::QueryReturnedNoRows)?; | ||
| 28 | - let int = |index: usize| -> Result<i64, ServerError> { Ok(row.get(index)?) }; | ||
| 29 | - | ||
| 30 | - Ok(ServerSettings { | ||
| 31 | - name: row.get(0)?, | ||
| 32 | - registration_open: user::bool_at(&row, 1)?, | ||
| 33 | - max_attachment_bytes: int(2)? as u64, | ||
| 34 | - maintenance: user::bool_at(&row, 3)?, | ||
| 35 | - user_quota_bytes: int(4)? as u64, | ||
| 36 | - community_quota_bytes: int(5)? as u64, | ||
| 37 | - message_retention_days: int(6)? as u32, | ||
| 38 | - attachment_retention_days: int(7)? as u32, | ||
| 39 | - announcement: row.get(8)?, | ||
| 40 | - max_communities_per_user: int(9)? as u32, | ||
| 41 | - max_message_length: int(10)? as u32, | ||
| 42 | - max_avatar_bytes: int(11)? as u64, | ||
| 43 | - messages_per_minute: int(12)? as u32, | ||
| 44 | - logins_per_minute: int(13)? as u32, | ||
| 45 | - }) | ||
| 46 | -} | ||
| 47 | - | ||
| 48 | -pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), ServerError> { | ||
| 49 | - conn.execute( | ||
| 50 | - &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()), | ||
| 51 | - ( | ||
| 52 | - settings.name.as_str(), | ||
| 53 | - i64::from(settings.registration_open), | ||
| 54 | - settings.max_attachment_bytes as i64, | ||
| 55 | - i64::from(settings.maintenance), | ||
| 56 | - settings.user_quota_bytes as i64, | ||
| 57 | - settings.community_quota_bytes as i64, | ||
| 58 | - i64::from(settings.message_retention_days), | ||
| 59 | - i64::from(settings.attachment_retention_days), | ||
| 60 | - settings.announcement.as_str(), | ||
| 61 | - i64::from(settings.max_communities_per_user), | ||
| 62 | - i64::from(settings.max_message_length), | ||
| 63 | - settings.max_avatar_bytes as i64, | ||
| 64 | - i64::from(settings.messages_per_minute), | ||
| 65 | - i64::from(settings.logins_per_minute), | ||
| 66 | - ), | ||
| 67 | - ) | ||
| 68 | - .await?; | ||
| 69 | - | ||
| 70 | - Ok(()) | ||
| 71 | -} | ||
crates/server/src/stats.rsdeleted+0 -61
| @@ -1,61 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - model::DayStat, | ||
| 3 | - time::{self, DAY_MILLIS}, | ||
| 4 | -}; | ||
| 5 | -use turso::Connection; | ||
| 6 | - | ||
| 7 | -use crate::{database, error::ServerError, user}; | ||
| 8 | - | ||
| 9 | -const MAXIMUM_DAYS: u32 = 90; | ||
| 10 | - | ||
| 11 | -pub async fn mark_active(user_id: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 12 | - if user::is_ghost(user_id, conn).await? { | ||
| 13 | - return Ok(()); | ||
| 14 | - } | ||
| 15 | - let day = (time::now_ms() / DAY_MILLIS) as i64; | ||
| 16 | - conn.execute( | ||
| 17 | - "INSERT OR IGNORE INTO daily_active (day, user_id) VALUES (?1, ?2)", | ||
| 18 | - (day, user_id), | ||
| 19 | - ) | ||
| 20 | - .await?; | ||
| 21 | - | ||
| 22 | - Ok(()) | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, ServerError> { | ||
| 26 | - let days = u64::from(days.clamp(1, MAXIMUM_DAYS)); | ||
| 27 | - let today = time::now_ms() / DAY_MILLIS; | ||
| 28 | - let mut stats = Vec::new(); | ||
| 29 | - | ||
| 30 | - for day in (today + 1 - days)..=today { | ||
| 31 | - let start = time::id_bound(day * DAY_MILLIS); | ||
| 32 | - let end = time::id_bound((day + 1) * DAY_MILLIS); | ||
| 33 | - let active_users = count( | ||
| 34 | - conn, | ||
| 35 | - "SELECT COUNT(*) FROM daily_active WHERE day = ?1", | ||
| 36 | - (day as i64,), | ||
| 37 | - ) | ||
| 38 | - .await?; | ||
| 39 | - let messages = count( | ||
| 40 | - conn, | ||
| 41 | - "SELECT COUNT(*) FROM message WHERE id >= ?1 AND id < ?2", | ||
| 42 | - (start.as_str(), end.as_str()), | ||
| 43 | - ) | ||
| 44 | - .await?; | ||
| 45 | - stats.push(DayStat { | ||
| 46 | - day, | ||
| 47 | - active_users, | ||
| 48 | - messages, | ||
| 49 | - }); | ||
| 50 | - } | ||
| 51 | - | ||
| 52 | - Ok(stats) | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -async fn count( | ||
| 56 | - conn: &Connection, | ||
| 57 | - sql: &str, | ||
| 58 | - params: impl turso::IntoParams, | ||
| 59 | -) -> Result<u64, ServerError> { | ||
| 60 | - Ok(database::scalar_i64(conn, sql, params).await? as u64) | ||
| 61 | -} | ||
crates/server/src/test.rsmodified+3 -3
| @@ -1,9 +1,9 @@ | |||
| 1 | use std::path::PathBuf; | 1 | use std::path::PathBuf; |
| 2 | 2 | ||
| 3 | -use crate::database::{self, DB}; | 3 | +use crate::db::Db; |
| 4 | 4 | ||
| 5 | -pub async fn get_database() -> DB { | 5 | +pub async fn db() -> Db { |
| 6 | - database::open(":memory:").await.unwrap() | 6 | + Db::open(":memory:").await.unwrap() |
| 7 | } | 7 | } |
| 8 | 8 | ||
| 9 | pub fn directory() -> PathBuf { | 9 | pub fn directory() -> PathBuf { |
crates/server/src/user.rsdeleted+0 -555
| @@ -1,555 +0,0 @@ | |||
| 1 | -use common::{ | ||
| 2 | - constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, | ||
| 3 | - error::{Error as CommonError, Field, Problem}, | ||
| 4 | - model::{Account, Presence, Role, User}, | ||
| 5 | - permission, time, | ||
| 6 | - validate::{validate_avatar_size, validate_status, validate_username}, | ||
| 7 | -}; | ||
| 8 | -use image::ImageFormat; | ||
| 9 | -use turso::{Connection, Row}; | ||
| 10 | - | ||
| 11 | -use crate::{ | ||
| 12 | - database::{self, new_id}, | ||
| 13 | - error::ServerError, | ||
| 14 | -}; | ||
| 15 | - | ||
| 16 | -pub fn user_columns(alias: &str) -> String { | ||
| 17 | - format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") | ||
| 18 | -} | ||
| 19 | - | ||
| 20 | -pub fn from_row_at(row: &Row, start: usize) -> Result<Option<User>, ServerError> { | ||
| 21 | - let Some(id) = row.get::<Option<String>>(start)? else { | ||
| 22 | - return Ok(None); | ||
| 23 | - }; | ||
| 24 | - let role: String = row.get(start + 2)?; | ||
| 25 | - | ||
| 26 | - Ok(Some(User { | ||
| 27 | - id, | ||
| 28 | - username: row.get(start + 1)?, | ||
| 29 | - role: Role::parse(&role).ok_or(CommonError::Server)?, | ||
| 30 | - status: row.get(start + 3)?, | ||
| 31 | - avatar_id: row.get(start + 4)?, | ||
| 32 | - })) | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -pub fn from_row(row: &Row) -> Result<User, ServerError> { | ||
| 36 | - Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?) | ||
| 37 | -} | ||
| 38 | - | ||
| 39 | -pub fn bool_at(row: &Row, index: usize) -> Result<bool, ServerError> { | ||
| 40 | - let flag: i64 = row.get(index)?; | ||
| 41 | - | ||
| 42 | - Ok(flag != 0) | ||
| 43 | -} | ||
| 44 | - | ||
| 45 | -async fn one( | ||
| 46 | - sql: &str, | ||
| 47 | - params: impl turso::IntoParams, | ||
| 48 | - conn: &Connection, | ||
| 49 | -) -> Result<User, ServerError> { | ||
| 50 | - let mut rows = conn.query(sql, params).await?; | ||
| 51 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 52 | - | ||
| 53 | - from_row(&row) | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -async fn set( | ||
| 57 | - column: &str, | ||
| 58 | - params: impl turso::IntoParams, | ||
| 59 | - conn: &Connection, | ||
| 60 | -) -> Result<(), ServerError> { | ||
| 61 | - conn.execute( | ||
| 62 | - &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"), | ||
| 63 | - params, | ||
| 64 | - ) | ||
| 65 | - .await?; | ||
| 66 | - | ||
| 67 | - Ok(()) | ||
| 68 | -} | ||
| 69 | - | ||
| 70 | -async fn set_returning( | ||
| 71 | - column: &str, | ||
| 72 | - params: impl turso::IntoParams, | ||
| 73 | - conn: &Connection, | ||
| 74 | -) -> Result<User, ServerError> { | ||
| 75 | - one( | ||
| 76 | - &format!( | ||
| 77 | - "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}", | ||
| 78 | - user_columns("user") | ||
| 79 | - ), | ||
| 80 | - params, | ||
| 81 | - conn, | ||
| 82 | - ) | ||
| 83 | - .await | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -pub async fn create( | ||
| 87 | - username: &str, | ||
| 88 | - password_hash: &str, | ||
| 89 | - conn: &Connection, | ||
| 90 | -) -> Result<User, ServerError> { | ||
| 91 | - one( | ||
| 92 | - &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")), | ||
| 93 | - ( | ||
| 94 | - new_id(), | ||
| 95 | - username, | ||
| 96 | - password_hash, | ||
| 97 | - Role::User.as_str(), | ||
| 98 | - Role::Builder.as_str(), | ||
| 99 | - ), | ||
| 100 | - conn, | ||
| 101 | - ) | ||
| 102 | - .await | ||
| 103 | -} | ||
| 104 | - | ||
| 105 | -pub async fn read(user_id: &str, conn: &Connection) -> Result<User, ServerError> { | ||
| 106 | - one( | ||
| 107 | - &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), | ||
| 108 | - (user_id,), | ||
| 109 | - conn, | ||
| 110 | - ) | ||
| 111 | - .await | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -pub async fn any(conn: &Connection) -> Result<bool, ServerError> { | ||
| 115 | - database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await | ||
| 116 | -} | ||
| 117 | - | ||
| 118 | -pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, ServerError> { | ||
| 119 | - let mut rows = conn | ||
| 120 | - .query( | ||
| 121 | - &format!( | ||
| 122 | - "SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE", | ||
| 123 | - user_columns("user") | ||
| 124 | - ), | ||
| 125 | - (username,), | ||
| 126 | - ) | ||
| 127 | - .await?; | ||
| 128 | - | ||
| 129 | - rows.next().await?.as_ref().map(from_row).transpose() | ||
| 130 | -} | ||
| 131 | - | ||
| 132 | -pub async fn is_taken( | ||
| 133 | - username: &str, | ||
| 134 | - except_id: Option<&str>, | ||
| 135 | - conn: &Connection, | ||
| 136 | -) -> Result<bool, ServerError> { | ||
| 137 | - Ok(by_username(username, conn) | ||
| 138 | - .await? | ||
| 139 | - .is_some_and(|existing| Some(existing.id.as_str()) != except_id)) | ||
| 140 | -} | ||
| 141 | - | ||
| 142 | -pub async fn by_session_token(token: &str, conn: &Connection) -> Result<User, ServerError> { | ||
| 143 | - let mut rows = conn | ||
| 144 | - .query( | ||
| 145 | - &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user_columns("user")), | ||
| 146 | - (token,), | ||
| 147 | - ) | ||
| 148 | - .await?; | ||
| 149 | - let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?; | ||
| 150 | - | ||
| 151 | - from_row(&row) | ||
| 152 | -} | ||
| 153 | - | ||
| 154 | -pub async fn credentials( | ||
| 155 | - username: &str, | ||
| 156 | - conn: &Connection, | ||
| 157 | -) -> Result<Option<(User, String)>, ServerError> { | ||
| 158 | - let mut rows = conn | ||
| 159 | - .query( | ||
| 160 | - &format!( | ||
| 161 | - "SELECT {}, password_hash FROM user WHERE username = ?1", | ||
| 162 | - user_columns("user") | ||
| 163 | - ), | ||
| 164 | - (username,), | ||
| 165 | - ) | ||
| 166 | - .await?; | ||
| 167 | - let Some(row) = rows.next().await? else { | ||
| 168 | - return Ok(None); | ||
| 169 | - }; | ||
| 170 | - | ||
| 171 | - Ok(Some((from_row(&row)?, row.get(5)?))) | ||
| 172 | -} | ||
| 173 | - | ||
| 174 | -pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, ServerError> { | ||
| 175 | - validate_username(username)?; | ||
| 176 | - | ||
| 177 | - if is_taken(username, Some(user_id), conn).await? { | ||
| 178 | - return Err(CommonError::Taken.into()); | ||
| 179 | - } | ||
| 180 | - | ||
| 181 | - set_returning("username", (user_id, username), conn).await | ||
| 182 | -} | ||
| 183 | - | ||
| 184 | -pub async fn update_status( | ||
| 185 | - user_id: &str, | ||
| 186 | - status: &str, | ||
| 187 | - conn: &Connection, | ||
| 188 | -) -> Result<User, ServerError> { | ||
| 189 | - validate_status(status)?; | ||
| 190 | - | ||
| 191 | - set_returning("status", (user_id, status), conn).await | ||
| 192 | -} | ||
| 193 | - | ||
| 194 | -pub fn check_avatar(bytes: &[u8]) -> Result<(), ServerError> { | ||
| 195 | - validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; | ||
| 196 | - let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg).map_err(|_| { | ||
| 197 | - CommonError::Invalid { | ||
| 198 | - field: Field::Avatar, | ||
| 199 | - problem: Problem::NotJpeg, | ||
| 200 | - } | ||
| 201 | - })?; | ||
| 202 | - if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE { | ||
| 203 | - return Err(CommonError::Invalid { | ||
| 204 | - field: Field::Avatar, | ||
| 205 | - problem: Problem::Dimensions { | ||
| 206 | - expected: AVATAR_SIZE, | ||
| 207 | - }, | ||
| 208 | - } | ||
| 209 | - .into()); | ||
| 210 | - } | ||
| 211 | - | ||
| 212 | - Ok(()) | ||
| 213 | -} | ||
| 214 | - | ||
| 215 | -pub async fn set_avatar( | ||
| 216 | - user_id: &str, | ||
| 217 | - avatar: Option<&[u8]>, | ||
| 218 | - conn: &mut Connection, | ||
| 219 | -) -> Result<User, ServerError> { | ||
| 220 | - if let Some(bytes) = avatar { | ||
| 221 | - check_avatar(bytes)?; | ||
| 222 | - } | ||
| 223 | - | ||
| 224 | - let avatar_id = avatar.map(|_| new_id()); | ||
| 225 | - let tx = conn.transaction().await?; | ||
| 226 | - tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,)) | ||
| 227 | - .await?; | ||
| 228 | - if let (Some(avatar_id), Some(bytes)) = (&avatar_id, avatar) { | ||
| 229 | - tx.execute( | ||
| 230 | - "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)", | ||
| 231 | - (avatar_id.as_str(), user_id, bytes), | ||
| 232 | - ) | ||
| 233 | - .await?; | ||
| 234 | - } | ||
| 235 | - let user = set_avatar_id(user_id, avatar_id.as_deref(), &tx).await?; | ||
| 236 | - tx.commit().await?; | ||
| 237 | - | ||
| 238 | - Ok(user) | ||
| 239 | -} | ||
| 240 | - | ||
| 241 | -async fn set_avatar_id( | ||
| 242 | - user_id: &str, | ||
| 243 | - avatar_id: Option<&str>, | ||
| 244 | - conn: &Connection, | ||
| 245 | -) -> Result<User, ServerError> { | ||
| 246 | - set_returning("avatar_id", (user_id, avatar_id), conn).await | ||
| 247 | -} | ||
| 248 | - | ||
| 249 | -pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, ServerError> { | ||
| 250 | - let mut rows = conn | ||
| 251 | - .query( | ||
| 252 | - "SELECT data FROM avatar WHERE id = ?1 UNION ALL SELECT data FROM community_avatar WHERE id = ?1", | ||
| 253 | - (avatar_id,), | ||
| 254 | - ) | ||
| 255 | - .await?; | ||
| 256 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 257 | - | ||
| 258 | - Ok(row.get(0)?) | ||
| 259 | -} | ||
| 260 | - | ||
| 261 | -pub async fn set_role_by_id( | ||
| 262 | - user_id: &str, | ||
| 263 | - role: Role, | ||
| 264 | - conn: &Connection, | ||
| 265 | -) -> Result<User, ServerError> { | ||
| 266 | - set_returning("role", (user_id, role.as_str()), conn).await | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -pub async fn suspended( | ||
| 270 | - user_id: &str, | ||
| 271 | - conn: &Connection, | ||
| 272 | -) -> Result<Option<Option<u64>>, ServerError> { | ||
| 273 | - let mut rows = conn | ||
| 274 | - .query( | ||
| 275 | - "SELECT suspended, suspended_until FROM user WHERE id = ?1", | ||
| 276 | - (user_id,), | ||
| 277 | - ) | ||
| 278 | - .await?; | ||
| 279 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 280 | - let until: Option<u64> = row.get::<Option<i64>>(1)?.map(|until| until as u64); | ||
| 281 | - | ||
| 282 | - if bool_at(&row, 0)? { | ||
| 283 | - return Ok(Some(None)); | ||
| 284 | - } | ||
| 285 | - | ||
| 286 | - Ok(until.filter(|until| *until > time::now_ms()).map(Some)) | ||
| 287 | -} | ||
| 288 | - | ||
| 289 | -pub async fn set_timeout( | ||
| 290 | - user_id: &str, | ||
| 291 | - until: Option<u64>, | ||
| 292 | - conn: &Connection, | ||
| 293 | -) -> Result<(), ServerError> { | ||
| 294 | - set( | ||
| 295 | - "suspended_until", | ||
| 296 | - (user_id, until.map(|until| until as i64)), | ||
| 297 | - conn, | ||
| 298 | - ) | ||
| 299 | - .await | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), ServerError> { | ||
| 303 | - set("last_ip", (user_id, ip), conn).await | ||
| 304 | -} | ||
| 305 | - | ||
| 306 | -pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, ServerError> { | ||
| 307 | - let mut rows = conn | ||
| 308 | - .query("SELECT last_ip FROM user WHERE id = ?1", (user_id,)) | ||
| 309 | - .await?; | ||
| 310 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 311 | - | ||
| 312 | - Ok(row.get(0)?) | ||
| 313 | -} | ||
| 314 | - | ||
| 315 | -pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 316 | - database::ids( | ||
| 317 | - conn, | ||
| 318 | - "SELECT id FROM user WHERE role = ?1", | ||
| 319 | - (Role::Builder.as_str(),), | ||
| 320 | - ) | ||
| 321 | - .await | ||
| 322 | -} | ||
| 323 | - | ||
| 324 | -pub async fn set_suspended( | ||
| 325 | - user_id: &str, | ||
| 326 | - suspended: bool, | ||
| 327 | - conn: &Connection, | ||
| 328 | -) -> Result<(), ServerError> { | ||
| 329 | - set("suspended", (user_id, i64::from(suspended)), conn).await | ||
| 330 | -} | ||
| 331 | - | ||
| 332 | -pub async fn set_voice_muted( | ||
| 333 | - user_id: &str, | ||
| 334 | - muted: bool, | ||
| 335 | - conn: &Connection, | ||
| 336 | -) -> Result<(), ServerError> { | ||
| 337 | - set("voice_muted", (user_id, i64::from(muted)), conn).await | ||
| 338 | -} | ||
| 339 | - | ||
| 340 | -pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), ServerError> { | ||
| 341 | - set("ghost", (user_id, i64::from(ghost)), conn).await | ||
| 342 | -} | ||
| 343 | - | ||
| 344 | -pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 345 | - let mut rows = conn | ||
| 346 | - .query("SELECT ghost FROM user WHERE id = ?1", (user_id,)) | ||
| 347 | - .await?; | ||
| 348 | - let Some(row) = rows.next().await? else { | ||
| 349 | - return Ok(false); | ||
| 350 | - }; | ||
| 351 | - | ||
| 352 | - bool_at(&row, 0) | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -pub async fn presence(user_id: &str, conn: &Connection) -> Result<Presence, ServerError> { | ||
| 356 | - let mut rows = conn | ||
| 357 | - .query("SELECT presence FROM user WHERE id = ?1", (user_id,)) | ||
| 358 | - .await?; | ||
| 359 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 360 | - let text: String = row.get(0)?; | ||
| 361 | - | ||
| 362 | - Ok(Presence::parse(&text).ok_or(CommonError::Server)?) | ||
| 363 | -} | ||
| 364 | - | ||
| 365 | -pub async fn update_presence( | ||
| 366 | - user_id: &str, | ||
| 367 | - presence: Presence, | ||
| 368 | - conn: &Connection, | ||
| 369 | -) -> Result<(), ServerError> { | ||
| 370 | - set("presence", (user_id, presence.as_str()), conn).await | ||
| 371 | -} | ||
| 372 | - | ||
| 373 | -pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, ServerError> { | ||
| 374 | - let mut rows = conn | ||
| 375 | - .query( | ||
| 376 | - "SELECT voice_muted, role FROM user WHERE id = ?1", | ||
| 377 | - (user_id,), | ||
| 378 | - ) | ||
| 379 | - .await?; | ||
| 380 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 381 | - let role: String = row.get(1)?; | ||
| 382 | - let builder = Role::parse(&role).is_some_and(permission::is_builder); | ||
| 383 | - | ||
| 384 | - Ok(bool_at(&row, 0)? && !builder) | ||
| 385 | -} | ||
| 386 | - | ||
| 387 | -pub async fn set_password_hash( | ||
| 388 | - user_id: &str, | ||
| 389 | - password_hash: &str, | ||
| 390 | - conn: &Connection, | ||
| 391 | -) -> Result<(), ServerError> { | ||
| 392 | - set("password_hash", (user_id, password_hash), conn).await | ||
| 393 | -} | ||
| 394 | - | ||
| 395 | -pub async fn all(conn: &Connection) -> Result<Vec<Account>, ServerError> { | ||
| 396 | - let mut rows = conn | ||
| 397 | - .query( | ||
| 398 | - &format!("SELECT {}, suspended, last_seen, suspended_until, ghost FROM user ORDER BY username COLLATE NOCASE", user_columns("user")), | ||
| 399 | - (), | ||
| 400 | - ) | ||
| 401 | - .await?; | ||
| 402 | - let mut accounts = Vec::new(); | ||
| 403 | - while let Some(row) = rows.next().await? { | ||
| 404 | - let last_seen: Option<i64> = row.get(6)?; | ||
| 405 | - let suspended_until: Option<i64> = row.get(7)?; | ||
| 406 | - accounts.push(Account { | ||
| 407 | - user: from_row(&row)?, | ||
| 408 | - suspended: bool_at(&row, 5)?, | ||
| 409 | - last_seen: last_seen.map(|millis| millis as u64), | ||
| 410 | - suspended_until: suspended_until.map(|millis| millis as u64), | ||
| 411 | - ghost: bool_at(&row, 8)?, | ||
| 412 | - }); | ||
| 413 | - } | ||
| 414 | - | ||
| 415 | - Ok(accounts) | ||
| 416 | -} | ||
| 417 | - | ||
| 418 | -pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, ServerError> { | ||
| 419 | - one( | ||
| 420 | - &format!( | ||
| 421 | - "DELETE FROM user WHERE id = ?1 RETURNING {}", | ||
| 422 | - user_columns("user") | ||
| 423 | - ), | ||
| 424 | - (user_id,), | ||
| 425 | - conn, | ||
| 426 | - ) | ||
| 427 | - .await | ||
| 428 | -} | ||
| 429 | - | ||
| 430 | -#[cfg(test)] | ||
| 431 | -mod tests { | ||
| 432 | - use std::io::Cursor; | ||
| 433 | - | ||
| 434 | - use common::{ | ||
| 435 | - constant::AVATAR_SIZE, | ||
| 436 | - error::{Error as CommonError, Field}, | ||
| 437 | - }; | ||
| 438 | - use image::{ImageFormat, RgbImage}; | ||
| 439 | - | ||
| 440 | - use crate::{database, error::ServerError, test, user}; | ||
| 441 | - | ||
| 442 | - fn jpeg(size: u32) -> Vec<u8> { | ||
| 443 | - let mut bytes = Cursor::new(Vec::new()); | ||
| 444 | - RgbImage::new(size, size) | ||
| 445 | - .write_to(&mut bytes, ImageFormat::Jpeg) | ||
| 446 | - .unwrap(); | ||
| 447 | - | ||
| 448 | - bytes.into_inner() | ||
| 449 | - } | ||
| 450 | - | ||
| 451 | - #[tokio::test] | ||
| 452 | - async fn set_avatar_checks_jpeg_size() { | ||
| 453 | - let db = test::get_database().await; | ||
| 454 | - let mut conn = database::connect(&db).await.unwrap(); | ||
| 455 | - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 456 | - | ||
| 457 | - let small = | ||
| 458 | - user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await; | ||
| 459 | - let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await; | ||
| 460 | - let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn) | ||
| 461 | - .await | ||
| 462 | - .unwrap(); | ||
| 463 | - | ||
| 464 | - assert!(matches!( | ||
| 465 | - small, | ||
| 466 | - Err(ServerError::Wire(CommonError::Invalid { | ||
| 467 | - field: Field::Avatar, | ||
| 468 | - .. | ||
| 469 | - })) | ||
| 470 | - )); | ||
| 471 | - assert!(matches!( | ||
| 472 | - not_jpeg, | ||
| 473 | - Err(ServerError::Wire(CommonError::Invalid { | ||
| 474 | - field: Field::Avatar, | ||
| 475 | - .. | ||
| 476 | - })) | ||
| 477 | - )); | ||
| 478 | - let avatar_id = valid.avatar_id.unwrap(); | ||
| 479 | - assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty()); | ||
| 480 | - } | ||
| 481 | - | ||
| 482 | - #[tokio::test] | ||
| 483 | - async fn create() { | ||
| 484 | - let db = test::get_database().await; | ||
| 485 | - let conn = database::connect(&db).await.unwrap(); | ||
| 486 | - | ||
| 487 | - let user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 488 | - | ||
| 489 | - assert_eq!("Tahinli", user.username); | ||
| 490 | - } | ||
| 491 | - | ||
| 492 | - #[tokio::test] | ||
| 493 | - async fn read() { | ||
| 494 | - let db = test::get_database().await; | ||
| 495 | - let conn = database::connect(&db).await.unwrap(); | ||
| 496 | - | ||
| 497 | - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 498 | - let searched_user = user::read(&created_user.id, &conn).await.unwrap(); | ||
| 499 | - | ||
| 500 | - assert_eq!(created_user, searched_user); | ||
| 501 | - } | ||
| 502 | - | ||
| 503 | - #[tokio::test] | ||
| 504 | - async fn read_by_username() { | ||
| 505 | - let db = test::get_database().await; | ||
| 506 | - let conn = database::connect(&db).await.unwrap(); | ||
| 507 | - | ||
| 508 | - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 509 | - let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 510 | - | ||
| 511 | - let searched_user = user::by_username("tahinli", &conn).await.unwrap(); | ||
| 512 | - | ||
| 513 | - assert_eq!(Some(created_user), searched_user); | ||
| 514 | - } | ||
| 515 | - | ||
| 516 | - #[tokio::test] | ||
| 517 | - async fn update() { | ||
| 518 | - let db = test::get_database().await; | ||
| 519 | - let conn = database::connect(&db).await.unwrap(); | ||
| 520 | - | ||
| 521 | - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 522 | - let updated_user = user::update(&created_user.id, "Not Tahinli", &conn) | ||
| 523 | - .await | ||
| 524 | - .unwrap(); | ||
| 525 | - let searched_user = user::read(&created_user.id, &conn).await.unwrap(); | ||
| 526 | - | ||
| 527 | - assert_eq!(created_user.id, searched_user.id); | ||
| 528 | - assert_eq!(updated_user, searched_user); | ||
| 529 | - assert_eq!("Not Tahinli", searched_user.username); | ||
| 530 | - } | ||
| 531 | - | ||
| 532 | - #[tokio::test] | ||
| 533 | - async fn update_on_missing_user() { | ||
| 534 | - let db = test::get_database().await; | ||
| 535 | - let conn = database::connect(&db).await.unwrap(); | ||
| 536 | - | ||
| 537 | - let updated_user = user::update("missing", "Not Tahinli", &conn).await; | ||
| 538 | - | ||
| 539 | - assert!(matches!( | ||
| 540 | - updated_user, | ||
| 541 | - Err(ServerError::Wire(CommonError::NotFound)) | ||
| 542 | - )); | ||
| 543 | - } | ||
| 544 | - | ||
| 545 | - #[tokio::test] | ||
| 546 | - async fn delete() { | ||
| 547 | - let db = test::get_database().await; | ||
| 548 | - let conn = database::connect(&db).await.unwrap(); | ||
| 549 | - | ||
| 550 | - let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 551 | - let deleted_user = user::delete(&created_user.id, &conn).await.unwrap(); | ||
| 552 | - | ||
| 553 | - assert_eq!(created_user, deleted_user); | ||
| 554 | - } | ||
| 555 | -} | ||
crates/server/src/user_community.rsdeleted+0 -411
| @@ -1,411 +0,0 @@ | |||
| 1 | -use std::collections::HashMap; | ||
| 2 | - | ||
| 3 | -use common::{ | ||
| 4 | - error::Error as CommonError, | ||
| 5 | - model::{Ban, Member, Rank, Unread, mentions}, | ||
| 6 | -}; | ||
| 7 | -use turso::{Connection, Row}; | ||
| 8 | - | ||
| 9 | -use crate::{community, database, error::ServerError, user}; | ||
| 10 | - | ||
| 11 | -fn rank_of(row: &Row, index: usize) -> Result<Rank, ServerError> { | ||
| 12 | - let text: String = row.get(index)?; | ||
| 13 | - | ||
| 14 | - Ok(Rank::parse(&text).ok_or(CommonError::Server)?) | ||
| 15 | -} | ||
| 16 | - | ||
| 17 | -pub async fn join( | ||
| 18 | - user_id: &str, | ||
| 19 | - community_id: &str, | ||
| 20 | - rank: Rank, | ||
| 21 | - conn: &Connection, | ||
| 22 | -) -> Result<(), ServerError> { | ||
| 23 | - conn.execute( | ||
| 24 | - "INSERT INTO user_community (user_id, community_id, rank) VALUES (?1, ?2, ?3)", | ||
| 25 | - (user_id, community_id, rank.as_str()), | ||
| 26 | - ) | ||
| 27 | - .await?; | ||
| 28 | - | ||
| 29 | - Ok(()) | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | -pub async fn leave( | ||
| 33 | - user_id: &str, | ||
| 34 | - community_id: &str, | ||
| 35 | - conn: &Connection, | ||
| 36 | -) -> Result<(), ServerError> { | ||
| 37 | - conn.execute( | ||
| 38 | - "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2", | ||
| 39 | - (user_id, community_id), | ||
| 40 | - ) | ||
| 41 | - .await?; | ||
| 42 | - | ||
| 43 | - Ok(()) | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -pub async fn rank( | ||
| 47 | - user_id: &str, | ||
| 48 | - community_id: &str, | ||
| 49 | - conn: &Connection, | ||
| 50 | -) -> Result<Option<Rank>, ServerError> { | ||
| 51 | - let mut rows = conn | ||
| 52 | - .query( | ||
| 53 | - "SELECT rank FROM user_community WHERE user_id = ?1 AND community_id = ?2", | ||
| 54 | - (user_id, community_id), | ||
| 55 | - ) | ||
| 56 | - .await?; | ||
| 57 | - | ||
| 58 | - rows.next() | ||
| 59 | - .await? | ||
| 60 | - .as_ref() | ||
| 61 | - .map(|row| rank_of(row, 0)) | ||
| 62 | - .transpose() | ||
| 63 | -} | ||
| 64 | - | ||
| 65 | -pub async fn set_rank( | ||
| 66 | - user_id: &str, | ||
| 67 | - community_id: &str, | ||
| 68 | - rank: Rank, | ||
| 69 | - conn: &Connection, | ||
| 70 | -) -> Result<(), ServerError> { | ||
| 71 | - conn.execute( | ||
| 72 | - "UPDATE user_community SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", | ||
| 73 | - (user_id, community_id, rank.as_str()), | ||
| 74 | - ) | ||
| 75 | - .await?; | ||
| 76 | - | ||
| 77 | - Ok(()) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -pub async fn mark_read( | ||
| 81 | - user_id: &str, | ||
| 82 | - community_id: &str, | ||
| 83 | - message_id: &str, | ||
| 84 | - conn: &Connection, | ||
| 85 | -) -> Result<(), ServerError> { | ||
| 86 | - conn.execute( | ||
| 87 | - "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", | ||
| 88 | - (user_id, community_id, message_id), | ||
| 89 | - ) | ||
| 90 | - .await?; | ||
| 91 | - | ||
| 92 | - Ok(()) | ||
| 93 | -} | ||
| 94 | - | ||
| 95 | -pub async fn unreads( | ||
| 96 | - user_id: &str, | ||
| 97 | - username: &str, | ||
| 98 | - conn: &Connection, | ||
| 99 | -) -> Result<Vec<Unread>, ServerError> { | ||
| 100 | - let mut rows = conn | ||
| 101 | - .query( | ||
| 102 | - "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", | ||
| 103 | - (user_id,), | ||
| 104 | - ) | ||
| 105 | - .await?; | ||
| 106 | - | ||
| 107 | - let mut unreads = Vec::new(); | ||
| 108 | - while let Some(row) = rows.next().await? { | ||
| 109 | - let messages: i64 = row.get(1)?; | ||
| 110 | - unreads.push(Unread { | ||
| 111 | - community_id: row.get(0)?, | ||
| 112 | - messages: messages as u32, | ||
| 113 | - mentions: 0, | ||
| 114 | - last_read: row.get::<Option<String>>(2)?, | ||
| 115 | - }); | ||
| 116 | - } | ||
| 117 | - | ||
| 118 | - let mention = format!("@{}", username.to_lowercase()); | ||
| 119 | - let mut rows = conn | ||
| 120 | - .query( | ||
| 121 | - "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", | ||
| 122 | - (user_id, mention.as_str()), | ||
| 123 | - ) | ||
| 124 | - .await?; | ||
| 125 | - | ||
| 126 | - let mut mention_counts: HashMap<String, u32> = HashMap::new(); | ||
| 127 | - while let Some(row) = rows.next().await? { | ||
| 128 | - let body: String = row.get(1)?; | ||
| 129 | - if mentions(&body, username) { | ||
| 130 | - *mention_counts.entry(row.get::<String>(0)?).or_default() += 1; | ||
| 131 | - } | ||
| 132 | - } | ||
| 133 | - | ||
| 134 | - for unread in &mut unreads { | ||
| 135 | - unread.mentions = mention_counts | ||
| 136 | - .get(&unread.community_id) | ||
| 137 | - .copied() | ||
| 138 | - .unwrap_or_default(); | ||
| 139 | - } | ||
| 140 | - | ||
| 141 | - Ok(unreads) | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -pub async fn member_ids(community_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 145 | - database::ids( | ||
| 146 | - conn, | ||
| 147 | - "SELECT user_id FROM user_community WHERE community_id = ?1", | ||
| 148 | - (community_id,), | ||
| 149 | - ) | ||
| 150 | - .await | ||
| 151 | -} | ||
| 152 | - | ||
| 153 | -pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, ServerError> { | ||
| 154 | - let mut rows = conn | ||
| 155 | - .query( | ||
| 156 | - &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")), | ||
| 157 | - (community_id,), | ||
| 158 | - ) | ||
| 159 | - .await?; | ||
| 160 | - | ||
| 161 | - let mut members = Vec::new(); | ||
| 162 | - while let Some(row) = rows.next().await? { | ||
| 163 | - members.push(Member { | ||
| 164 | - user: user::from_row(&row)?, | ||
| 165 | - rank: rank_of(&row, 5)?, | ||
| 166 | - }); | ||
| 167 | - } | ||
| 168 | - | ||
| 169 | - Ok(members) | ||
| 170 | -} | ||
| 171 | - | ||
| 172 | -pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, ServerError> { | ||
| 173 | - let count = database::scalar_i64( | ||
| 174 | - conn, | ||
| 175 | - "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", | ||
| 176 | - (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), | ||
| 177 | - ) | ||
| 178 | - .await?; | ||
| 179 | - | ||
| 180 | - Ok(count as usize) | ||
| 181 | -} | ||
| 182 | - | ||
| 183 | -pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, ServerError> { | ||
| 184 | - database::ids( | ||
| 185 | - conn, | ||
| 186 | - "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", | ||
| 187 | - (user_id, Rank::Owner.as_str()), | ||
| 188 | - ) | ||
| 189 | - .await | ||
| 190 | -} | ||
| 191 | - | ||
| 192 | -pub async fn ban( | ||
| 193 | - user_id: &str, | ||
| 194 | - community_id: &str, | ||
| 195 | - reason: Option<&str>, | ||
| 196 | - conn: &Connection, | ||
| 197 | -) -> Result<(), ServerError> { | ||
| 198 | - conn.execute( | ||
| 199 | - "INSERT OR REPLACE INTO ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", | ||
| 200 | - (user_id, community_id, reason), | ||
| 201 | - ) | ||
| 202 | - .await?; | ||
| 203 | - | ||
| 204 | - Ok(()) | ||
| 205 | -} | ||
| 206 | - | ||
| 207 | -pub async fn unban( | ||
| 208 | - user_id: &str, | ||
| 209 | - community_id: &str, | ||
| 210 | - conn: &Connection, | ||
| 211 | -) -> Result<(), ServerError> { | ||
| 212 | - conn.execute( | ||
| 213 | - "DELETE FROM ban WHERE user_id = ?1 AND community_id = ?2", | ||
| 214 | - (user_id, community_id), | ||
| 215 | - ) | ||
| 216 | - .await?; | ||
| 217 | - | ||
| 218 | - Ok(()) | ||
| 219 | -} | ||
| 220 | - | ||
| 221 | -pub async fn is_banned( | ||
| 222 | - user_id: &str, | ||
| 223 | - community_id: &str, | ||
| 224 | - conn: &Connection, | ||
| 225 | -) -> Result<bool, ServerError> { | ||
| 226 | - database::exists( | ||
| 227 | - conn, | ||
| 228 | - "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)", | ||
| 229 | - (user_id, community_id), | ||
| 230 | - ) | ||
| 231 | - .await | ||
| 232 | -} | ||
| 233 | - | ||
| 234 | -pub async fn bans(community_id: &str, conn: &Connection) -> Result<Vec<Ban>, ServerError> { | ||
| 235 | - let mut rows = conn | ||
| 236 | - .query( | ||
| 237 | - &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")), | ||
| 238 | - (community_id,), | ||
| 239 | - ) | ||
| 240 | - .await?; | ||
| 241 | - | ||
| 242 | - let mut bans = Vec::new(); | ||
| 243 | - while let Some(row) = rows.next().await? { | ||
| 244 | - bans.push(Ban { | ||
| 245 | - user: user::from_row(&row)?, | ||
| 246 | - reason: row.get(5)?, | ||
| 247 | - }); | ||
| 248 | - } | ||
| 249 | - | ||
| 250 | - Ok(bans) | ||
| 251 | -} | ||
| 252 | - | ||
| 253 | -#[cfg(test)] | ||
| 254 | -mod tests { | ||
| 255 | - use common::model::{Member, Rank}; | ||
| 256 | - | ||
| 257 | - use crate::{community, database, test, user, user_community}; | ||
| 258 | - | ||
| 259 | - #[tokio::test] | ||
| 260 | - async fn join() { | ||
| 261 | - let db = test::get_database().await; | ||
| 262 | - let conn = database::connect(&db).await.unwrap(); | ||
| 263 | - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 264 | - let member = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 265 | - let community = community::create("The Community", &conn).await.unwrap(); | ||
| 266 | - | ||
| 267 | - user_community::join(&member.id, &community.id, Rank::Member, &conn) | ||
| 268 | - .await | ||
| 269 | - .unwrap(); | ||
| 270 | - | ||
| 271 | - assert_eq!( | ||
| 272 | - Some(Rank::Member), | ||
| 273 | - user_community::rank(&member.id, &community.id, &conn) | ||
| 274 | - .await | ||
| 275 | - .unwrap() | ||
| 276 | - ); | ||
| 277 | - assert_eq!( | ||
| 278 | - None, | ||
| 279 | - user_community::rank(&owner.id, &community.id, &conn) | ||
| 280 | - .await | ||
| 281 | - .unwrap() | ||
| 282 | - ); | ||
| 283 | - } | ||
| 284 | - | ||
| 285 | - #[tokio::test] | ||
| 286 | - async fn join_again() { | ||
| 287 | - let db = test::get_database().await; | ||
| 288 | - let conn = database::connect(&db).await.unwrap(); | ||
| 289 | - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 290 | - let community = community::create("The Community", &conn).await.unwrap(); | ||
| 291 | - | ||
| 292 | - user_community::join(&owner.id, &community.id, Rank::Owner, &conn) | ||
| 293 | - .await | ||
| 294 | - .unwrap(); | ||
| 295 | - | ||
| 296 | - assert!( | ||
| 297 | - user_community::join(&owner.id, &community.id, Rank::Member, &conn) | ||
| 298 | - .await | ||
| 299 | - .is_err() | ||
| 300 | - ); | ||
| 301 | - } | ||
| 302 | - | ||
| 303 | - #[tokio::test] | ||
| 304 | - async fn leave() { | ||
| 305 | - let db = test::get_database().await; | ||
| 306 | - let conn = database::connect(&db).await.unwrap(); | ||
| 307 | - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 308 | - let community = community::create("The Community", &conn).await.unwrap(); | ||
| 309 | - user_community::join(&owner.id, &community.id, Rank::Owner, &conn) | ||
| 310 | - .await | ||
| 311 | - .unwrap(); | ||
| 312 | - | ||
| 313 | - user_community::leave(&owner.id, &community.id, &conn) | ||
| 314 | - .await | ||
| 315 | - .unwrap(); | ||
| 316 | - | ||
| 317 | - assert_eq!( | ||
| 318 | - None, | ||
| 319 | - user_community::rank(&owner.id, &community.id, &conn) | ||
| 320 | - .await | ||
| 321 | - .unwrap() | ||
| 322 | - ); | ||
| 323 | - } | ||
| 324 | - | ||
| 325 | - #[tokio::test] | ||
| 326 | - async fn members() { | ||
| 327 | - let db = test::get_database().await; | ||
| 328 | - let conn = database::connect(&db).await.unwrap(); | ||
| 329 | - let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 330 | - let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 331 | - let _user_3 = user::create("Third Tahinli", "hash", &conn).await.unwrap(); | ||
| 332 | - let community = community::create("The Community", &conn).await.unwrap(); | ||
| 333 | - | ||
| 334 | - user_community::join(&user_1.id, &community.id, Rank::Owner, &conn) | ||
| 335 | - .await | ||
| 336 | - .unwrap(); | ||
| 337 | - user_community::join(&user_2.id, &community.id, Rank::Member, &conn) | ||
| 338 | - .await | ||
| 339 | - .unwrap(); | ||
| 340 | - | ||
| 341 | - let members = user_community::members(&community.id, &conn).await.unwrap(); | ||
| 342 | - | ||
| 343 | - assert_eq!( | ||
| 344 | - vec![ | ||
| 345 | - Member { | ||
| 346 | - user: user_1, | ||
| 347 | - rank: Rank::Owner | ||
| 348 | - }, | ||
| 349 | - Member { | ||
| 350 | - user: user_2, | ||
| 351 | - rank: Rank::Member | ||
| 352 | - }, | ||
| 353 | - ], | ||
| 354 | - members | ||
| 355 | - ); | ||
| 356 | - } | ||
| 357 | - | ||
| 358 | - #[tokio::test] | ||
| 359 | - async fn ban_and_unban() { | ||
| 360 | - let db = test::get_database().await; | ||
| 361 | - let conn = database::connect(&db).await.unwrap(); | ||
| 362 | - let member = user::create("Not Tahinli", "hash", &conn).await.unwrap(); | ||
| 363 | - let community = community::create("The Community", &conn).await.unwrap(); | ||
| 364 | - user_community::join(&member.id, &community.id, Rank::Member, &conn) | ||
| 365 | - .await | ||
| 366 | - .unwrap(); | ||
| 367 | - | ||
| 368 | - user_community::ban(&member.id, &community.id, None, &conn) | ||
| 369 | - .await | ||
| 370 | - .unwrap(); | ||
| 371 | - let banned = user_community::is_banned(&member.id, &community.id, &conn) | ||
| 372 | - .await | ||
| 373 | - .unwrap(); | ||
| 374 | - user_community::unban(&member.id, &community.id, &conn) | ||
| 375 | - .await | ||
| 376 | - .unwrap(); | ||
| 377 | - | ||
| 378 | - assert!(banned); | ||
| 379 | - assert!( | ||
| 380 | - !user_community::is_banned(&member.id, &community.id, &conn) | ||
| 381 | - .await | ||
| 382 | - .unwrap() | ||
| 383 | - ); | ||
| 384 | - assert!( | ||
| 385 | - user_community::bans(&community.id, &conn) | ||
| 386 | - .await | ||
| 387 | - .unwrap() | ||
| 388 | - .is_empty() | ||
| 389 | - ); | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | - #[tokio::test] | ||
| 393 | - async fn communities_of() { | ||
| 394 | - let db = test::get_database().await; | ||
| 395 | - let conn = database::connect(&db).await.unwrap(); | ||
| 396 | - let owner = user::create("Tahinli", "hash", &conn).await.unwrap(); | ||
| 397 | - let community_1 = community::create("The Community", &conn).await.unwrap(); | ||
| 398 | - let community_2 = community::create("The Community", &conn).await.unwrap(); | ||
| 399 | - | ||
| 400 | - user_community::join(&owner.id, &community_1.id, Rank::Owner, &conn) | ||
| 401 | - .await | ||
| 402 | - .unwrap(); | ||
| 403 | - user_community::join(&owner.id, &community_2.id, Rank::Owner, &conn) | ||
| 404 | - .await | ||
| 405 | - .unwrap(); | ||
| 406 | - | ||
| 407 | - let communities_of = community::communities_of(&owner.id, &conn).await.unwrap(); | ||
| 408 | - | ||
| 409 | - assert_eq!(vec![community_1, community_2], communities_of); | ||
| 410 | - } | ||
| 411 | -} | ||