From f8f75cba4d0856b527f994433c0e9ef69f0704bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 05:28:22 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20simplify=20cod?= =?UTF-8?q?ebase=20for=20ssot,=20kiss=20and=20yagni?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/client/src/accounts.rs | 16 +- crates/client/src/avatar.rs | 6 +- crates/client/src/embed.rs | 13 +- crates/client/src/gui.rs | 137 ++-- crates/client/src/gui/auth.rs | 20 +- crates/client/src/gui/builder.rs | 111 ++- crates/client/src/gui/builder/access.rs | 50 +- crates/client/src/gui/builder/backups.rs | 65 +- crates/client/src/gui/builder/communities.rs | 51 +- crates/client/src/gui/builder/log.rs | 12 +- crates/client/src/gui/builder/messages.rs | 20 +- crates/client/src/gui/builder/overview.rs | 31 +- crates/client/src/gui/builder/reports.rs | 60 +- crates/client/src/gui/builder/server.rs | 110 +-- crates/client/src/gui/builder/storage.rs | 24 +- crates/client/src/gui/builder/ui.rs | 86 +- crates/client/src/gui/builder/users.rs | 13 +- crates/client/src/gui/builder/voice.rs | 49 +- crates/client/src/gui/chat.rs | 289 +++---- crates/client/src/gui/community_settings.rs | 46 +- crates/client/src/gui/composer.rs | 54 +- crates/client/src/gui/forward.rs | 32 +- crates/client/src/gui/media_view.rs | 59 +- crates/client/src/gui/message_actions.rs | 49 +- crates/client/src/gui/poll.rs | 18 +- crates/client/src/gui/profile.rs | 84 +- crates/client/src/gui/settings_page.rs | 116 ++- crates/client/src/gui/sidebar.rs | 341 ++++---- crates/client/src/gui/voice_note.rs | 32 +- crates/client/src/gui/voice_settings.rs | 51 +- crates/client/src/lib.rs | 6 + crates/client/src/media/mod.rs | 16 +- crates/client/src/media/voice_note.rs | 6 +- crates/client/src/mutes.rs | 15 +- crates/client/src/network.rs | 275 +++---- crates/client/src/settings.rs | 125 ++- crates/client/src/tray.rs | 31 +- crates/client/src/voice/audio.rs | 28 +- crates/client/src/voice/audio/pipewire.rs | 7 +- crates/client/src/voice/engine.rs | 60 +- crates/client/src/voice/mod.rs | 111 +-- crates/common/src/event.rs | 6 +- crates/common/src/model.rs | 372 +++------ crates/common/src/network.rs | 63 +- crates/common/src/permission.rs | 8 - crates/common/src/request.rs | 4 +- crates/common/src/time.rs | 10 + crates/common/src/validate.rs | 32 +- crates/server/src/admin_log.rs | 81 +- crates/server/src/attachment.rs | 189 ++--- crates/server/src/authentication.rs | 15 +- crates/server/src/backup.rs | 15 +- crates/server/src/community.rs | 52 +- crates/server/src/database.rs | 14 + crates/server/src/direct.rs | 26 +- crates/server/src/friend.rs | 17 +- crates/server/src/invitation.rs | 31 +- crates/server/src/lib.rs | 28 +- crates/server/src/message.rs | 60 +- crates/server/src/network.rs | 85 +- crates/server/src/report.rs | 23 +- crates/server/src/request.rs | 807 +++++++++---------- crates/server/src/server_ban.rs | 23 +- crates/server/src/server_settings.rs | 18 +- crates/server/src/stats.rs | 11 +- crates/server/src/user.rs | 269 +++---- crates/server/src/voice.rs | 135 ++-- 67 files changed, 2208 insertions(+), 2911 deletions(-) diff --git a/crates/client/src/accounts.rs b/crates/client/src/accounts.rs index 5eb187b..2f6e66b 100644 --- a/crates/client/src/accounts.rs +++ b/crates/client/src/accounts.rs @@ -3,6 +3,8 @@ use std::{fs, path::PathBuf}; use common::model::User; use tracing::warn; +use crate::config_file; + #[derive(Debug, Clone, PartialEq, Eq)] pub struct Account { pub user_id: String, @@ -17,11 +19,6 @@ pub struct Accounts { } impl Accounts { - pub fn active(&self) -> Option<&Account> { - let active = self.active.as_deref()?; - self.list.iter().find(|account| account.user_id == active) - } - pub fn get(&self, user_id: &str) -> Option<&Account> { self.list.iter().find(|account| account.user_id == user_id) } @@ -72,12 +69,9 @@ impl Accounts { } } -fn path() -> Option { - dirs::config_dir().map(|dir| dir.join("yumush").join("accounts")) -} - pub fn load() -> Accounts { - let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else { + let Some(content) = config_file("accounts").and_then(|path| fs::read_to_string(path).ok()) + else { return Accounts::default(); }; let mut accounts = Accounts::default(); @@ -98,7 +92,7 @@ pub fn load() -> Accounts { } fn save(accounts: &Accounts) { - let Some(path) = path() else { + let Some(path) = config_file("accounts") else { return; }; let mut content: String = accounts diff --git a/crates/client/src/avatar.rs b/crates/client/src/avatar.rs index b8c49e8..8dc143b 100644 --- a/crates/client/src/avatar.rs +++ b/crates/client/src/avatar.rs @@ -7,7 +7,7 @@ use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterT const QUALITIES: [u8; 3] = [85, 60, 40]; pub fn prepare(bytes: &[u8], maximum: u64) -> Result, Error> { - let image = image::load_from_memory(bytes).map_err(decode_error)?; + let image = image::load_from_memory(bytes).map_err(image_error)?; let square = center_square(image) .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3) .to_rgb8(); @@ -38,12 +38,12 @@ fn encode(image: &RgbImage, quality: u8) -> Result, Error> { let mut bytes = Vec::new(); JpegEncoder::new_with_quality(&mut bytes, quality) .encode_image(image) - .map_err(decode_error)?; + .map_err(image_error)?; Ok(bytes) } -fn decode_error(error: image::ImageError) -> Error { +fn image_error(error: image::ImageError) -> Error { Error::Decode(error.to_string()) } diff --git a/crates/client/src/embed.rs b/crates/client/src/embed.rs index a941682..544a2f5 100644 --- a/crates/client/src/embed.rs +++ b/crates/client/src/embed.rs @@ -325,11 +325,14 @@ fn entity(e: &str) -> Option { "lt" => Some('<'), "gt" => Some('>'), "quot" => Some('"'), - "#39" | "#x27" => Some('\''), - _ => match e.strip_prefix("#x") { - Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?), - None => char::from_u32(e.strip_prefix('#')?.parse().ok()?), - }, + _ => numeric(e), + } +} + +fn numeric(e: &str) -> Option { + match e.strip_prefix("#x") { + Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?), + None => char::from_u32(e.strip_prefix('#')?.parse().ok()?), } } diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index c799b7f..ad38945 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -11,8 +11,8 @@ use common::{ error::Error, event::Event, model::{ - BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, ServerSettings, - Unread, User, mentions, + BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, + ServerSettings, Unread, User, mentions, }, time::created_at_ms, }; @@ -338,9 +338,10 @@ pub fn pop_in( element: E, anchor: Anchor, ) -> AnimationElement { - let travel = match anchor.is_bottom() { - true => MOTION_TRAVEL, - false => -MOTION_TRAVEL, + let travel = if anchor.is_bottom() { + MOTION_TRAVEL + } else { + -MOTION_TRAVEL }; element.with_animation(id, motion(), move |element, delta| { @@ -353,9 +354,10 @@ pub fn swap_in( element: E, forward: bool, ) -> AnimationElement { - let travel = match forward { - true => MOTION_TRAVEL, - false => -MOTION_TRAVEL, + let travel = if forward { + MOTION_TRAVEL + } else { + -MOTION_TRAVEL }; element.with_animation(id, motion(), move |element, delta| { @@ -662,8 +664,8 @@ impl Yumush { } pub fn tray_state(&self) -> crate::tray::TrayState { - let groups = self.chat.unread_total(true); - let direct = self.chat.unread_total(false); + let groups = self.chat.unread_groups(); + let direct = self.chat.unread_direct(); crate::tray::TrayState { messages: groups.messages + direct.messages, mentions: groups.mentions + direct.mentions, @@ -787,17 +789,13 @@ impl Yumush { } fn logout(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user) = self.user.take() else { + let Some(user) = self.user.clone() else { return; }; self.accounts.forget(&user.id); - self.end_voice(cx); - self.leave_settings(); + self.end_session(window, cx); let network = self.network.clone(); - self.chat.reset(); - self.change_page(Route::Login, window, cx); - cx.spawn_in(window, async move |this, cx| { if let Err(error) = network.logout().await { notify_error(&this, cx, error); @@ -866,7 +864,7 @@ impl Yumush { } pub fn actor_rank(&self) -> Option { - self.user.as_ref().and_then(|me| self.chat.my_rank(me)) + self.user.as_ref().and_then(|me| self.chat.rank_of(me)) } pub fn community_badge( @@ -952,7 +950,7 @@ impl Yumush { Event::VoiceMuted { user_id, muted: true, - } if self.is_me(user_id) => self.force_mute(cx), + } if self.is_me(user_id) => self.set_muted(true, cx), Event::Typing { .. } => { cx.spawn(async move |this, cx| { cx.background_executor().timer(chat::TYPING_TTL).await; @@ -1015,9 +1013,7 @@ impl Yumush { .entry(message.community_id.clone()) .or_insert_with(|| Unread { community_id: message.community_id.clone(), - messages: 0, - mentions: 0, - last_read: None, + ..Default::default() }); unread.messages += 1; if mentions(&message.body, &me.username) { @@ -1057,7 +1053,7 @@ impl Yumush { pub(super) fn is_direct(&self, community_id: &str) -> bool { self.chat.communities().iter().any(|community| { - community.id == community_id && matches!(community.kind, CommunityKind::Direct { .. }) + community.id == community_id && community.kind.is_direct() }) } @@ -1128,45 +1124,8 @@ impl Yumush { let active = window .as_ref() .is_some_and(|window| window.is_window_active()); - if let NetworkEvent::Pushed(pushed) = &event - && let Event::MessageCreated(message) = pushed.as_ref() - && self.should_notify(message, active) - { - self.network.play_notification(); - } - - if let NetworkEvent::Pushed(pushed) = &event - && let Event::MessageCreated(message) = pushed.as_ref() - { - self.count_message(message, active, cx); - } - - if let NetworkEvent::Pushed(pushed) = &event - && let Event::MessageCreated(message) = pushed.as_ref() - && message.call == Some(CallLog::Declined) - && self.chat.in_voice(&message.community_id) - { - self.end_voice(cx); - } - - if let NetworkEvent::Pushed(pushed) = &event - && let Event::VoiceJoined { - community_id, - user_id, - } = pushed.as_ref() - && self.starts_call(community_id, user_id) - { - self.chat.ringing.insert(community_id.clone()); - } - - if let NetworkEvent::Pushed(pushed) = &event - && let Event::VoiceLeft { - community_id, - user_id, - } = pushed.as_ref() - && self.ends_call(community_id, user_id) - { - self.end_voice(cx); + if let NetworkEvent::Pushed(pushed) = &event { + self.before_pushed(pushed, active, cx); } let Some(window) = window else { @@ -1188,7 +1147,7 @@ impl Yumush { NetworkEvent::Disconnected(error) => self.connection.lost(&error), NetworkEvent::SessionLost => { if let Some(user) = &self.user { - self.accounts.forget(&user.id.clone()); + self.accounts.forget(&user.id); } self.end_session(window, cx); } @@ -1203,12 +1162,15 @@ impl Yumush { Event::Removed { community_id, community_name, - banned, + sanction, reason, } => { self.leave_voice_in(&community_id, cx); self.chat.remove_community(&community_id); - let action = if banned { "Banned from" } else { "Kicked from" }; + let action = match sanction { + Sanction::Ban => "Banned from", + Sanction::Kick => "Kicked from", + }; let text = match reason { Some(reason) => format!("{action} {community_name}: {reason}"), None => format!("{action} {community_name}"), @@ -1220,11 +1182,7 @@ impl Yumush { self.apply_pushed(Event::CommunityDeleted { community_id }, cx); } Event::ReportCreated => self.report_created(window, cx), - Event::Announcement { text } => { - if let Some(settings) = self.server.as_mut() { - settings.announcement = text; - } - } + Event::Announcement { text } => self.set_announcement(text), event => { let voice = matches!( event, @@ -1244,6 +1202,41 @@ impl Yumush { cx.notify(); } + fn before_pushed(&mut self, event: &Event, active: bool, cx: &mut Context) { + match event { + Event::MessageCreated(message) => { + if self.should_notify(message, active) { + self.network.play_notification(); + } + self.count_message(message, active, cx); + if message.call == Some(CallLog::Declined) + && self.chat.in_voice(&message.community_id) + { + self.end_voice(cx); + } + } + Event::VoiceJoined { + community_id, + user_id, + } if self.starts_call(community_id, user_id) => { + self.chat.ringing.insert(community_id.clone()); + } + Event::VoiceLeft { + community_id, + user_id, + } if self.ends_call(community_id, user_id) => { + self.end_voice(cx); + } + _ => {} + } + } + + fn set_announcement(&mut self, text: String) { + if let Some(settings) = self.server.as_mut() { + settings.announcement = text; + } + } + fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context) { match event { NetworkEvent::Connected => { @@ -1257,11 +1250,7 @@ impl Yumush { | Event::Removed { .. } | Event::CommunityDeleted { .. } | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)), - Event::Announcement { text } => { - if let Some(settings) = self.server.as_mut() { - settings.announcement = text; - } - } + Event::Announcement { text } => self.set_announcement(text), event => self.apply_pushed(event, cx), }, } diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index 3d14c29..061929f 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -68,7 +68,7 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { .register(&username, &password, invite.as_deref()) .await } - _ => network.login(&username, &password).await, + Route::Login | Route::Chat => network.login(&username, &password).await, }; match result { @@ -118,7 +118,7 @@ impl Yumush { let palette = palette(cx); let action_label = match route { Route::Register => "Register", - _ => "Log in", + Route::Login | Route::Chat => "Log in", }; let entity = cx.entity(); @@ -134,18 +134,10 @@ impl Yumush { .font_weight(FontWeight::MEDIUM) .child(action_label); - let registration_open = self - .server - .as_ref() - .is_none_or(|settings| settings.registration_open); - let maintenance = self - .server - .as_ref() - .is_some_and(|settings| settings.maintenance); - let title = self - .server - .as_ref() - .map_or_else(|| "yumush".to_string(), |settings| settings.name.clone()); + let server = self.server.as_ref(); + let registration_open = server.is_none_or(|settings| settings.registration_open); + let maintenance = server.is_some_and(|settings| settings.maintenance); + let title = server.map_or_else(|| "yumush".to_string(), |settings| settings.name.clone()); let tabs = segment_track(palette) .child(tab(palette, &entity, Route::Login, "Log in", route)) diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 2f4f4de..072d8a0 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -11,6 +11,8 @@ mod ui; mod users; mod voice; +use std::{fmt::Display, future::Future}; + use common::model::{CommunityKind, Member, Role}; use gpui_kit::{ AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, @@ -27,19 +29,7 @@ use super::{ Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, text, }; - -const BUILDER_TABS: [(BuilderTab, &str, IconName); 10] = [ - (BuilderTab::Overview, "Overview", IconName::LayoutDashboard), - (BuilderTab::Users, "Users", IconName::Users), - (BuilderTab::Communities, "Communities", IconName::Building2), - (BuilderTab::Messages, "Messages", IconName::MessageSquare), - (BuilderTab::Voice, "Voice", IconName::Mic), - (BuilderTab::Storage, "Storage", IconName::HardDrive), - (BuilderTab::Access, "Access", IconName::Key), - (BuilderTab::Reports, "Reports", IconName::Flag), - (BuilderTab::Server, "Server", IconName::Server), - (BuilderTab::Log, "Log", IconName::ScrollText), -]; +use crate::network::NetworkHandle; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum BuilderTab { @@ -55,6 +45,51 @@ pub(super) enum BuilderTab { Log, } +impl BuilderTab { + const ALL: [Self; 10] = [ + Self::Overview, + Self::Users, + Self::Communities, + Self::Messages, + Self::Voice, + Self::Storage, + Self::Access, + Self::Reports, + Self::Server, + Self::Log, + ]; + + fn label(self) -> &'static str { + match self { + Self::Overview => "Overview", + Self::Users => "Users", + Self::Communities => "Communities", + Self::Messages => "Messages", + Self::Voice => "Voice", + Self::Storage => "Storage", + Self::Access => "Access", + Self::Reports => "Reports", + Self::Server => "Server", + Self::Log => "Log", + } + } + + fn icon(self) -> IconName { + match self { + Self::Overview => IconName::LayoutDashboard, + Self::Users => IconName::Users, + Self::Communities => IconName::Building2, + Self::Messages => IconName::MessageSquare, + Self::Voice => IconName::Mic, + Self::Storage => IconName::HardDrive, + Self::Access => IconName::Key, + Self::Reports => IconName::Flag, + Self::Server => IconName::Server, + Self::Log => IconName::ScrollText, + } + } +} + pub(super) struct Transfer { pub(super) community_id: String, pub(super) members: Vec, @@ -69,10 +104,7 @@ impl Yumush { cx: &App, ) -> impl IntoElement { let tab = self.chat.builder_tab; - let title = BUILDER_TABS - .iter() - .find(|(candidate, _, _)| *candidate == tab) - .map_or("", |(_, label, _)| label); + let title = tab.label(); let body = match tab { BuilderTab::Overview => self .overview_rows(palette) @@ -187,11 +219,7 @@ impl Yumush { .bg(palette.panel) .border_r_1() .border_color(palette.border) - .children( - BUILDER_TABS.map(|(tab, label, icon)| { - self.builder_nav_item(tab, label, icon, entity, palette) - }), - ) + .children(BuilderTab::ALL.map(|tab| self.builder_nav_item(tab, entity, palette))) .child(div().flex_1()) .child(self.ghost_toggle(entity, palette)) } @@ -199,11 +227,11 @@ impl Yumush { fn builder_nav_item( &self, tab: BuilderTab, - label: &'static str, - icon: IconName, entity: &Entity, palette: Palette, ) -> impl IntoElement { + let label = tab.label(); + let icon = tab.icon(); let active = self.chat.builder_tab == tab; let color = if active { palette.text } else { palette.muted }; let open = (tab == BuilderTab::Reports) @@ -309,22 +337,42 @@ impl Yumush { cx.notify(); } - pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context) { + pub(super) fn fetch_builder( + &self, + window: &mut Window, + cx: &mut Context, + fetch: impl FnOnce(NetworkHandle) -> Fut + 'static, + apply: impl FnOnce(&mut Self, T, &mut Context) + 'static, + ) where + T: 'static, + E: Display + 'static, + Fut: Future> + 'static, + { if !self.is_builder() { return; } let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let accounts = match network.users().await { - Ok(accounts) => accounts, + let value = match fetch(network).await { + Ok(value) => value, Err(error) => { notify_error(&this, cx, error); return; } }; - let _ = this.update(cx, |yumush, cx| { + let _ = this.update(cx, |yumush, cx| apply(yumush, value, cx)); + }) + .detach(); + } + + pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context) { + self.fetch_builder( + window, + cx, + |network| async move { network.users().await }, + |yumush, accounts, cx| { for account in &accounts { yumush.request_user_avatar(&account.user, cx); } @@ -336,9 +384,8 @@ impl Yumush { yumush.chat.builder_users = accounts; yumush.set_ghost_state(ghost); cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context) { @@ -390,7 +437,7 @@ impl Yumush { let _ = this.update(cx, |yumush, cx| { yumush.set_ghost_state(enabled); if enabled { - yumush.force_mute(cx); + yumush.set_muted(true, cx); } cx.notify(); }); diff --git a/crates/client/src/gui/builder/access.rs b/crates/client/src/gui/builder/access.rs index d2a54b3..b138909 100644 --- a/crates/client/src/gui/builder/access.rs +++ b/crates/client/src/gui/builder/access.rs @@ -156,49 +156,27 @@ impl Yumush { } pub(super) fn load_invites(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let codes = match network.invite_codes().await { - Ok(codes) => codes, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { network.invite_codes().await }, + |yumush, codes, cx| { yumush.chat.builder_invites = codes; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn load_server_bans(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let bans = match network.server_bans().await { - Ok(bans) => bans, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { network.server_bans().await }, + |yumush, bans, cx| { yumush.chat.builder_bans = bans; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn create_invite(&mut self, window: &mut Window, cx: &mut Context) { diff --git a/crates/client/src/gui/builder/backups.rs b/crates/client/src/gui/builder/backups.rs index 4e32e9c..d454abb 100644 --- a/crates/client/src/gui/builder/backups.rs +++ b/crates/client/src/gui/builder/backups.rs @@ -4,51 +4,31 @@ use gpui_kit::{ component::Icon, div, prelude::FluentBuilder as _, px, }; -use super::ui::{accent_button, card, card_header, list_row}; -use crate::gui::{ - DATE, Palette, Tooltip, Yumush, clickable, entity_action, millis_time, notify_error, storage, - text, -}; +use super::ui::{accent_button, card, card_header, delete_icon_button, icon_button, list_row}; +use crate::gui::{DATE, Palette, Yumush, entity_action, millis_time, notify_error, storage, text}; fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette: Palette) -> Div { let export_name = info.name.clone(); - let export = clickable( + let export = icon_button( format!("export_backup_{}", info.name), + IconName::Download, + "Export", + palette.muted, palette, entity_action(entity, move |yumush, window, cx| { yumush.export_backup(&export_name, window, cx) }), - ) - .tip("Export") - .size(px(26.)) - .flex() - .flex_shrink_0() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::Download).w(px(14.)).h(px(14.))); + ); let delete_name = info.name.clone(); - let delete = clickable( + let delete = delete_icon_button( format!("delete_backup_{}", info.name), + pending, palette, entity_action(entity, move |yumush, window, cx| { yumush.delete_backup(&delete_name, window, cx) }), - ) - .tip(if pending { "Confirm" } else { "Delete" }) - .size(px(26.)) - .flex() - .flex_shrink_0() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.danger) - .when(pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) - }) - .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.))); + ); list_row() .child( @@ -132,26 +112,15 @@ impl Yumush { } pub(super) fn load_backups(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let backups = match network.backups().await { - Ok(backups) => backups, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { network.backups().await }, + |yumush, backups, cx| { yumush.backups = backups; cx.notify(); - }); - }) - .detach(); + }, + ); } fn create_backup(&self, window: &mut Window, cx: &mut Context) { diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs index e6727cc..35ac6b8 100644 --- a/crates/client/src/gui/builder/communities.rs +++ b/crates/client/src/gui/builder/communities.rs @@ -1,4 +1,4 @@ -use common::model::{Community, CommunityKind, CommunitySummary, Member, Rank}; +use common::model::{Community, CommunitySummary, Member, Rank}; use gpui_kit::{ AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px, @@ -6,33 +6,13 @@ use gpui_kit::{ use super::{ Transfer, - ui::{card, icon_button, pill, plain_button}, + ui::{card, icon_button, pill, plain_button, rows_body}, }; use crate::gui::{ Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text, entity_action, notify_error, profile::user_link, text, }; -fn rows_body(rows: Vec
, empty: &str, palette: Palette) -> Div { - if rows.is_empty() { - return div() - .py(px(24.)) - .flex() - .justify_center() - .text_size(text(12.)) - .text_color(palette.muted) - .child(empty.to_string()); - } - div() - .flex() - .flex_col() - .children(rows.into_iter().enumerate().map(|(index, row)| { - row.when(index > 0, |row| { - row.border_t_1().border_color(palette.border) - }) - })) -} - impl Yumush { pub(super) fn set_builder_community_voice( &mut self, @@ -58,21 +38,11 @@ impl Yumush { } pub(super) fn load_builder_communities(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let summaries = match network.all_communities().await { - Ok(summaries) => summaries, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { network.all_communities().await }, + |yumush, summaries, cx| { for summary in &summaries { if let Some(avatar_id) = &summary.community.avatar_id { yumush.request_avatar(avatar_id, cx); @@ -83,9 +53,8 @@ impl Yumush { } yumush.chat.builder_communities = summaries; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn delete_builder_community( @@ -267,7 +236,7 @@ impl Yumush { ) { let community_id = community.id.clone(); if self.chat.joined(&community_id) { - let direct = matches!(community.kind, CommunityKind::Direct { .. }); + let direct = community.kind.is_direct(); self.go_to_community(community_id.clone(), direct, window, cx); } else { self.open_builder_community(community, window, cx); diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index 0a0d5df..9e600fc 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -1,5 +1,5 @@ use common::{ - model::{AdminAction, AdminLogEntry, action_detail, action_name}, + model::{AdminAction, AdminLogEntry, action_detail}, time::{created_at_ms, now_ms}, }; use gpui_kit::{ @@ -12,7 +12,9 @@ use gpui_kit::{ }; use jiff::Timestamp; -use super::ui::{accent_button, card, day_millis, list_row, pill, toolbar}; +use super::ui::{ + accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar, +}; use crate::gui::STAMP; use crate::gui::{ Palette, Yumush, @@ -104,7 +106,7 @@ fn builder_log_csv(entries: &[AdminLogEntry]) -> String { let fields = [ time, actor, - action_name(&entry.action).to_string(), + entry.action.name().to_string(), target, entry.community.clone().unwrap_or_default(), action_detail(&entry.action).unwrap_or_default(), @@ -220,8 +222,8 @@ impl Yumush { .copied() .filter(|name| *name != "All") .map(str::to_string); - let after_ms = day_millis(&search_text(&self.chat.builder_log_from, cx), false); - let before_ms = day_millis(&search_text(&self.chat.builder_log_to, cx), true); + let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx)); + let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx)); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs index 736d349..040c227 100644 --- a/crates/client/src/gui/builder/messages.rs +++ b/crates/client/src/gui/builder/messages.rs @@ -4,7 +4,10 @@ use gpui_kit::{ assets::IconName, div, prelude::FluentBuilder as _, px, }; -use super::ui::{accent_button, card, day_millis, icon_button, list_card, list_row}; +use super::ui::{ + accent_button, card, delete_icon_button, end_of_day_ms, icon_button, list_card, list_row, + start_of_day_ms, +}; use crate::gui::YEAR_STAMP; use crate::gui::{ Palette, Yumush, @@ -36,19 +39,14 @@ fn message_hit_row( yumush.jump_to(community_id.clone(), false, window, cx) }), ); - let delete = icon_button( + let delete = delete_icon_button( format!("delete_message_{}", hit.message.id), - IconName::Trash, - if pending { "Confirm" } else { "Delete" }, - palette.danger, + pending, palette, entity_action(entity, move |yumush, window, cx| { yumush.delete_builder_message(&message_id, window, cx) }), - ) - .when(pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) - }); + ); let purge = hit.author.as_ref().map(|author| { let user_id = author.id.clone(); icon_button( @@ -211,8 +209,8 @@ impl Yumush { let community = search_text(&self.chat.builder_message_community, cx); let user_id = self.resolve_user(&username); let community_id = self.resolve_community(&community); - let after_ms = day_millis(&search_text(&self.chat.builder_message_from, cx), false); - let before_ms = day_millis(&search_text(&self.chat.builder_message_to, cx), true); + let after_ms = start_of_day_ms(&search_text(&self.chat.builder_message_from, cx)); + let before_ms = end_of_day_ms(&search_text(&self.chat.builder_message_to, cx)); let text = (!text.is_empty()).then_some(text); let network = self.network.clone(); diff --git a/crates/client/src/gui/builder/overview.rs b/crates/client/src/gui/builder/overview.rs index b3d6191..8604292 100644 --- a/crates/client/src/gui/builder/overview.rs +++ b/crates/client/src/gui/builder/overview.rs @@ -3,7 +3,7 @@ use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px use jiff::Timestamp; use super::ui::{card, card_header, stat_tile}; -use crate::gui::{DAY, Palette, Yumush, notify_error, storage, text}; +use crate::gui::{DAY, Palette, Yumush, storage, text}; const CHART_HEIGHT: f32 = 80.; @@ -103,31 +103,18 @@ fn bar_chart( impl Yumush { pub(super) fn load_overview(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let loaded = async { + self.fetch_builder( + window, + cx, + |network| async move { Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?)) - } - .await; - let (overview, stats) = match loaded { - Ok(loaded) => loaded, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + }, + |yumush, (overview, stats), cx| { yumush.chat.builder_overview = Some(overview); yumush.chat.builder_stats = stats; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn overview_rows(&self, palette: Palette) -> Vec
{ diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index 09e7136..be11390 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -2,7 +2,7 @@ use std::future::Future; use common::{ error::Error, - model::{Report, ReportStatus}, + model::{BanScope, Report, ReportStatus}, }; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, @@ -48,50 +48,33 @@ fn status_color(status: ReportStatus, palette: Palette) -> Hsla { impl Yumush { pub(super) fn load_open_reports(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let count = match network.reports(Some(ReportStatus::Open)).await { - Ok(reports) => reports.len(), - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { + network + .reports(Some(ReportStatus::Open)) + .await + .map(|reports| reports.len()) + }, + |yumush, count, cx| { yumush.chat.open_reports = count; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn load_reports(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } let status = self.chat.report_filter; - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let reports = match network.reports(status).await { - Ok(reports) => reports, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + move |network| async move { network.reports(status).await }, + |yumush, reports, cx| { yumush.chat.builder_reports = reports; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn refresh_reports(&self, window: &mut Window, cx: &mut Context) { @@ -177,7 +160,7 @@ impl Yumush { let reason = reason.to_string(); self.report_action(window, cx, move |network| async move { network - .ban_user(&user_id, Some(reason.as_str()), false) + .ban_user(&user_id, Some(reason.as_str()), BanScope::Account) .await }); } @@ -390,7 +373,6 @@ impl Yumush { danger_button( format!("ban_report_{}", report.id), "Ban", - false, palette, entity_action(entity, move |yumush, window, cx| { yumush.ban_report_target(&ban_id, &ban_reason, window, cx) diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs index 6c3d498..295fea7 100644 --- a/crates/client/src/gui/builder/server.rs +++ b/crates/client/src/gui/builder/server.rs @@ -1,10 +1,20 @@ use common::model::ServerSettings; -use gpui_kit::{AnyElement, Context, Entity, IntoElement, Window}; +use gpui_kit::{ + AnyElement, App, Context, Entity, IntoElement, Window, component::input::InputState, +}; -use super::ui::{ - field_row, kilobytes_bytes, kilobytes_text, list_card, megabytes_bytes, megabytes_text, number, +use super::ui::{field_row, list_card, number, to_bytes, to_units}; +use crate::gui::{ + KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented, }; -use crate::gui::{Palette, Yumush, auth::field, notify_error, settings_page::segmented}; + +fn input_text(input: &Entity, cx: &App) -> String { + input.read(cx).text().to_string() +} + +fn input_number(input: &Entity, cx: &App) -> u32 { + number(&input_text(input, cx)) +} impl Yumush { pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context) { @@ -18,21 +28,21 @@ impl Yumush { }); self.chat.server_limit.update(cx, |input, cx| { input.set_value( - megabytes_text(settings.max_attachment_bytes).as_str(), + to_units(settings.max_attachment_bytes, MB as u64).as_str(), window, cx, ) }); self.chat.server_user_quota.update(cx, |input, cx| { input.set_value( - megabytes_text(settings.user_quota_bytes).as_str(), + to_units(settings.user_quota_bytes, MB as u64).as_str(), window, cx, ) }); self.chat.server_community_quota.update(cx, |input, cx| { input.set_value( - megabytes_text(settings.community_quota_bytes).as_str(), + to_units(settings.community_quota_bytes, MB as u64).as_str(), window, cx, ) @@ -68,7 +78,7 @@ impl Yumush { }); self.chat.server_max_avatar.update(cx, |input, cx| { input.set_value( - kilobytes_text(settings.max_avatar_bytes).as_str(), + to_units(settings.max_avatar_bytes, KB as u64).as_str(), window, cx, ) @@ -88,73 +98,25 @@ impl Yumush { } pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context) { - let name = self.chat.server_name.read(cx).text().to_string(); - let max_attachment_bytes = - megabytes_bytes(&self.chat.server_limit.read(cx).text().to_string()); - let user_quota_bytes = - megabytes_bytes(&self.chat.server_user_quota.read(cx).text().to_string()); - let community_quota_bytes = - megabytes_bytes(&self.chat.server_community_quota.read(cx).text().to_string()); - let message_retention_days = number( - &self - .chat - .server_message_retention - .read(cx) - .text() - .to_string(), - ); - let attachment_retention_days = number( - &self - .chat - .server_attachment_retention - .read(cx) - .text() - .to_string(), - ); - let announcement = self.chat.server_announcement.read(cx).text().to_string(); - let max_communities_per_user = - number(&self.chat.server_max_communities.read(cx).text().to_string()); - let max_message_length = number( - &self - .chat - .server_max_message_length - .read(cx) - .text() - .to_string(), - ); - let max_avatar_bytes = - kilobytes_bytes(&self.chat.server_max_avatar.read(cx).text().to_string()); - let messages_per_minute = number( - &self - .chat - .server_messages_per_minute - .read(cx) - .text() - .to_string(), - ); - let logins_per_minute = number( - &self - .chat - .server_logins_per_minute - .read(cx) - .text() - .to_string(), - ); + let chat = &self.chat; let settings = ServerSettings { - name, - registration_open: self.chat.server_registration_open, - max_attachment_bytes, - maintenance: self.chat.server_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, + name: input_text(&chat.server_name, cx), + registration_open: chat.server_registration_open, + max_attachment_bytes: to_bytes(&input_text(&chat.server_limit, cx), MB as u64), + maintenance: chat.server_maintenance, + user_quota_bytes: to_bytes(&input_text(&chat.server_user_quota, cx), MB as u64), + community_quota_bytes: to_bytes( + &input_text(&chat.server_community_quota, cx), + MB as u64, + ), + message_retention_days: input_number(&chat.server_message_retention, cx), + attachment_retention_days: input_number(&chat.server_attachment_retention, cx), + announcement: input_text(&chat.server_announcement, cx), + max_communities_per_user: input_number(&chat.server_max_communities, cx), + max_message_length: input_number(&chat.server_max_message_length, cx), + max_avatar_bytes: to_bytes(&input_text(&chat.server_max_avatar, cx), KB as u64), + messages_per_minute: input_number(&chat.server_messages_per_minute, cx), + logins_per_minute: input_number(&chat.server_logins_per_minute, cx), }; let network = self.network.clone(); diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index 6b225e9..bc3f570 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -4,11 +4,12 @@ use gpui_kit::{ assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, }; -use super::ui::{accent_button, card, card_header, list_card, list_row, toolbar}; +use super::ui::{ + accent_button, card, card_header, delete_icon_button, list_card, list_row, toolbar, +}; use crate::gui::{ - DATE, Palette, Tooltip, Yumush, + DATE, Palette, Yumush, auth::field, - clickable, community_settings::{search_text, user_name}, entity_action, id_time, notify_error, storage, text, }; @@ -83,25 +84,14 @@ fn attachment_row( palette: Palette, ) -> Div { let attachment_id = info.attachment.id.clone(); - let delete = clickable( + let delete = delete_icon_button( format!("delete_attachment_{}", info.attachment.id), + pending, palette, entity_action(entity, move |yumush, window, cx| { yumush.delete_builder_attachment(&attachment_id, window, cx) }), - ) - .tip(if pending { "Confirm" } else { "Delete" }) - .size(px(26.)) - .flex() - .flex_shrink_0() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.danger) - .when(pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) - }) - .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.))); + ); list_row() .child( diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs index 37bea0e..49b3806 100644 --- a/crates/client/src/gui/builder/ui.rs +++ b/crates/client/src/gui/builder/ui.rs @@ -1,32 +1,20 @@ -use crate::gui::{KB, MB, Palette, Tooltip as _, clickable, primary_button, text}; +use crate::gui::{Palette, Tooltip as _, clickable, primary_button, text}; use gpui_kit::{ AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window, assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, }; use jiff::{civil::Date, tz::TimeZone}; -pub(super) fn megabytes_bytes(text: &str) -> u64 { +pub(super) fn to_bytes(text: &str, unit: u64) -> u64 { text.trim() .parse::() .ok() - .and_then(|megabytes| megabytes.checked_mul(MB as u64)) + .and_then(|units| units.checked_mul(unit)) .unwrap_or(0) } -pub(super) fn kilobytes_bytes(text: &str) -> u64 { - text.trim() - .parse::() - .ok() - .and_then(|kilobytes| kilobytes.checked_mul(KB as u64)) - .unwrap_or(0) -} - -pub(super) fn megabytes_text(bytes: u64) -> String { - (bytes / MB as u64).to_string() -} - -pub(super) fn kilobytes_text(bytes: u64) -> String { - (bytes / KB as u64).to_string() +pub(super) fn to_units(bytes: u64, unit: u64) -> String { + (bytes / unit).to_string() } pub(super) fn number(text: &str) -> u32 { @@ -53,6 +41,25 @@ pub(super) fn icon_button( .child(Icon::new(icon).w(px(14.)).h(px(14.))) } +pub(super) fn delete_icon_button( + id: String, + pending: bool, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + icon_button( + id, + IconName::Trash, + if pending { "Confirm" } else { "Delete" }, + palette.danger, + palette, + action, + ) + .when(pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) +} + pub(super) fn action_button( id: String, icon: IconName, @@ -145,7 +152,6 @@ pub(super) fn action_group( pub(super) fn danger_button( id: String, label: &'static str, - pending: bool, palette: Palette, action: impl Fn(&mut Window, &mut App) + 'static, ) -> impl IntoElement { @@ -160,26 +166,46 @@ pub(super) fn danger_button( .border_1() .border_color(palette.danger.opacity(0.5)) .text_color(palette.danger) - .when(pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) - }) - .child(if pending { "Confirm" } else { label }) + .child(label) } -pub(super) fn day_millis(text: &str, end_of_day: bool) -> Option { - let date: Date = text.parse().ok()?; - let date = if end_of_day { - date.tomorrow().ok()? - } else { - date - }; +fn epoch_ms(date: Date) -> Option { let millis = date .to_zoned_datetime(TimeZone::system()) .ok()? .timestamp() .as_millisecond(); + u64::try_from(millis).ok() +} + +pub(super) fn start_of_day_ms(text: &str) -> Option { + let date: Date = text.parse().ok()?; + epoch_ms(date) +} + +pub(super) fn end_of_day_ms(text: &str) -> Option { + let date: Date = text.parse().ok()?; + epoch_ms(date.tomorrow().ok()?)?.checked_sub(1) +} - u64::try_from(millis - i64::from(end_of_day)).ok() +pub(super) fn rows_body(rows: Vec
, empty: &str, palette: Palette) -> Div { + if rows.is_empty() { + return div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child(empty.to_string()); + } + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) } pub(super) fn accent_button( diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 7589661..eeb5657 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -2,7 +2,7 @@ use std::future::Future; use common::{ error::Error, - model::{Account, Role, SessionInfo, User}, + model::{Account, BanScope, Role, SessionInfo, User}, permission, time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, }; @@ -338,7 +338,10 @@ impl Yumush { } pub(super) fn toggle_builder_ban_ip(&mut self, cx: &mut Context) { - self.chat.builder_ban_ip = !self.chat.builder_ban_ip; + self.chat.builder_ban_scope = match self.chat.builder_ban_scope { + BanScope::Account => BanScope::AccountAndIp, + BanScope::AccountAndIp => BanScope::Account, + }; cx.notify(); } @@ -349,12 +352,12 @@ impl Yumush { let reason = self.chat.builder_ban_reason.read(cx).text().to_string(); let reason = reason.trim().to_string(); let reason = (!reason.is_empty()).then_some(reason); - let ip = self.chat.builder_ban_ip; + let scope = self.chat.builder_ban_scope; self.chat .builder_ban_reason .update(cx, |input, cx| input.set_value("", window, cx)); self.builder_user_action(window, cx, move |network| async move { - network.ban_user(&user_id, reason.as_deref(), ip).await + network.ban_user(&user_id, reason.as_deref(), scope).await }); } @@ -506,7 +509,7 @@ impl Yumush { entity: &Entity, palette: Palette, ) -> Div { - let ip_label = if self.chat.builder_ban_ip { + let ip_label = if self.chat.builder_ban_scope == BanScope::AccountAndIp { "IP: on" } else { "IP: off" diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs index 28c1ea4..abb75cb 100644 --- a/crates/client/src/gui/builder/voice.rs +++ b/crates/client/src/gui/builder/voice.rs @@ -6,57 +6,26 @@ use common::{ }; use gpui_kit::{ AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, - div, prelude::FluentBuilder as _, px, + div, px, }; -use super::ui::{card, card_header, icon_button, list_card, pill}; +use super::ui::{card, card_header, icon_button, list_card, pill, rows_body}; use crate::{ gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text}, network::NetworkHandle, }; -fn rows_body(rows: Vec
, empty: &str, palette: Palette) -> Div { - if rows.is_empty() { - return div() - .py(px(24.)) - .flex() - .justify_center() - .text_size(text(12.)) - .text_color(palette.muted) - .child(empty.to_string()); - } - div() - .flex() - .flex_col() - .children(rows.into_iter().enumerate().map(|(index, row)| { - row.when(index > 0, |row| { - row.border_t_1().border_color(palette.border) - }) - })) -} - impl Yumush { pub(super) fn load_voice_rooms(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let rooms = match network.voice_rooms().await { - Ok(rooms) => rooms, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { + self.fetch_builder( + window, + cx, + |network| async move { network.voice_rooms().await }, + |yumush, rooms, cx| { yumush.chat.builder_voice_rooms = rooms; cx.notify(); - }); - }) - .detach(); + }, + ); } pub(super) fn voice_action( diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index ff96209..247c65b 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -28,7 +28,7 @@ use common::{ constant::MESSAGE_PAGE_LIMIT, event::Event, model::{ - ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, CallLog, Community, + Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community, CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, @@ -183,7 +183,7 @@ pub struct Chat { pub(super) builder_timeout: Entity, pub(super) pending_builder_ban: Option, pub(super) builder_ban_reason: Entity, - pub(super) builder_ban_ip: bool, + pub(super) builder_ban_scope: BanScope, pub(super) builder_bans: Vec, pub(super) builder_invites: Vec, pub(super) invite_uses: Entity, @@ -259,11 +259,6 @@ impl Chat { ) .detach(); - let username_input = editable_input("Username...", Yumush::save_username, window, cx); - let status_input = editable_input("Status...", Yumush::save_status, window, cx); - let community_name_input = - editable_input("Community name...", Yumush::save_community_name, window, cx); - let search_input = new_input("Find user", window, cx); cx.subscribe_in( &search_input, @@ -289,49 +284,7 @@ impl Chat { let builder_search = new_input("Search...", window, cx); let builder_password = new_input("New password...", window, cx); builder_password.update(cx, |input, cx| input.set_masked(true, window, cx)); - let builder_rename = new_input("New username...", window, cx); - let server_name = new_input("Server name...", window, cx); - let server_limit = new_input("", window, cx); - let server_user_quota = new_input("", window, cx); - let server_community_quota = new_input("", window, cx); - let server_message_retention = new_input("", window, cx); - let server_attachment_retention = new_input("", window, cx); - let server_announcement = new_input("Announcement...", window, cx); - let server_max_communities = new_input("", window, cx); - let server_max_message_length = new_input("Max message length...", window, cx); - let server_max_avatar = new_input("", window, cx); - let server_messages_per_minute = new_input("", window, cx); - let server_logins_per_minute = new_input("", window, cx); - let builder_timeout = new_input("Minutes...", window, cx); - let builder_ban_reason = new_input("Reason...", window, cx); - let invite_uses = new_input("Uses...", window, cx); - let invite_hours = new_input("Hours", window, cx); - let new_username = new_input("Username...", window, cx); let new_password = new_input("Password...", window, cx); - let report_reason = new_input("Reason...", window, cx); - let builder_message_text = new_input("Text...", window, cx); - let builder_message_user = new_input("User...", window, cx); - let builder_message_community = new_input("Community...", window, cx); - let builder_message_from = new_input("From YYYY-MM-DD", window, cx); - let builder_message_to = new_input("To YYYY-MM-DD", window, cx); - let builder_attachment_user = new_input("User...", window, cx); - let builder_attachment_community = new_input("Community...", window, cx); - let builder_log_actor = new_input("Actor...", window, cx); - let builder_log_target = new_input("Target...", window, cx); - let builder_log_from = new_input("From YYYY-MM-DD", window, cx); - let builder_log_to = new_input("To YYYY-MM-DD", window, cx); - let builder_log_action = cx.new(|cx| { - SelectState::new( - SearchableVec::new( - std::iter::once("All") - .chain(ACTION_NAMES) - .collect::>(), - ), - Some(IndexPath::new(0)), - window, - cx, - ) - }); new_password.update(cx, |input, cx| input.set_masked(true, window, cx)); for search in [&ban_search, &log_search, &builder_search] { cx.subscribe_in(search, window, |_, _, event, window, cx| { @@ -383,9 +336,14 @@ impl Chat { tab: SidebarTab::Communities, sidebar_collapsed: false, view: View::Chat, - username_input, - community_name_input, - status_input, + username_input: editable_input("Username...", Yumush::save_username, window, cx), + community_name_input: editable_input( + "Community name...", + Yumush::save_community_name, + window, + cx, + ), + status_input: editable_input("Status...", Yumush::save_status, window, cx), avatars: HashMap::new(), hues: HashMap::new(), avatar_requests: HashSet::new(), @@ -402,22 +360,33 @@ impl Chat { builder_overview: None, builder_logs: vec![], builder_stats: vec![], - builder_log_actor, - builder_log_target, - builder_log_action, - builder_log_from, - builder_log_to, + builder_log_actor: new_input("Actor...", window, cx), + builder_log_target: new_input("Target...", window, cx), + builder_log_action: cx.new(|cx| { + SelectState::new( + SearchableVec::new( + std::iter::once("All") + .chain(AdminActionKind::ALL.into_iter().map(AdminActionKind::as_str)) + .collect::>(), + ), + Some(IndexPath::new(0)), + window, + cx, + ) + }), + builder_log_from: new_input("From YYYY-MM-DD", window, cx), + builder_log_to: new_input("To YYYY-MM-DD", window, cx), builder_search, builder_communities: vec![], pending_community_delete: None, - builder_message_text, - builder_message_user, - builder_message_community, - builder_message_from, - builder_message_to, + builder_message_text: new_input("Text...", window, cx), + builder_message_user: new_input("User...", window, cx), + builder_message_community: new_input("Community...", window, cx), + builder_message_from: new_input("From YYYY-MM-DD", window, cx), + builder_message_to: new_input("To YYYY-MM-DD", window, cx), builder_messages: vec![], - builder_attachment_user, - builder_attachment_community, + builder_attachment_user: new_input("User...", window, cx), + builder_attachment_community: new_input("Community...", window, cx), builder_usage_users: vec![], builder_usage_communities: vec![], builder_attachments: vec![], @@ -426,41 +395,41 @@ impl Chat { pending_builder_purge: None, transfer: None, builder_password, - server_name, - server_limit, - server_user_quota, - server_community_quota, - server_message_retention, - server_attachment_retention, - server_announcement, - server_max_communities, - server_max_message_length, - server_max_avatar, - server_messages_per_minute, - server_logins_per_minute, + server_name: new_input("Server name...", window, cx), + server_limit: new_input("", window, cx), + server_user_quota: new_input("", window, cx), + server_community_quota: new_input("", window, cx), + server_message_retention: new_input("", window, cx), + server_attachment_retention: new_input("", window, cx), + server_announcement: new_input("Announcement...", window, cx), + server_max_communities: new_input("", window, cx), + server_max_message_length: new_input("Max message length...", window, cx), + server_max_avatar: new_input("", window, cx), + server_messages_per_minute: new_input("", window, cx), + server_logins_per_minute: new_input("", window, cx), server_registration_open: true, server_maintenance: false, pending_builder_timeout: None, - builder_timeout, + builder_timeout: new_input("Minutes...", window, cx), pending_builder_ban: None, - builder_ban_reason, - builder_ban_ip: false, + builder_ban_reason: new_input("Reason...", window, cx), + builder_ban_scope: BanScope::Account, builder_bans: vec![], builder_invites: vec![], - invite_uses, - invite_hours, + invite_uses: new_input("Uses...", window, cx), + invite_hours: new_input("Hours", window, cx), pending_invite_delete: None, - new_username, + new_username: new_input("Username...", window, cx), new_password, pending_builder_password: None, builder_sessions: None, pending_builder_rename: None, - builder_rename, + builder_rename: new_input("New username...", window, cx), builder_reports: vec![], report_filter: Some(ReportStatus::Open), open_reports: 0, report: None, - report_reason, + report_reason: new_input("Reason...", window, cx), voice: HashMap::new(), drafts: HashMap::new(), voice_state: VoiceState::Off, @@ -478,13 +447,10 @@ impl Chat { } } - pub(super) fn unread_total(&self, group: bool) -> Unread { + fn unread_where(&self, keep: impl Fn(&CommunityKind) -> bool) -> Unread { self.communities .iter() - .filter(|community| { - !self.muted.contains(&community.id) - && matches!(community.kind, CommunityKind::Group) == group - }) + .filter(|community| !self.muted.contains(&community.id) && keep(&community.kind)) .filter_map(|community| self.unread.get(&community.id)) .fold(Unread::default(), |total, unread| Unread { messages: total.messages + unread.messages, @@ -493,6 +459,14 @@ impl Chat { }) } + pub(super) fn unread_groups(&self) -> Unread { + self.unread_where(|kind| matches!(kind, CommunityKind::Group)) + } + + pub(super) fn unread_direct(&self) -> Unread { + self.unread_where(|kind| !matches!(kind, CommunityKind::Group)) + } + pub fn focus(&self, window: &mut Window, cx: &mut Context) { let input = match self.selected_community_id { Some(_) => &self.message_input, @@ -880,10 +854,6 @@ impl Chat { permission::effective_rank(user.role, rank) } - pub fn my_rank(&self, me: &User) -> Option { - self.rank_of(me) - } - pub fn rank_of_id(&self, user_id: &str) -> Option { self.member(user_id).and_then(|user| self.rank_of(user)) } @@ -891,8 +861,8 @@ impl Chat { pub fn can_pin(&self, me: &User) -> bool { let direct = self .selected_community() - .is_some_and(|community| matches!(community.kind, CommunityKind::Direct { .. })); - permission::can_pin(self.my_rank(me), direct) + .is_some_and(|community| community.kind.is_direct()); + permission::can_pin(self.rank_of(me), direct) } fn update_pin(&mut self, message: &Message) { @@ -905,7 +875,7 @@ impl Chat { pub fn can_delete(&self, message: &Message, me: &User) -> bool { permission::can_delete_message( - self.my_rank(me), + self.rank_of(me), self.rank_of_id(&message.user_id), message.user_id == me.id, ) @@ -1016,7 +986,7 @@ impl Chat { self.pending_builder_rename = None; self.pending_builder_timeout = None; self.pending_builder_ban = None; - self.builder_ban_ip = false; + self.builder_ban_scope = BanScope::Account; self.builder_bans.clear(); self.builder_invites.clear(); self.pending_invite_delete = None; @@ -1228,15 +1198,7 @@ impl Yumush { let text = self.announcement()?; Some( - div() - .flex() - .items_center() - .justify_between() - .gap(px(8.)) - .px(px(12.)) - .py(px(6.)) - .bg(palette.accent) - .text_color(palette.on_accent) + accent_bar(palette) .child(text.to_string()) .child( clickable( @@ -1311,15 +1273,7 @@ impl Yumush { return None; } Some( - div() - .flex() - .items_center() - .justify_between() - .gap(px(8.)) - .px(px(12.)) - .py(px(6.)) - .bg(palette.accent) - .text_color(palette.on_accent) + accent_bar(palette) .child(format!("{count} new messages")) .child( div() @@ -1381,7 +1335,7 @@ impl Yumush { .absolute() .top(px(-6.)) .right(px(-6.)) - .children(super::sidebar::badge( + .children(super::sidebar::unread_badge( palette, false, Some(&Unread { @@ -1548,7 +1502,7 @@ impl Yumush { self.load_members(window, cx); self.load_pins(window, cx); self.load_voice(window, cx); - self.load_latest_messages(window, cx); + self.load_messages(None, window, cx); cx.notify(); } @@ -1570,7 +1524,7 @@ impl Yumush { if self.chat.selected_community_id.is_some() { self.load_members(window, cx); - self.load_latest_messages(window, cx); + self.load_messages(None, window, cx); } } @@ -1757,6 +1711,11 @@ impl Yumush { ) { self.chat.jump = Some(message_id); self.chat.reveal_jump(); + self.continue_jump(window, cx); + cx.notify(); + } + + fn continue_jump(&mut self, window: &mut Window, cx: &mut Context) { if self.chat.jump.is_none() { Self::fade_highlight(cx); } else if self.chat.history == History::More { @@ -1764,7 +1723,6 @@ impl Yumush { } else { self.chat.jump = None; } - cx.notify(); } fn fade_highlight(cx: &mut Context) { @@ -1775,10 +1733,6 @@ impl Yumush { .detach(); } - fn load_latest_messages(&self, window: &mut Window, cx: &mut Context) { - self.load_messages(None, window, cx); - } - fn load_older_messages(&self, window: &mut Window, cx: &mut Context) { let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else { return; @@ -1813,13 +1767,7 @@ impl Yumush { .chat .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str())); if seeking { - if yumush.chat.jump.is_none() { - Self::fade_highlight(cx); - } else if yumush.chat.history == History::More { - yumush.load_older_messages(window, cx); - } else { - yumush.chat.jump = None; - } + yumush.continue_jump(window, cx); } if let Some(message_id) = newest.filter(|_| latest) { yumush.mark_read(&community_id, &message_id, cx); @@ -1959,7 +1907,9 @@ impl Yumush { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { - let muted = muted || yumush.mic_locked() || yumush.hidden_in(&community_id); + let muted = muted + || yumush.is_server_muted() + || yumush.hidden_in(&community_id); yumush.network.set_muted(muted); yumush.chat.voice.insert(community_id.clone(), participants); yumush.chat.voice_state = VoiceState::In { @@ -2030,10 +1980,6 @@ impl Yumush { .is_some_and(|me| self.chat.server_muted.contains(&me.id)) } - pub(super) fn mic_locked(&self) -> bool { - self.is_server_muted() - } - fn hidden_in(&self, community_id: &str) -> bool { self.chat.ghost || !self.chat.joined(community_id) } @@ -2044,16 +1990,8 @@ impl Yumush { .is_some_and(|community_id| self.hidden_in(community_id)) } - pub(super) fn force_mute(&mut self, cx: &mut Context) { - if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { - *muted = true; - self.network.set_muted(true); - } - cx.notify(); - } - fn toggle_mute(&mut self, window: &mut Window, cx: &mut Context) { - if self.mic_locked() { + if self.is_server_muted() { return; } let Some((muted, _)) = self.chat.voice_flags() else { @@ -2066,7 +2004,7 @@ impl Yumush { self.set_muted(!muted, cx); } - fn set_muted(&mut self, value: bool, cx: &mut Context) { + pub(super) fn set_muted(&mut self, value: bool, cx: &mut Context) { if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { *muted = value; self.network.set_muted(value); @@ -2269,15 +2207,7 @@ impl Yumush { let accept_id = community_id.clone(); Some( - div() - .flex() - .items_center() - .justify_between() - .gap(px(8.)) - .px(px(12.)) - .py(px(6.)) - .bg(palette.accent) - .text_color(palette.on_accent) + accent_bar(palette) .child( div() .flex() @@ -2505,25 +2435,31 @@ impl Yumush { } } +struct MemberRow { + user: User, + rank: Option, + in_voice: bool, + muted: bool, + presence: Presence, +} + fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) -> impl IntoElement { let chat = &yumush.chat; let entity = entity.clone(); - let voice: Vec = chat + let voice = chat .selected_community_id .as_deref() - .map(|community_id| chat.voice_ids(community_id).to_vec()) + .map(|community_id| chat.voice_ids(community_id)) .unwrap_or_default(); - let members: Vec<(User, Option, bool, bool, Presence)> = chat + let members: Vec = chat .members .iter() - .map(|member| { - ( - member.user.clone(), - chat.rank_of(&member.user), - voice.contains(&member.user.id), - chat.server_muted.contains(&member.user.id), - yumush.presence_of(&member.user.id), - ) + .map(|member| MemberRow { + user: member.user.clone(), + rank: chat.rank_of(&member.user), + in_voice: voice.contains(&member.user.id), + muted: chat.server_muted.contains(&member.user.id), + presence: yumush.presence_of(&member.user.id), }) .collect(); let avatars = chat.avatars.clone(); @@ -2533,10 +2469,7 @@ fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) - .appearance(false) .trigger(MembersTrigger { palette, - members: members - .iter() - .map(|(user, _, _, _, _)| user.clone()) - .collect(), + members: members.iter().map(|row| row.user.clone()).collect(), avatars: avatars.clone(), }) .content(move |_, _, _| { @@ -2556,7 +2489,7 @@ fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) - .children( members .iter() - .map(|(user, rank, in_voice, muted, presence)| { + .map(|MemberRow { user, rank, in_voice, muted, presence }| { profile_popover( format!("member_{}", user.id), Anchor::TopRight, @@ -2623,6 +2556,18 @@ fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) - }) } +fn accent_bar(palette: Palette) -> Div { + div() + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .px(px(12.)) + .py(px(6.)) + .bg(palette.accent) + .text_color(palette.on_accent) +} + fn new_divider(palette: Palette) -> impl IntoElement { div() .flex() @@ -2716,9 +2661,7 @@ fn render_message( return render_call(message, call, chat, me, palette); } let author = chat.author(&message.user_id); - let username = author - .map(|user| user.username.as_str()) - .unwrap_or("unknown"); + let username = author.map_or("unknown", |user| user.username.as_str()); let name = div() .flex() .items_center() diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index 13de0e4..98c4843 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -10,8 +10,7 @@ use common::{ }; use gpui_kit::{ AnyElement, App, AsyncWindowContext, Context, Div, Entity, Image, InteractiveElement, - IntoElement, ParentElement, PathPromptOptions, StatefulInteractiveElement, Styled, WeakEntity, - Window, + IntoElement, ParentElement, StatefulInteractiveElement, Styled, WeakEntity, Window, component::{ WindowExt, input::{Input, InputState}, @@ -28,8 +27,8 @@ use super::{ clickable, community_icon, entity_action, id_time, notify_error, profile::user_link, settings_page::{ - Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file, - row, section, text_row, + Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, + section, text_row, }, }; @@ -78,21 +77,15 @@ impl Yumush { palette: Palette, cx: &App, ) -> impl IntoElement { - let name = self - .chat - .selected_community() + let community = self.chat.selected_community(); + let name = community .map(|community| community.name.clone()) .unwrap_or_default(); let actor = self.actor_rank(); - let community_id = self.chat.selected_community_id.clone().unwrap_or_default(); let bans_count = self.chat.bans.len(); let mut sections = Vec::new(); - if let Some(community) = self - .chat - .selected_community() - .filter(|_| permission::can_rename_community(actor)) - { + if let Some(community) = community.filter(|_| permission::can_rename_community(actor)) { sections.push( picture_card( Picture { @@ -137,11 +130,7 @@ impl Yumush { .into_any_element(), ); } - if let Some(community) = self - .chat - .selected_community() - .filter(|_| permission::can_manage_voice(actor)) - { + if let Some(community) = community.filter(|_| permission::can_manage_voice(actor)) { sections.push( section( "Voice", @@ -191,10 +180,10 @@ impl Yumush { sections.push(section("Moderation", palette, moderation).into_any_element()); } let mut danger = Vec::new(); - if permission::can_leave(actor) { + if let Some(community) = community.filter(|_| permission::can_leave(actor)) { danger.push(row( "Leave community", - leave_control(entity, community_id, palette), + leave_control(entity, community.id.clone(), palette), )); } if permission::can_delete_community(actor) { @@ -263,26 +252,13 @@ impl Yumush { let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; - let picked = cx.prompt_for_paths(PathPromptOptions { - files: true, - directories: false, - multiple: false, - prompt: None, - }); + let picked = picked_avatar(cx, self.max_avatar_bytes()); let network = self.network.clone(); - let maximum = self.max_avatar_bytes(); cx.spawn_in(window, async move |this, cx| { - let Ok(Ok(Some(paths))) = picked.await else { - return; - }; - let Some(path) = paths.into_iter().next() else { + let Some(prepared) = picked.await else { return; }; - let prepared = cx - .background_executor() - .spawn(async move { read_avatar_file(&path, maximum) }) - .await; let result = match prepared { Ok(bytes) => { network diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index d3e9c1e..a3381f9 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -9,8 +9,8 @@ use common::{ validate::{validate_message_body, validate_new_message, validate_poll}, }; use gpui_kit::{ - Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, - KeyBinding, ParentElement, Styled, Window, actions, + Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, + IntoElement, KeyBinding, ParentElement, Styled, Window, actions, assets::IconName, component::{ Icon, WindowExt, @@ -31,7 +31,7 @@ use super::{ actions!(composer, [Bold, Italic, Code, Strike]); -pub const CONTEXT: &str = "MessageComposer"; +const CONTEXT: &str = "MessageComposer"; const FORMAT_ROWS: [(&str, &str); 6] = [ ("**bold**", "Ctrl+B"), @@ -471,22 +471,31 @@ fn wrap(input: &Entity, mark: &str, window: &mut Window, cx: &mut Ap }); } +pub(super) fn trigger_icon( + id: impl Into, + icon: IconName, + size: f32, + palette: Palette, +) -> Trigger { + Trigger::new(hoverable( + id, + div() + .size(px(size)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(icon).w(px(14.)).h(px(14.))), + palette, + )) +} + pub fn format_popover(palette: Palette) -> impl IntoElement { Popover::new("format_popover") .anchor(Anchor::BottomLeft) .appearance(false) - .trigger(Trigger::new(hoverable( - "format_trigger", - div() - .size(px(28.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::Type).w(px(14.)).h(px(14.))), - palette, - ))) + .trigger(trigger_icon("format_trigger", IconName::Type, 28., palette)) .content(move |_, _, _| { pop_in( "format_list", @@ -515,7 +524,7 @@ pub fn format_popover(palette: Palette) -> impl IntoElement { }) } -fn poll_field(input: &Entity, palette: Palette) -> impl IntoElement { +pub(super) fn poll_field(input: &Entity, palette: Palette) -> impl IntoElement { div() .h(px(30.)) .px(px(10.)) @@ -543,18 +552,7 @@ pub fn poll_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i Popover::new("poll_popover") .anchor(Anchor::BottomLeft) .appearance(false) - .trigger(Trigger::new(hoverable( - "poll_trigger", - div() - .size(px(28.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))), - palette, - ))) + .trigger(trigger_icon("poll_trigger", IconName::ChartBar, 28., palette)) .content(move |_, _, cx| { let popover = cx.entity(); let toggle = entity.clone(); diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index 47469ce..a1286c3 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -5,12 +5,16 @@ use gpui_kit::{ component::{ WindowExt, checkbox::Checkbox, - input::{Input, InputEvent, InputState}, + input::{InputEvent, InputState}, }, div, px, }; -use super::{Yumush, clickable, community_name, composer::Composer, notify_error, palette}; +use super::{ + Yumush, clickable, + composer::{Composer, poll_field}, + community_name, notify_error, palette, +}; pub struct Forward { yumush: Entity, @@ -97,22 +101,7 @@ impl Render for Forward { .flex_col() .gap(px(10.)) .child( - div() - .h(px(30.)) - .px(px(10.)) - .flex() - .items_center() - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.field) - .child( - Input::new(&self.filter) - .appearance(false) - .text_color(palette.text) - .flex_1() - .min_w_0(), - ), + poll_field(&self.filter, palette), ) .child( Checkbox::new("keep_authors") @@ -160,7 +149,7 @@ impl Yumush { &mut self, selected: Vec, community_id: String, - snippet: bool, + keep_authors: bool, window: &mut Window, cx: &mut Context, ) { @@ -179,7 +168,10 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.forward_messages(ids, &community_id, snippet).await { + if let Err(error) = network + .forward_messages(ids, &community_id, keep_authors) + .await + { notify_error(&this, cx, error); } }) diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index 77bdcb9..5b32852 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -8,9 +8,9 @@ use std::{ use common::model::{Attachment, AttachmentKind, Message}; use gpui_kit::{ - App, AppContext, Context, Entity, FontWeight, Image, ImageFormat, InteractiveElement, - IntoElement, ParentElement, PathPromptOptions, RenderImage, StatefulInteractiveElement, Styled, - Subscription, Task, Window, + App, AppContext, AsyncWindowContext, Context, Entity, FontWeight, Image, ImageFormat, + InteractiveElement, IntoElement, ParentElement, PathPromptOptions, RenderImage, + StatefulInteractiveElement, Styled, Subscription, Task, WeakEntity, Window, assets::IconName, component::{ Icon, WindowExt, @@ -29,6 +29,7 @@ use super::{ use crate::{ embed::{self, Embed, EmbedKind}, media::{Player, voice_note as note}, + network::NetworkHandle, }; const FRAME_TICK: Duration = Duration::from_millis(16); @@ -120,7 +121,7 @@ fn fit(width: Option, height: Option, limit: (f32, f32)) -> (f32, f32) } fn cache_path(attachment: &Attachment) -> Option { - let directory = dirs::cache_dir()?.join("yumush").join("media"); + let directory = note::media_cache_dir()?; std::fs::create_dir_all(&directory).ok()?; let extension = attachment .name @@ -135,6 +136,35 @@ pub fn time_text(time: Duration) -> String { format!("{}:{:02}", seconds / 60, seconds % 60) } +fn duration_secs(player: &Player) -> f32 { + player + .info() + .duration + .unwrap_or_default() + .as_secs_f32() + .max(0.1) +} + +pub(super) async fn upload_file( + this: &WeakEntity, + network: &NetworkHandle, + community_id: &str, + path: PathBuf, + maximum: Option, + cx: &mut AsyncWindowContext, +) -> Result { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.uploading += 1; + cx.notify(); + }); + let uploaded = network.upload_attachment(community_id, path, maximum).await; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.uploading -= 1; + cx.notify(); + }); + uploaded +} + fn to_render_image(frame: &crate::media::Frame) -> Option> { let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) @@ -265,15 +295,9 @@ impl Yumush { return; }; for path in paths { + let result = + upload_file(&this, &network, &community_id, path, maximum, cx).await; let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.uploading += 1; - cx.notify(); - }); - let result = network - .upload_attachment(&community_id, path, maximum) - .await; - let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.uploading -= 1; if let Ok(attachment) = &result { yumush.chat.media.pending.push(attachment.clone()); } @@ -417,11 +441,11 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let duration = player.info().duration.unwrap_or_default().as_secs_f32(); + let duration = duration_secs(&player); let seek = cx.new(|_| { SliderState::new() .min(0.) - .max(duration.max(0.1)) + .max(duration) .default_value(0.) }); let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| { @@ -760,12 +784,7 @@ fn waveform_view( .map_or(&[][..], |waveform| waveform.peaks.as_slice()); match state { Some(PlayState::Ready { player, .. }) => { - let duration = player - .info() - .duration - .unwrap_or_default() - .as_secs_f32() - .max(0.1); + let duration = duration_secs(player); let progress = player.position().as_secs_f32() / duration; let entity = entity.clone(); bars(levels, progress, palette, move |index, _, cx| { diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index ecf2b06..9d734ab 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -14,11 +14,12 @@ use gpui_kit::{ }; use super::{ - CLOCK, Palette, Tooltip as _, Trigger, Yumush, + CLOCK, Palette, Tooltip as _, Yumush, auth::field, avatar, chat::{Chat, ReportTarget}, - clickable, entity_action, hoverable, id_time, notify_error, pop_in, primary_button, sidebar, + clickable, composer::trigger_icon, entity_action, id_time, notify_error, pop_in, + primary_button, sidebar, }; pub fn reactions( @@ -84,22 +85,12 @@ pub fn react_popover( Popover::new(format!("react_{}", message.id)) .anchor(Anchor::TopRight) .appearance(false) - .trigger(Trigger::new(hoverable( + .trigger(trigger_icon( format!("react_trigger_{}", message.id), - div() - .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child( - Icon::new(IconName::FaceSlightlySmiling) - .w(px(14.)) - .h(px(14.)), - ), + IconName::FaceSlightlySmiling, + 24., palette, - ))) + )) .content(move |_, _, cx| { let popover = cx.entity(); pop_in( @@ -243,18 +234,7 @@ pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> Popover::new("search_popover") .anchor(Anchor::TopRight) .appearance(false) - .trigger(Trigger::new(hoverable( - "search_trigger", - div() - .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))), - palette, - ))) + .trigger(trigger_icon("search_trigger", IconName::Search, 24., palette)) .content(move |_, _, cx| { let popover = cx.entity(); pop_in( @@ -331,18 +311,7 @@ pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i Popover::new("pins_popover") .anchor(Anchor::TopRight) .appearance(false) - .trigger(Trigger::new(hoverable( - "pins_trigger", - div() - .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::Pin).w(px(14.)).h(px(14.))), - palette, - ))) + .trigger(trigger_icon("pins_trigger", IconName::Pin, 24., palette)) .content(move |_, _, cx| { let popover = cx.entity(); pop_in( diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index 3710dba..2437cf9 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -25,14 +25,14 @@ fn my_positions(poll: &Poll, user_id: &str) -> Vec { .collect() } -fn next_votes(poll: &Poll, user_id: &str, position: u32) -> Vec { - let mut mine = my_positions(poll, user_id); +fn next_votes(mine: &[u32], position: u32, multiple: bool) -> Vec { + let mut next = mine.to_vec(); if mine.contains(&position) { - mine.retain(|mine| *mine != position); - mine - } else if poll.multiple { - mine.push(position); - mine + next.retain(|vote| *vote != position); + next + } else if multiple { + next.push(position); + next } else { vec![position] } @@ -69,7 +69,7 @@ pub fn poll_card( .filter(|message| { !poll.closed && me.is_some_and(|me| { - me.id == message.user_id || chat.my_rank(me) >= Some(Rank::Moderator) + me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator) }) }) .map(|message| message.id.clone()); @@ -79,7 +79,7 @@ pub fn poll_card( let share = percent(count, voters); let picked = mine.contains(&(position as u32)); let next = me_id - .map(|id| next_votes(poll, id, position as u32)) + .map(|_| next_votes(&mine, position as u32, poll.multiple)) .unwrap_or_default(); let entity = entity.clone(); let id = format!("poll_option_{key}_{position}"); diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index 2469483..b4ff933 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -138,7 +138,7 @@ impl Card { menu_row( "profile_message", "Message", - IconName::MessageSquare, + menu_icon(IconName::MessageSquare), palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { @@ -153,7 +153,7 @@ impl Card { menu_row( "profile_report", "Report", - IconName::TriangleAlert, + menu_icon(IconName::TriangleAlert), palette.danger, palette, entity_action(entity, move |yumush, window, cx| { @@ -169,7 +169,7 @@ impl Card { menu_row( "profile_friend", label, - icon, + menu_icon(icon), palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { @@ -287,7 +287,7 @@ impl Card { menu_row( label.clone(), label, - IconName::Shield, + menu_icon(IconName::Shield), palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { @@ -306,7 +306,7 @@ impl Card { menu_row( "kick", "Kick", - IconName::Close, + menu_icon(IconName::Close), palette.danger, palette, yumush_action(entity, popover, move |yumush, window, cx| { @@ -319,7 +319,7 @@ impl Card { menu_row( "ban", "Ban", - IconName::Ban, + menu_icon(IconName::Ban), palette.danger, palette, yumush_action(entity, popover, move |yumush, window, cx| { @@ -345,7 +345,7 @@ impl Card { menu_row( "delete_user", label, - IconName::Trash, + menu_icon(IconName::Trash), palette.danger, palette, delete_user_action(&user_id, self.confirming, entity, popover), @@ -380,30 +380,26 @@ fn main_self_rows( palette: Palette, ) -> Vec { vec![ - presence_row( + drill_row(menu_row( "profile_presence", - presence, + presence.label(), + presence_dot(presence, palette), + palette.text, palette, card_menu_action(entity, CardMenu::Presence), - ) - .child(div().flex_1()) - .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.))) - .into_any_element(), - menu_row( + )), + drill_row(menu_row( "profile_accounts", "Accounts", - IconName::CircleUser, + menu_icon(IconName::CircleUser), palette.text, palette, card_menu_action(entity, CardMenu::Accounts), - ) - .child(div().flex_1()) - .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.))) - .into_any_element(), + )), menu_row( "profile_settings", "Settings", - IconName::Settings, + menu_icon(IconName::Settings), palette.text, palette, yumush_action(entity, popover, |yumush, window, cx| { @@ -414,7 +410,7 @@ fn main_self_rows( menu_row( "profile_logout", "Log out", - IconName::LogOut, + menu_icon(IconName::LogOut), palette.danger, palette, yumush_action(entity, popover, |yumush, window, cx| { @@ -436,7 +432,7 @@ fn accounts_rows( menu_row( format!("switch_{user_id}"), username.clone(), - IconName::CircleUser, + menu_icon(IconName::CircleUser), palette.text, palette, yumush_action(entity, popover, move |yumush, window, cx| { @@ -449,7 +445,7 @@ fn accounts_rows( menu_row( "profile_accounts_back", "Accounts", - IconName::ArrowLeft, + menu_icon(IconName::ArrowLeft), palette.muted, palette, card_menu_action(entity, CardMenu::Main), @@ -466,7 +462,7 @@ fn accounts_rows( menu_row( "profile_add_account", "Add account", - IconName::UserPlus, + menu_icon(IconName::UserPlus), palette.text, palette, yumush_action(entity, popover, |yumush, window, cx| { @@ -482,7 +478,7 @@ fn presence_rows(entity: &Entity, palette: Palette) -> Vec { menu_row( "profile_presence_back", "Status", - IconName::ArrowLeft, + menu_icon(IconName::ArrowLeft), palette.muted, palette, card_menu_action(entity, CardMenu::Main), @@ -491,9 +487,11 @@ fn presence_rows(entity: &Entity, palette: Palette) -> Vec { ]; rows.extend(Presence::ALL.into_iter().map(|presence| { - presence_row( + menu_row( format!("presence_{}", presence.as_str()), - presence, + presence.label(), + presence_dot(presence, palette), + palette.text, palette, entity_action(entity, move |yumush, window, cx| { yumush.set_presence(presence, window, cx) @@ -522,24 +520,6 @@ fn presence_dot(presence: Presence, palette: Palette) -> Div { .bg(presence_color(presence, palette)) } -fn presence_row( - id: impl Into, - presence: Presence, - palette: Palette, - on_click: impl Fn(&mut Window, &mut App) + 'static, -) -> Stateful
{ - clickable(id, palette, on_click) - .h(px(30.)) - .px(px(8.)) - .flex() - .items_center() - .gap(px(8.)) - .rounded(px(6.)) - .text_color(palette.text) - .child(presence_dot(presence, palette)) - .child(presence.label()) -} - fn yumush_action( entity: &Entity, popover: &Entity, @@ -576,10 +556,14 @@ fn delete_user_action( } } +fn menu_icon(icon: IconName) -> Icon { + Icon::new(icon).w(px(14.)).h(px(14.)) +} + fn menu_row( id: impl Into, label: impl Into, - icon: IconName, + leading: impl IntoElement, color: Hsla, palette: Palette, on_click: impl Fn(&mut Window, &mut App) + 'static, @@ -592,10 +576,16 @@ fn menu_row( .gap(px(8.)) .rounded(px(6.)) .text_color(color) - .child(Icon::new(icon).w(px(14.)).h(px(14.))) + .child(leading) .child(label.into()) } +fn drill_row(row: Stateful
) -> AnyElement { + row.child(div().flex_1()) + .child(menu_icon(IconName::ChevronRight)) + .into_any_element() +} + impl Yumush { fn open_removal( &self, diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index c70e698..9a526a5 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -1,10 +1,11 @@ use super::text; -use std::path::Path; +use std::{future::Future, path::Path}; use common::{error::Error, model::User}; use gpui_kit::{ - AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, - ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window, + AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla, + InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, + StatefulInteractiveElement, Styled, WeakEntity, Window, assets::IconName, component::{Icon, input::InputState, switch::Switch}, div, @@ -18,19 +19,6 @@ use super::{ }; use crate::settings::{self, FontSize, ThemeChoice}; -const THEMES: [(ThemeChoice, &str); 4] = [ - (ThemeChoice::System, "System"), - (ThemeChoice::Light, "Light"), - (ThemeChoice::Dark, "Dark"), - (ThemeChoice::Black, "Black"), -]; - -const FONT_SIZES: [(FontSize, &str); 3] = [ - (FontSize::Small, "Small"), - (FontSize::Medium, "Medium"), - (FontSize::Large, "Large"), -]; - impl Yumush { pub(super) fn settings_page( &self, @@ -101,7 +89,7 @@ impl Yumush { row( "Theme", segmented( - THEMES, + ThemeChoice::ALL.map(|choice| (choice, choice.label())), self.settings.theme, entity, palette, @@ -111,7 +99,7 @@ impl Yumush { row( "Font size", segmented( - FONT_SIZES, + FontSize::ALL.map(|size| (size, size.label())), self.settings.font_size, entity, palette, @@ -171,12 +159,8 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.update_user(&username).await { - Ok(user) => { - let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); - } - Err(error) => notify_error(&this, cx, error), - } + let result = network.update_user(&username).await; + apply_user(&this, cx, result); }) .detach(); } @@ -186,49 +170,25 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.update_status(&status).await { - Ok(user) => { - let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); - } - Err(error) => notify_error(&this, cx, error), - } + let result = network.update_status(&status).await; + apply_user(&this, cx, result); }) .detach(); } pub(super) fn upload_avatar(&mut self, window: &mut Window, cx: &mut Context) { - let picked = cx.prompt_for_paths(PathPromptOptions { - files: true, - directories: false, - multiple: false, - prompt: None, - }); + let picked = picked_avatar(cx, self.max_avatar_bytes()); let network = self.network.clone(); - let maximum = self.max_avatar_bytes(); cx.spawn_in(window, async move |this, cx| { - let Ok(Ok(Some(paths))) = picked.await else { - return; - }; - let Some(path) = paths.into_iter().next() else { + let Some(prepared) = picked.await else { return; }; - - let prepared = cx - .background_executor() - .spawn(async move { read_avatar_file(&path, maximum) }) - .await; let result = match prepared { Ok(bytes) => network.update_avatar(bytes).await, Err(error) => Err(error), }; - - match result { - Ok(user) => { - let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); - } - Err(error) => notify_error(&this, cx, error), - } + apply_user(&this, cx, result); }) .detach(); } @@ -237,12 +197,8 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.remove_avatar().await { - Ok(user) => { - let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); - } - Err(error) => notify_error(&this, cx, error), - } + let result = network.remove_avatar().await; + apply_user(&this, cx, result); }) .detach(); } @@ -293,6 +249,46 @@ impl Yumush { } } +fn apply_user( + this: &WeakEntity, + cx: &mut AsyncWindowContext, + result: Result, +) { + match result { + Ok(user) => { + let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); + } + Err(error) => notify_error(this, cx, error), + } +} + +pub(super) fn picked_avatar( + cx: &App, + maximum: u64, +) -> impl Future, Error>>> + 'static { + let picked = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: false, + prompt: None, + }); + let executor = cx.background_executor().clone(); + + async move { + let Ok(Ok(Some(paths))) = picked.await else { + return None; + }; + let Some(path) = paths.into_iter().next() else { + return None; + }; + Some( + executor + .spawn(async move { read_avatar_file(&path, maximum) }) + .await, + ) + } +} + pub(super) fn header( entity: &Entity, palette: Palette, @@ -577,7 +573,7 @@ pub(super) fn delete_control( .child(if confirming { "Confirm" } else { "Delete" }) } -pub(super) fn read_avatar_file(path: &Path, maximum: u64) -> Result, Error> { +fn read_avatar_file(path: &Path, maximum: u64) -> Result, Error> { let bytes = std::fs::read(path)?; crate::avatar::prepare(&bytes, maximum) diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 255f99a..57f5ac7 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -1,12 +1,12 @@ use super::text; use common::{ - model::{CommunityKind, Invitation, Role, Unread, User}, + model::{Community, CommunityKind, Invitation, Role, Unread, User}, permission, validate::validate_community_name, }; use gpui_kit::{ Anchor, AnimationExt, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, - IntoElement, MouseButton, ParentElement, StatefulInteractiveElement, Styled, Window, + IntoElement, MouseButton, ParentElement, Pixels, StatefulInteractiveElement, Styled, Window, assets::IconName, component::{ Icon, @@ -47,13 +47,15 @@ impl Yumush { palette: Palette, ) -> impl IntoElement { let collapsed = self.chat.sidebar_collapsed; - let (from, to, id) = match collapsed { - true => (SIDEBAR_WIDTH, SIDEBAR_COLLAPSED_WIDTH, "sidebar_collapsing"), - false => (SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_WIDTH, "sidebar_expanding"), + let (from, to, id) = if collapsed { + (SIDEBAR_WIDTH, SIDEBAR_COLLAPSED_WIDTH, "sidebar_collapsing") + } else { + (SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_WIDTH, "sidebar_expanding") }; - let content = match collapsed { - true => self.collapsed_sidebar(entity, palette).into_any_element(), - false => self.expanded_sidebar(entity, query, palette), + let content = if collapsed { + self.collapsed_sidebar(entity, palette).into_any_element() + } else { + self.expanded_sidebar(entity, query, palette) }; div() @@ -136,65 +138,54 @@ impl Yumush { fn voice_panel(&self, entity: &Entity, palette: Palette) -> Option { let community = self.chat.voice_room()?; - let direct = matches!(community.kind, CommunityKind::Direct { .. }); - let go_id = community.id.clone(); let tone = voice_stats::quality(&self.chat.voice_samples) .map_or(palette.ok, |quality| quality.color(palette)); let stats_entity = entity.clone(); - let panel = div() + let panel = call_style(div(), palette) .flex() .items_center() .gap(px(4.)) .p(px(6.)) .rounded(px(8.)) - .border_1() - .border_color(palette.ok.opacity(0.35)) - .bg(palette.ok.opacity(0.08)) .child( - clickable( - "voice_panel_go", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.go_to_community(go_id.clone(), direct, window, cx) - }), - ) - .tip("Go to call") - .flex_1() - .min_w_0() - .px(px(4.)) - .py(px(2.)) - .rounded(px(6.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - Icon::new(IconName::AudioLines) - .w(px(16.)) - .h(px(16.)) - .text_color(tone), - ) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child( - div() - .text_size(text(12.)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.ok) - .child("Voice connected"), - ) - .child( - div() - .truncate() - .text_size(text(11.)) - .text_color(palette.muted) - .child(community_name(community).to_string()), - ), - ), + clickable("voice_panel_go", palette, go_to_call(entity, community)) + .tip("Go to call") + .flex_1() + .min_w_0() + .px(px(4.)) + .py(px(2.)) + .rounded(px(6.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + Icon::new(IconName::AudioLines) + .w(px(16.)) + .h(px(16.)) + .text_color(tone), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(text(12.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.ok) + .child("Voice connected"), + ) + .child( + div() + .truncate() + .text_size(text(11.)) + .text_color(palette.muted) + .child(community_name(community).to_string()), + ), + ), ) .child(icon_button( "voice_panel_leave".to_string(), @@ -226,16 +217,15 @@ impl Yumush { fn voice_dot(&self, entity: &Entity, palette: Palette) -> Option { let community = self.chat.voice_room()?; - let direct = matches!(community.kind, CommunityKind::Direct { .. }); - let go_id = community.id.clone(); Some( - clickable( - "voice_panel_go_collapsed", + call_style( + clickable( + "voice_panel_go_collapsed", + palette, + go_to_call(entity, community), + ), palette, - entity_action(entity, move |yumush, window, cx| { - yumush.go_to_community(go_id.clone(), direct, window, cx) - }), ) .tip("Go to call") .size(px(28.)) @@ -243,9 +233,6 @@ impl Yumush { .items_center() .justify_center() .rounded(px(6.)) - .border_1() - .border_color(palette.ok.opacity(0.35)) - .bg(palette.ok.opacity(0.08)) .child( Icon::new(IconName::AudioLines) .w(px(14.)) @@ -275,9 +262,10 @@ impl Yumush { } fn collapse_button(&self, entity: &Entity, palette: Palette) -> AnyElement { - let (icon, tip) = match self.chat.sidebar_collapsed { - true => (IconName::PanelLeftOpen, "Expand"), - false => (IconName::PanelLeftClose, "Collapse"), + let (icon, tip) = if self.chat.sidebar_collapsed { + (IconName::PanelLeftOpen, "Expand") + } else { + (IconName::PanelLeftClose, "Collapse") }; icon_button( @@ -294,13 +282,9 @@ impl Yumush { fn tab_bar(&self, entity: &Entity, palette: Palette) -> impl IntoElement { let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32; - let direct = self.chat.unread_total(false); + let direct = self.chat.unread_direct(); let tabs = [ - ( - SidebarTab::Communities, - "Communities", - self.chat.unread_total(true), - ), + (SidebarTab::Communities, "Communities", self.chat.unread_groups()), ( SidebarTab::Messages, "Messages", @@ -330,7 +314,7 @@ impl Yumush { .gap(px(6.)) .text_size(text(12.)) .child(label) - .children(badge(palette, false, Some(&alert))); + .children(unread_badge(palette, false, Some(&alert))); match tab { SidebarTab::Communities => item @@ -390,7 +374,7 @@ impl Yumush { .h(px(20.)) .text_color(palette.accent), "Notes", - badge(palette, false, unread), + unread_badge(palette, false, unread), ), palette.accent.opacity(0.1), ) @@ -423,45 +407,56 @@ impl Yumush { .map(|community| { let active = self.chat.is_selected(&community.id); let muted = self.chat.muted.contains(&community.id); - let unread = self.chat.unread.get(&community.id); let can_leave = !active || permission::can_leave(self.actor_rank()); - let community_id = community.id.clone(); - let select = entity.clone(); - - let themed = palette.for_community(Some(community), &self.chat.hues); - hoverable_with( - format!("community_{}", community.id), - entry( - themed, - active, - community_icon( - palette, - community, - px(16.), - text(10.), - &self.chat.avatars, - ), - community.name.clone(), - badge(palette, muted, unread), - ), - themed.accent.opacity(0.1), - ) - .on_click(move |_, window, cx| { - select.update(cx, |yumush, cx| { - yumush.select_community(community_id.clone(), window, cx) - }) - }) - .context_menu(community_menu( + + self.sidebar_community_row( entity, - community.id.clone(), - can_leave, - muted, - )) - .into_any_element() + community, + palette, + px(16.), + "community", + community_menu(entity, community.id.clone(), can_leave, muted), + ) }), ) } + fn sidebar_community_row( + &self, + entity: &Entity, + community: &Community, + palette: Palette, + size: Pixels, + key: &str, + menu: impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static, + ) -> AnyElement { + let active = self.chat.is_selected(&community.id); + let muted = self.chat.muted.contains(&community.id); + let unread = self.chat.unread.get(&community.id); + let community_id = community.id.clone(); + let select = entity.clone(); + + let themed = palette.for_community(Some(community), &self.chat.hues); + hoverable_with( + format!("{key}_{}", community.id), + entry( + themed, + active, + self.community_badge(community, size, text(10.), palette), + community_name(community).to_string(), + unread_badge(palette, muted, unread), + ), + themed.accent.opacity(0.1), + ) + .on_click(move |_, window, cx| { + select.update(cx, |yumush, cx| { + yumush.select_community(community_id.clone(), window, cx) + }) + }) + .context_menu(menu) + .into_any_element() + } + fn requests(&self, entity: &Entity, palette: Palette) -> Option
{ let friends = &self.chat.friends; let rows: Vec = friends @@ -489,34 +484,21 @@ impl Yumush { self.chat .communities .iter() - .filter(|community| matches!(community.kind, CommunityKind::Direct { .. })) + .filter(|community| community.kind.is_direct()) .filter(|community| matches_query(community_name(community), query)) .map(|community| { - let active = self.chat.is_selected(&community.id); let muted = self.chat.muted.contains(&community.id); - let unread = self.chat.unread.get(&community.id); - let community_id = community.id.clone(); - let select = entity.clone(); - - let themed = palette.for_community(Some(community), &self.chat.hues); - hoverable_with( - format!("direct_{}", community.id), - entry( - themed, - active, - self.community_badge(community, px(20.), text(10.), palette), - community_name(community).to_string(), - badge(palette, muted, unread), - ), - themed.accent.opacity(0.1), + let menu_entity = entity.clone(); + let menu_id = community.id.clone(); + + self.sidebar_community_row( + entity, + community, + palette, + px(20.), + "direct", + move |menu, _, _| mute_item(menu, &menu_entity, menu_id.clone(), muted), ) - .on_click(move |_, window, cx| { - select.update(cx, |yumush, cx| { - yumush.select_community(community_id.clone(), window, cx) - }) - }) - .context_menu(direct_menu(entity, community.id.clone(), muted)) - .into_any_element() }) .collect() } @@ -535,18 +517,7 @@ impl Yumush { hoverable( format!("friend_{}", user.id), - entry( - palette, - false, - presence_avatar( - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), - self.presence_of(&user.id), - px(20.), - palette, - ), - user.username.clone(), - Vec::new(), - ), + self.user_row(palette, user, Vec::new()), palette, ) .on_click(move |_, window, cx| { @@ -587,10 +558,11 @@ impl Yumush { }), )); } - if let Some((label, icon)) = relation - .action() - .filter(|_| matches!(relation, Relation::Stranger | Relation::Incoming)) - { + let action = match relation { + Relation::Stranger | Relation::Incoming => relation.action(), + _ => None, + }; + if let Some((label, icon)) = action { let user_id = user.id.clone(); trailing.push(icon_button( format!("friend_action_{}", user.id), @@ -603,6 +575,15 @@ impl Yumush { )); } + self.user_row(palette, user, trailing).into_any_element() + } + + fn user_row( + &self, + palette: Palette, + user: &User, + trailing: impl IntoIterator, + ) -> Div { entry( palette, false, @@ -615,23 +596,15 @@ impl Yumush { user.username.clone(), trailing, ) - .into_any_element() } fn incoming_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { let accept_id = user.id.clone(); let decline_id = user.id.clone(); - entry( + self.user_row( palette, - false, - presence_avatar( - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), - self.presence_of(&user.id), - px(20.), - palette, - ), - user.username.clone(), + user, [ icon_button( format!("accept_friend_{}", user.id), @@ -659,16 +632,9 @@ impl Yumush { fn outgoing_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { let cancel_id = user.id.clone(); - entry( + self.user_row( palette, - false, - presence_avatar( - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), - self.presence_of(&user.id), - px(20.), - palette, - ), - user.username.clone(), + user, [icon_button( format!("cancel_friend_{}", user.id), palette, @@ -814,7 +780,30 @@ impl Yumush { } } -pub(super) fn badge(palette: Palette, muted: bool, unread: Option<&Unread>) -> Option { +fn go_to_call( + entity: &Entity, + community: &Community, +) -> impl Fn(&mut Window, &mut App) + 'static { + let direct = community.kind.is_direct(); + let go_id = community.id.clone(); + + entity_action(entity, move |yumush, window, cx| { + yumush.go_to_community(go_id.clone(), direct, window, cx) + }) +} + +fn call_style(element: E, palette: Palette) -> E { + element + .border_1() + .border_color(palette.ok.opacity(0.35)) + .bg(palette.ok.opacity(0.08)) +} + +pub(super) fn unread_badge( + palette: Palette, + muted: bool, + unread: Option<&Unread>, +) -> Option { if muted { return Some( div() @@ -866,16 +855,6 @@ fn mute_item( })) } -fn direct_menu( - entity: &Entity, - community_id: String, - muted: bool, -) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { - let entity = entity.clone(); - - move |menu, _, _| mute_item(menu, &entity, community_id.clone(), muted) -} - fn community_menu( entity: &Entity, community_id: String, diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index 5f76371..b30bdf2 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -15,7 +15,8 @@ use gpui_kit::{ use rtrb::{Consumer, RingBuffer}; use super::{ - Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, media_view::time_text, + Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, + media_view::{time_text, upload_file}, notify_error, primary_button, text, }; use crate::{ @@ -47,6 +48,12 @@ pub enum VoiceNote { }, } +fn drain(consumer: &mut Consumer, samples: &mut Vec) { + while let Ok(sample) = consumer.pop() { + samples.push(sample); + } +} + pub fn bars( levels: &[f32], progress: f32, @@ -214,9 +221,7 @@ impl Yumush { } = &mut self.chat.media.voice_note { let start = samples.len(); - while let Ok(sample) = consumer.pop() { - samples.push(sample); - } + drain(consumer, samples); levels.push(voice_note::level(&samples[start..])); if levels.len() > BARS { levels.remove(0); @@ -239,9 +244,7 @@ impl Yumush { else { return; }; - while let Ok(sample) = consumer.pop() { - samples.push(sample); - } + drain(&mut consumer, &mut samples); let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; @@ -260,18 +263,9 @@ impl Yumush { else { return; }; - let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.uploading += 1; - cx.notify(); - }); - let uploaded = network - .upload_attachment(&community_id, path, maximum) - .await; - let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.uploading -= 1; - cx.notify(); - }); - let attachment = match uploaded { + let attachment = match upload_file(&this, &network, &community_id, path, maximum, cx) + .await + { Ok(attachment) => attachment, Err(error) => return notify_error(&this, cx, error), }; diff --git a/crates/client/src/gui/voice_settings.rs b/crates/client/src/gui/voice_settings.rs index 1cd5051..f3b0243 100644 --- a/crates/client/src/gui/voice_settings.rs +++ b/crates/client/src/gui/voice_settings.rs @@ -37,13 +37,6 @@ pub(super) enum Side { Output, } -#[derive(Clone, Copy)] -pub(super) enum VoiceField { - Sensitivity, - InputVolume, - OutputVolume, -} - #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum MicTest { Off, @@ -121,13 +114,13 @@ impl VoiceControls { } }), cx.subscribe(&sensitivity, |this, _, event: &SliderEvent, cx| { - this.slider_changed(VoiceField::Sensitivity, event, cx); + this.slider_changed(event, |voice, value| voice.sensitivity_db = value, cx); }), cx.subscribe(&input_volume, |this, _, event: &SliderEvent, cx| { - this.slider_changed(VoiceField::InputVolume, event, cx); + this.slider_changed(event, |voice, value| voice.input_volume = value, cx); }), cx.subscribe(&output_volume, |this, _, event: &SliderEvent, cx| { - this.slider_changed(VoiceField::OutputVolume, event, cx); + this.slider_changed(event, |voice, value| voice.output_volume = value, cx); }), ]; @@ -348,18 +341,16 @@ impl Yumush { .child(content) } - fn slider_changed(&mut self, field: VoiceField, event: &SliderEvent, cx: &mut Context) { + fn slider_changed( + &mut self, + event: &SliderEvent, + set: fn(&mut VoiceSettings, f32), + cx: &mut Context, + ) { let SliderEvent::Change(value) = event else { return; }; - let value = value.start(); - let voice = &mut self.settings.voice; - - match field { - VoiceField::Sensitivity => voice.sensitivity_db = value, - VoiceField::InputVolume => voice.input_volume = value, - VoiceField::OutputVolume => voice.output_volume = value, - } + set(&mut self.settings.voice, value.start()); self.commit_settings(cx); } @@ -398,18 +389,25 @@ impl Yumush { && self.settings.voice.push_to_talk_key == key } + fn finish_capture(&mut self, key: String, cx: &mut Context) { + self.voice.key = KeyCapture::Idle; + self.settings.voice.push_to_talk_key = key; + self.commit_settings(cx); + cx.notify(); + } + pub(super) fn voice_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context) { let key = event.keystroke.key.clone(); match self.voice.key { KeyCapture::Waiting => { cx.stop_propagation(); - self.voice.key = KeyCapture::Idle; - if key != "escape" { - self.settings.voice.push_to_talk_key = key; - self.commit_settings(cx); + if key == "escape" { + self.voice.key = KeyCapture::Idle; + cx.notify(); + } else { + self.finish_capture(key, cx); } - cx.notify(); } KeyCapture::Idle => { if self.is_push_key(&key) { @@ -443,10 +441,7 @@ impl Yumush { let Some((key, _)) = held.iter().find(|(_, down)| *down) else { return; }; - self.voice.key = KeyCapture::Idle; - self.settings.voice.push_to_talk_key = key.to_string(); - self.commit_settings(cx); - cx.notify(); + self.finish_capture(key.to_string(), cx); } KeyCapture::Idle => { if let Some((_, down)) = held.iter().find(|(key, _)| self.is_push_key(key)) { diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index b61f084..f703b25 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use common::config::Config; pub mod accounts; @@ -13,6 +15,10 @@ pub mod voice; pub const NAME: &str = "Yumush"; +pub fn config_file(name: &str) -> Option { + dirs::config_dir().map(|dir| dir.join("yumush").join(name)) +} + const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/../../configs/client_config.toml" diff --git a/crates/client/src/media/mod.rs b/crates/client/src/media/mod.rs index fa97a10..59c5e29 100644 --- a/crates/client/src/media/mod.rs +++ b/crates/client/src/media/mod.rs @@ -116,13 +116,18 @@ impl Info { } } -pub fn probe(path: &Path) -> Result { +fn open_tracks(path: &Path) -> Result<(Reader, Tracks, Info), MediaError> { let reader = Reader::open(path)?; let tracks = Tracks::find(&reader); if tracks.video.is_none() && tracks.audio.is_none() { return Err(MediaError::Unsupported); } - Ok(Info::of(path, &reader, &tracks)) + let info = Info::of(path, &reader, &tracks); + Ok((reader, tracks, info)) +} + +pub fn probe(path: &Path) -> Result { + open_tracks(path).map(|(_, _, info)| info) } const FLAC_TAIL: u64 = 256 * 1024; @@ -167,12 +172,7 @@ pub struct Player { impl Player { pub fn open(path: &Path, choice: Choice) -> Result { - let reader = Reader::open(path)?; - let tracks = Tracks::find(&reader); - if tracks.video.is_none() && tracks.audio.is_none() { - return Err(MediaError::Unsupported); - } - let info = Info::of(path, &reader, &tracks); + let (reader, tracks, info) = open_tracks(path)?; let (producer, consumer) = RingBuffer::new(RING_SAMPLES); let playback: Playback = Arc::new(Mutex::new(consumer)); let audio = if tracks.audio.is_some() { diff --git a/crates/client/src/media/voice_note.rs b/crates/client/src/media/voice_note.rs index 14b514e..c5e238e 100644 --- a/crates/client/src/media/voice_note.rs +++ b/crates/client/src/media/voice_note.rs @@ -103,9 +103,13 @@ pub fn encode(samples: &[f32]) -> Option> { Some(muxer.into_inner()) } +pub fn media_cache_dir() -> Option { + Some(dirs::cache_dir()?.join("yumush").join("media")) +} + pub fn save(samples: &[f32]) -> Option { let bytes = encode(samples)?; - let directory = dirs::cache_dir()?.join("yumush").join("media"); + let directory = media_cache_dir()?; std::fs::create_dir_all(&directory).ok()?; let path = directory.join(format!("voice-{}.ogg", now_ms())); std::fs::write(&path, bytes).ok()?; diff --git a/crates/client/src/mutes.rs b/crates/client/src/mutes.rs index efd5934..aa54ca0 100644 --- a/crates/client/src/mutes.rs +++ b/crates/client/src/mutes.rs @@ -1,21 +1,16 @@ -use std::{ - collections::HashSet, - fs, - path::{Path, PathBuf}, -}; +use std::{collections::HashSet, fs, path::Path}; use tracing::warn; -fn path() -> Option { - dirs::config_dir().map(|dir| dir.join("yumush").join("mutes")) -} +use crate::config_file; fn prefix(account_user_id: &str) -> String { format!("{account_user_id}\t") } pub fn load(account_user_id: &str) -> HashSet { - let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else { + let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) + else { return HashSet::new(); }; let prefix = prefix(account_user_id); @@ -28,7 +23,7 @@ pub fn load(account_user_id: &str) -> HashSet { } pub fn save(account_user_id: &str, muted: &HashSet) { - let Some(path) = path() else { + let Some(path) = config_file("mutes") else { return; }; let prefix = prefix(account_user_id); diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index 8988274..6ea606c 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -12,14 +12,14 @@ use common::{ error::Error, event::Event, model::{ - Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community, + Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, network::{ DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded, - receive_download_status, receive_event, send_download_request, send_encoded, send_request, + receive_download_status, receive_event, send_encoded, send_request, send_stream_kind, send_upload_header, }, request::{DownloadRequest, Request, UploadHeader}, @@ -112,15 +112,29 @@ pub struct NetworkHandle { } impl NetworkHandle { - pub async fn request(&self, request: Request) -> Result { + async fn ask( + &self, + build: impl FnOnce(oneshot::Sender>) -> Command, + ) -> Result { let (reply, response) = oneshot::channel(); self.command_sender - .send(Command::Request { request, reply }) + .send(build(reply)) .await .map_err(|_| Error::ChannelClosed)?; - match response.await.map_err(|_| Error::ChannelClosed)?? { + response.await.map_err(|_| Error::ChannelClosed)? + } + + fn with_voice(&self, f: impl FnOnce(&Voice) -> T) -> Option { + self.voice.lock().unwrap().as_ref().map(f) + } + + async fn request(&self, request: Request) -> Result { + match self + .ask(|reply| Command::Request { request, reply }) + .await? + { Response::Error(error) => Err(error), response => Ok(response), } @@ -131,18 +145,11 @@ impl NetworkHandle { Response::Session { user, token } => (user, token), _ => return Err(Error::Server), }; - let _ = self.set_device(&device_name()).await; + let _ = self.done(Request::SetDevice { name: device_name() }).await; Ok(session) } - async fn set_device(&self, name: &str) -> Result<(), Error> { - self.done(Request::SetDevice { - name: name.to_string(), - }) - .await - } - pub async fn sessions(&self, user_id: &str) -> Result, Error> { match self .request(Request::Sessions { @@ -186,10 +193,7 @@ impl NetworkHandle { } pub async fn detach(&self) -> Result<(), Error> { - match self.request(Request::Detach).await? { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::Detach).await } pub async fn register( @@ -221,10 +225,7 @@ impl NetworkHandle { } pub async fn logout(&self) -> Result<(), Error> { - match self.request(Request::Logout).await? { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::Logout).await } pub async fn update_user(&self, username: &str) -> Result { @@ -280,14 +281,14 @@ impl NetworkHandle { &self, user_id: &str, reason: Option<&str>, - ip: bool, + scope: BanScope, ) -> Result<(), Error> { validate_reason(reason)?; self.done(Request::BanUser { user_id: user_id.to_string(), reason: reason.map(str::to_string), - ip, + scope, }) .await } @@ -520,15 +521,10 @@ impl NetworkHandle { } pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { - match self - .request(Request::LeaveCommunity { - community_id: community_id.to_string(), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::LeaveCommunity { + community_id: community_id.to_string(), + }) + .await } pub async fn communities(&self) -> Result, Error> { @@ -557,17 +553,12 @@ impl NetworkHandle { reason: Option<&str>, ) -> Result<(), Error> { validate_reason(reason)?; - match self - .request(Request::Kick { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::Kick { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + reason: reason.map(str::to_string), + }) + .await } pub async fn ban( @@ -577,30 +568,20 @@ impl NetworkHandle { reason: Option<&str>, ) -> Result<(), Error> { validate_reason(reason)?; - match self - .request(Request::Ban { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - reason: reason.map(str::to_string), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::Ban { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + reason: reason.map(str::to_string), + }) + .await } pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Error> { - match self - .request(Request::Unban { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::Unban { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + }) + .await } pub async fn bans(&self, community_id: &str) -> Result, Error> { @@ -633,17 +614,12 @@ impl NetworkHandle { user_id: &str, rank: Rank, ) -> Result<(), Error> { - match self - .request(Request::SetRank { - community_id: community_id.to_string(), - user_id: user_id.to_string(), - rank, - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::SetRank { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + rank, + }) + .await } pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> { @@ -1040,19 +1016,13 @@ impl NetworkHandle { path: PathBuf, maximum: Option, ) -> Result { - let (reply, response) = oneshot::channel(); - - self.command_sender - .send(Command::Upload { - community_id: community_id.to_string(), - path, - maximum, - reply, - }) - .await - .map_err(|_| Error::ChannelClosed)?; - - response.await.map_err(|_| Error::ChannelClosed)? + self.ask(|reply| Command::Upload { + community_id: community_id.to_string(), + path, + maximum, + reply, + }) + .await } pub async fn download_attachment( @@ -1060,33 +1030,21 @@ impl NetworkHandle { attachment_id: &str, thumbnail: bool, ) -> Result, Error> { - let (reply, response) = oneshot::channel(); - - self.command_sender - .send(Command::Download { - attachment_id: attachment_id.to_string(), - thumbnail, - reply, - }) - .await - .map_err(|_| Error::ChannelClosed)?; - - response.await.map_err(|_| Error::ChannelClosed)? + self.ask(|reply| Command::Download { + attachment_id: attachment_id.to_string(), + thumbnail, + reply, + }) + .await } pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> { - let (reply, response) = oneshot::channel(); - - self.command_sender - .send(Command::BackupDownload { - name: name.to_string(), - path, - reply, - }) - .await - .map_err(|_| Error::ChannelClosed)?; - - response.await.map_err(|_| Error::ChannelClosed)? + self.ask(|reply| Command::BackupDownload { + name: name.to_string(), + path, + reply, + }) + .await } pub async fn read_messages( @@ -1114,16 +1072,11 @@ impl NetworkHandle { } pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> { - match self - .request(Request::MarkRead { - community_id: community_id.to_string(), - message_id: message_id.to_string(), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::MarkRead { + community_id: community_id.to_string(), + message_id: message_id.to_string(), + }) + .await } pub async fn update_status(&self, status: &str) -> Result { @@ -1202,22 +1155,14 @@ impl NetworkHandle { } pub async fn typing(&self, community_id: &str) -> Result<(), Error> { - match self - .request(Request::Typing { - community_id: community_id.to_string(), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::Typing { + community_id: community_id.to_string(), + }) + .await } pub async fn leave_voice(&self) -> Result<(), Error> { - match self.request(Request::LeaveVoice).await? { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::LeaveVoice).await } pub async fn read_community(&self, community_id: &str) -> Result { @@ -1252,35 +1197,22 @@ impl NetworkHandle { } pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> { - match self.request(Request::SetGhost { enabled }).await? { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::SetGhost { enabled }).await } pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Error> { - match self - .request(Request::KickFromVoice { - user_id: user_id.to_string(), - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::KickFromVoice { + user_id: user_id.to_string(), + }) + .await } pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Error> { - match self - .request(Request::ServerMute { - user_id: user_id.to_string(), - muted, - }) - .await? - { - Response::Done => Ok(()), - _ => Err(Error::Server), - } + self.done(Request::ServerMute { + user_id: user_id.to_string(), + muted, + }) + .await } pub async fn set_community_voice( @@ -1336,39 +1268,28 @@ impl NetworkHandle { } pub fn voice_level_db(&self) -> Option { - let live = self.voice.lock().unwrap().as_ref().map(Voice::level_db); - live.or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db)) + self.with_voice(Voice::level_db) + .or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db)) } pub fn voice_sample(&self) -> Option { - self.voice.lock().unwrap().as_ref().map(Voice::sample) + self.with_voice(Voice::sample) } pub fn set_talking(&self, talking: bool) { - if let Some(voice) = self.voice.lock().unwrap().as_ref() { - voice.set_talking(talking); - } + self.with_voice(|voice| voice.set_talking(talking)); } pub fn set_muted(&self, muted: bool) { - if let Some(voice) = self.voice.lock().unwrap().as_ref() { - voice.set_muted(muted); - } + self.with_voice(|voice| voice.set_muted(muted)); } pub fn set_deafened(&self, deafened: bool) { - if let Some(voice) = self.voice.lock().unwrap().as_ref() { - voice.set_deafened(deafened); - } + self.with_voice(|voice| voice.set_deafened(deafened)); } pub fn speaking(&self) -> Vec { - self.voice - .lock() - .unwrap() - .as_ref() - .map(Voice::speaking) - .unwrap_or_default() + self.with_voice(Voice::speaking).unwrap_or_default() } } @@ -1629,7 +1550,7 @@ async fn download( attachment_id: attachment_id.to_string(), thumbnail, }; - send_download_request(&request, &mut send_stream).await?; + send_encoded(&request, &mut send_stream).await?; send_stream.finish()?; match receive_download_status(&mut receive_stream).await? { diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index ada0311..dbaf3a1 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -1,6 +1,6 @@ -use std::{fmt::Display, fs, ops::RangeInclusive, path::PathBuf}; +use std::{fmt::Display, fs, ops::RangeInclusive}; -use common::config::Config; +use common::{config::Config, string_enum}; use gpui_kit::{ App, Global, Pixels, component::{Theme, ThemeMode}, @@ -8,28 +8,32 @@ use gpui_kit::{ }; use tracing::warn; -use crate::voice::audio::Choice; +use crate::{config_file, voice::audio::Choice}; pub const SENSITIVITY_DB: RangeInclusive = -80.0..=0.0; pub const VOLUME: RangeInclusive = 0.0..=200.0; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ThemeChoice { - System, - Light, - Dark, - Black, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + ThemeChoice { + System => "system", + Light => "light", + Dark => "dark", + Black => "black", + } } pub struct Look(pub ThemeChoice); impl Global for Look {} -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FontSize { - Small, - Medium, - Large, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + FontSize { + Small => "small", + Medium => "medium", + Large => "large", + } } pub struct Scale(pub FontSize); @@ -37,20 +41,14 @@ pub struct Scale(pub FontSize); impl Global for Scale {} impl FontSize { - const ALL: [Self; 3] = [FontSize::Small, FontSize::Medium, FontSize::Large]; - - fn name(self) -> &'static str { + pub fn label(self) -> &'static str { match self { - FontSize::Small => "small", - FontSize::Medium => "medium", - FontSize::Large => "large", + FontSize::Small => "Small", + FontSize::Medium => "Medium", + FontSize::Large => "Large", } } - fn parse(value: &str) -> Option { - Self::ALL.into_iter().find(|size| size.name() == value) - } - pub fn pixels(self) -> Pixels { match self { FontSize::Small => px(13.), @@ -61,37 +59,30 @@ impl FontSize { } impl ThemeChoice { - const ALL: [Self; 4] = [ - ThemeChoice::System, - ThemeChoice::Light, - ThemeChoice::Dark, - ThemeChoice::Black, - ]; - - fn name(self) -> &'static str { + pub fn label(self) -> &'static str { match self { - ThemeChoice::System => "system", - ThemeChoice::Light => "light", - ThemeChoice::Dark => "dark", - ThemeChoice::Black => "black", + ThemeChoice::System => "System", + ThemeChoice::Light => "Light", + ThemeChoice::Dark => "Dark", + ThemeChoice::Black => "Black", } } - - fn parse(value: &str) -> Option { - Self::ALL.into_iter().find(|choice| choice.name() == value) - } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Activation { - VoiceActivity, - PushToTalk, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + Activation { + VoiceActivity => "voice_activity", + PushToTalk => "push_to_talk", + } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Profile { - Voice, - Music, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + Profile { + Voice => "voice", + Music => "music", + } } #[derive(Debug, Clone, PartialEq)] @@ -127,12 +118,8 @@ pub struct Settings { pub close_to_tray: bool, } -fn path() -> Option { - dirs::config_dir().map(|dir| dir.join("yumush").join("settings")) -} - pub fn load() -> Settings { - let config = path() + let config = config_file("settings") .and_then(|path| fs::read_to_string(path).ok()) .and_then(|content| Config::parse(&content).ok()); let text = |key: &str| { @@ -161,14 +148,12 @@ pub fn load() -> Settings { input: text("voice.input"), output: text("voice.output"), }, - activation: match text("voice.activation").as_deref() { - Some("push_to_talk") => Activation::PushToTalk, - _ => Activation::VoiceActivity, - }, - profile: match text("voice.profile").as_deref() { - Some("music") => Profile::Music, - _ => Profile::Voice, - }, + activation: text("voice.activation") + .and_then(|value| Activation::parse(&value)) + .unwrap_or(Activation::VoiceActivity), + profile: text("voice.profile") + .and_then(|value| Profile::parse(&value)) + .unwrap_or(Profile::Voice), push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), }; @@ -189,23 +174,15 @@ fn line(key: &str, value: impl Display) -> String { } pub fn save(settings: &Settings) { - let Some(path) = path() else { + let Some(path) = config_file("settings") else { return; }; let voice = &settings.voice; - let activation = match voice.activation { - Activation::VoiceActivity => "voice_activity", - Activation::PushToTalk => "push_to_talk", - }; - let profile = match voice.profile { - Profile::Voice => "voice", - Profile::Music => "music", - }; let key = voice.push_to_talk_key.as_str(); let content = [ - line("theme", settings.theme.name()), - line("font_size", settings.font_size.name()), + line("theme", settings.theme.as_str()), + line("font_size", settings.font_size.as_str()), line("close_to_tray", settings.close_to_tray), line("voice.sensitivity", voice.sensitivity_db), line("voice.input_volume", voice.input_volume), @@ -218,8 +195,8 @@ pub fn save(settings: &Settings) { "voice.output", voice.choice.output.as_deref().unwrap_or_default(), ), - line("voice.activation", activation), - line("voice.profile", profile), + line("voice.activation", voice.activation.as_str()), + line("voice.profile", voice.profile.as_str()), line("voice.push_to_talk", key), ] .concat(); diff --git a/crates/client/src/tray.rs b/crates/client/src/tray.rs index 497cae6..33d8e52 100644 --- a/crates/client/src/tray.rs +++ b/crates/client/src/tray.rs @@ -136,19 +136,24 @@ impl ksni::Tray for Tray { fn menu(&self) -> Vec> { use ksni::menu::StandardItem; - [("Show", TrayAction::Show), ("Quit", TrayAction::Quit)] - .into_iter() - .map(|(label, action)| { - StandardItem { - label: label.to_string(), - activate: Box::new(move |tray: &mut Self| { - let _ = tray.sender.send(action); - }), - ..Default::default() - } - .into() - }) - .collect() + vec![ + StandardItem { + label: "Show".to_string(), + activate: Box::new(|tray: &mut Self| { + let _ = tray.sender.send(TrayAction::Show); + }), + ..Default::default() + } + .into(), + StandardItem { + label: "Quit".to_string(), + activate: Box::new(|tray: &mut Self| { + let _ = tray.sender.send(TrayAction::Quit); + }), + ..Default::default() + } + .into(), + ] } } diff --git a/crates/client/src/voice/audio.rs b/crates/client/src/voice/audio.rs index c3899df..f9cd2de 100644 --- a/crates/client/src/voice/audio.rs +++ b/crates/client/src/voice/audio.rs @@ -54,13 +54,27 @@ pub enum Audio { Device(backend::Backend), } -pub fn start(capture: Option, playback: Playback, choice: Choice) -> Audio { +enum Mode { + Off, + Tone, + Device, +} + +fn mode() -> Mode { match std::env::var("YUMUSH_AUDIO").as_deref() { - Ok("off") => Audio::Silent, - Ok("tone") => Audio::Tone(Worker::spawn("voice-tone", move |stop| { + Ok("off") => Mode::Off, + Ok("tone") => Mode::Tone, + _ => Mode::Device, + } +} + +pub fn start(capture: Option, playback: Playback, choice: Choice) -> Audio { + match mode() { + Mode::Off => Audio::Silent, + Mode::Tone => Audio::Tone(Worker::spawn("voice-tone", move |stop| { tone(capture.as_ref(), &playback, stop) })), - _ => device(capture, playback, choice), + Mode::Device => device(capture, playback, choice), } } @@ -76,9 +90,9 @@ fn device(_: Option, _: Playback, _: Choice) -> Audio { #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] pub fn devices() -> Devices { - match std::env::var("YUMUSH_AUDIO").as_deref() { - Ok("off" | "tone") => Devices::default(), - _ => backend::devices(), + match mode() { + Mode::Off | Mode::Tone => Devices::default(), + Mode::Device => backend::devices(), } } diff --git a/crates/client/src/voice/audio/pipewire.rs b/crates/client/src/voice/audio/pipewire.rs index 89c2986..e7b5e6e 100644 --- a/crates/client/src/voice/audio/pipewire.rs +++ b/crates/client/src/voice/audio/pipewire.rs @@ -250,9 +250,10 @@ fn run( return; }; let chunks = bytes.as_chunks_mut::().0; - let frames = match requested { - 0 => chunks.len(), - requested => requested.min(chunks.len()), + let frames = if requested == 0 { + chunks.len() + } else { + requested.min(chunks.len()) }; play(&playback, frames, |index, sample| { chunks[index] = stereo_bytes(sample); diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index d751d44..bc9ac7d 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -11,7 +11,7 @@ use common::{ }; use ec_opus::{Application, Bandwidth, Decoder, Encoder}; -use crate::settings::Profile; +use crate::settings::{Activation, Profile}; pub const SILENT_DB: f32 = -100.0; const JITTER_CAPACITY: usize = 10; @@ -45,13 +45,20 @@ fn db(amplitude: f32) -> f32 { (20.0 * amplitude.log10()).max(SILENT_DB) } +fn bitrate(profile: Profile) -> u32 { + match profile { + Profile::Voice => VOICE_BITRATE as u32, + Profile::Music => MUSIC_BITRATE as u32, + } +} + fn encoder(profile: Profile) -> Encoder { - let (application, bitrate) = match profile { - Profile::Voice => (Application::Voip, VOICE_BITRATE), - Profile::Music => (Application::Audio, MUSIC_BITRATE), + let application = match profile { + Profile::Voice => Application::Voip, + Profile::Music => Application::Audio, }; let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder"); - encoder.set_bitrate(bitrate as u32); + encoder.set_bitrate(bitrate(profile)); encoder.set_bandwidth(Some(Bandwidth::Full)); encoder.set_analysis(true); encoder.set_inband_fec(true); @@ -166,7 +173,7 @@ pub struct Engine { gate: f32, input_gain: f32, output_gain: f32, - push_to_talk: bool, + activation: Activation, talking: bool, hangover: u32, sending: bool, @@ -197,7 +204,7 @@ impl Engine { gate: 0.0, input_gain: 1.0, output_gain: 1.0, - push_to_talk: false, + activation: Activation::VoiceActivity, talking: false, hangover: 0, sending: false, @@ -227,10 +234,9 @@ impl Engine { if loud >= self.gate { self.hangover = HANGOVER_FRAMES; } - let talking = if self.push_to_talk { - self.talking - } else { - self.hangover > 0 + let talking = match self.activation { + Activation::PushToTalk => self.talking, + Activation::VoiceActivity => self.hangover > 0, }; self.hangover = self.hangover.saturating_sub(1); let speaking = talking && !self.muted && !self.deafened; @@ -276,18 +282,13 @@ impl Engine { let now = Instant::now(); self.received_bytes += datagram.len(); - let stale = self + let speaker = self .speakers - .get(&user_id) - .is_none_or(|speaker| now.duration_since(speaker.last_heard) > RESTART_AFTER); - if stale { - self.speakers - .insert(user_id.clone(), Speaker::new(sequence, now)); + .entry(user_id) + .or_insert_with(|| Speaker::new(sequence, now)); + if now.duration_since(speaker.last_heard) > RESTART_AFTER { + *speaker = Speaker::new(sequence, now); } - - let Some(speaker) = self.speakers.get_mut(&user_id) else { - return; - }; speaker.last_heard = now; if payload.is_empty() || sequence < speaker.next { return; @@ -379,14 +380,7 @@ impl Engine { } pub fn bitrate_kbps(&self) -> u32 { - match self.profile { - Profile::Voice => VOICE_BITRATE as u32 / 1000, - Profile::Music => MUSIC_BITRATE as u32 / 1000, - } - } - - pub fn forget(&mut self, user_id: &str) { - self.speakers.remove(user_id); + bitrate(self.profile) / 1000 } pub fn set_muted(&mut self, muted: bool) { @@ -402,13 +396,13 @@ impl Engine { sensitivity_db: f32, input_volume: f32, output_volume: f32, - push_to_talk: bool, + activation: Activation, profile: Profile, ) { self.gate = 10f32.powf(sensitivity_db / 20.0); self.input_gain = input_volume / 100.0; self.output_gain = output_volume / 100.0; - self.push_to_talk = push_to_talk; + self.activation = activation; if profile != self.profile { self.encoder = encoder(profile); self.profile = profile; @@ -422,10 +416,6 @@ impl Engine { pub fn level_db(&self) -> f32 { self.level_db } - - pub fn output_gain(&self) -> f32 { - self.output_gain - } } #[cfg(test)] diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index 443c09e..cd13c15 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -19,7 +19,7 @@ use tracing::warn; pub mod audio; pub mod engine; -use crate::settings::{Activation, VoiceSettings}; +use crate::settings::VoiceSettings; use audio::{Audio, Choice}; use engine::{Engine, SILENT_DB, Traffic}; @@ -127,8 +127,6 @@ fn plops(plops: &[Plop], seconds: f32) -> Vec { reverb(dry, rate) } -const YUMUSH_SECONDS: f32 = 0.9; -const RING_SECONDS: f32 = 1.3; const DETUNE: [f32; 2] = [0.998, 1.002]; const PITCH_SETTLE: f32 = 0.04; const ATTACK: f32 = 0.004; @@ -145,52 +143,28 @@ struct Plop { gain: f32, } -const YUMUSH: [Plop; 2] = [ - Plop { - start: 0.0, - from: 620.0, - rise: 0.6, - decay: 0.07, - gain: 1.0, - }, +const fn plop(start: f32, from: f32, rise: f32, decay: f32, gain: f32) -> Plop { Plop { - start: 0.13, - from: 400.0, - rise: 0.45, - decay: 0.14, - gain: 0.9, - }, + start, + from, + rise, + decay, + gain, + } +} + +const YUMUSH_SECONDS: f32 = 0.9; +const YUMUSH: [Plop; 2] = [ + plop(0.0, 620.0, 0.6, 0.07, 1.0), + plop(0.13, 400.0, 0.45, 0.14, 0.9), ]; +const RING_SECONDS: f32 = 1.3; const RING: [Plop; 4] = [ - Plop { - start: 0.0, - from: 400.0, - rise: 0.45, - decay: 0.1, - gain: 0.9, - }, - Plop { - start: 0.14, - from: 500.0, - rise: 0.45, - decay: 0.1, - gain: 0.9, - }, - Plop { - start: 0.28, - from: 620.0, - rise: 0.6, - decay: 0.12, - gain: 1.0, - }, - Plop { - start: 0.5, - from: 620.0, - rise: 0.6, - decay: 0.2, - gain: 0.8, - }, + plop(0.0, 400.0, 0.45, 0.1, 0.9), + plop(0.14, 500.0, 0.45, 0.1, 0.9), + plop(0.28, 620.0, 0.6, 0.12, 1.0), + plop(0.5, 620.0, 0.6, 0.2, 0.8), ]; impl Plop { @@ -302,34 +276,33 @@ impl Voice { self.choice = settings.choice.clone(); } - if let Ok(mut engine) = self.engine.lock() { + self.with_engine((), |engine| { engine.configure( settings.sensitivity_db, settings.input_volume, settings.output_volume, - settings.activation == Activation::PushToTalk, + settings.activation, settings.profile, - ); - } + ) + }); + } + + fn with_engine(&self, default: T, f: impl FnOnce(&mut Engine) -> T) -> T { + self.engine + .lock() + .map_or(default, |mut engine| f(&mut engine)) } pub fn receive(&self, datagram: &[u8]) { - if let Ok(mut engine) = self.engine.lock() { - engine.receive(datagram); - } + self.with_engine((), |engine| engine.receive(datagram)); } pub fn speaking(&self) -> Vec { - self.engine - .lock() - .map(|engine| engine.speaking()) - .unwrap_or_default() + self.with_engine(Vec::new(), |engine| engine.speaking()) } pub fn level_db(&self) -> f32 { - self.engine - .lock() - .map_or(SILENT_DB, |engine| engine.level_db()) + self.with_engine(SILENT_DB, |engine| engine.level_db()) } pub fn sample(&self) -> VoiceSample { @@ -337,33 +310,23 @@ impl Voice { .connection .as_ref() .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0); - let Ok(mut engine) = self.engine.lock() else { - return VoiceSample::default(); - }; - - VoiceSample { + self.with_engine(VoiceSample::default(), |engine| VoiceSample { ping_ms, traffic: engine.take_traffic(), bitrate_kbps: engine.bitrate_kbps(), - } + }) } pub fn set_muted(&self, muted: bool) { - if let Ok(mut engine) = self.engine.lock() { - engine.set_muted(muted); - } + self.with_engine((), |engine| engine.set_muted(muted)); } pub fn set_deafened(&self, deafened: bool) { - if let Ok(mut engine) = self.engine.lock() { - engine.set_deafened(deafened); - } + self.with_engine((), |engine| engine.set_deafened(deafened)); } pub fn set_talking(&self, talking: bool) { - if let Ok(mut engine) = self.engine.lock() { - engine.set_talking(talking); - } + self.with_engine((), |engine| engine.set_talking(talking)); } } diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs index 8276a1a..440a768 100644 --- a/crates/common/src/event.rs +++ b/crates/common/src/event.rs @@ -1,6 +1,8 @@ use bitcode::{Decode, Encode}; -use crate::model::{Community, Friends, Invitation, Member, Message, Presence, Rank, User}; +use crate::model::{ + Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, User, +}; #[derive(Debug, Clone, Encode, Decode)] pub enum Event { @@ -25,7 +27,7 @@ pub enum Event { Removed { community_id: String, community_name: String, - banned: bool, + sanction: Sanction, reason: Option, }, FriendsUpdated(Friends), diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index edba8d3..0dffe55 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -5,52 +5,57 @@ use crate::constant::{ MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH, }; -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] -pub enum Role { - User, - Builder, -} +#[macro_export] +macro_rules! string_enum { + ($(#[$meta:meta])* $name:ident { $($variant:ident => $text:literal),+ $(,)? }) => { + $(#[$meta])* + pub enum $name { + $($variant),+ + } -impl Role { - pub const ALL: [Self; 2] = [Role::User, Role::Builder]; + impl $name { + pub const ALL: [Self; [$(stringify!($variant)),+].len()] = [$(Self::$variant),+]; - pub fn as_str(self) -> &'static str { - match self { - Role::User => "user", - Role::Builder => "builder", + pub const fn as_str(self) -> &'static str { + match self { + $(Self::$variant => $text),+ + } + } + + pub fn parse(text: &str) -> Option { + Self::ALL.into_iter().find(|item| item.as_str() == text) + } } + }; +} + +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] + Role { + User => "user", + Builder => "builder", } +} +impl Role { pub fn label(self) -> &'static str { match self { Role::User => "User", Role::Builder => "Builder", } } - - pub fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|role| role.as_str() == text) - } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] -pub enum Presence { - Online, - Busy, - Offline, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] + Presence { + Online => "online", + Busy => "busy", + Offline => "offline", + } } impl Presence { - pub const ALL: [Self; 3] = [Presence::Online, Presence::Busy, Presence::Offline]; - - pub fn as_str(self) -> &'static str { - match self { - Presence::Online => "online", - Presence::Busy => "busy", - Presence::Offline => "offline", - } - } - pub fn label(self) -> &'static str { match self { Presence::Online => "Online", @@ -58,42 +63,20 @@ impl Presence { Presence::Offline => "Offline", } } - - pub fn parse(text: &str) -> Option { - Self::ALL - .into_iter() - .find(|presence| presence.as_str() == text) - } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] -pub enum Rank { - Member, - Moderator, - Admin, - Owner, - Builder, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] + Rank { + Member => "member", + Moderator => "moderator", + Admin => "admin", + Owner => "owner", + Builder => "builder", + } } impl Rank { - pub const ALL: [Self; 5] = [ - Rank::Member, - Rank::Moderator, - Rank::Admin, - Rank::Owner, - Rank::Builder, - ]; - - pub fn as_str(self) -> &'static str { - match self { - Rank::Member => "member", - Rank::Moderator => "moderator", - Rank::Admin => "admin", - Rank::Owner => "owner", - Rank::Builder => "builder", - } - } - pub fn label(self) -> &'static str { match self { Rank::Member => "Member", @@ -103,10 +86,6 @@ impl Rank { Rank::Builder => "Builder", } } - - pub fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|rank| rank.as_str() == text) - } } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -147,6 +126,24 @@ pub enum CommunityKind { Notes, } +impl CommunityKind { + pub fn is_direct(&self) -> bool { + matches!(self, Self::Direct { .. }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum Sanction { + Kick, + Ban, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum BanScope { + Account, + AccountAndIp, +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Community { pub id: String, @@ -250,114 +247,40 @@ pub enum AdminAction { BackupDownloaded { name: String }, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AdminActionKind { - RoleChanged, - UserDeleted, - UserSuspended, - UserUnsuspended, - SessionsRevoked, - PasswordReset, - ProfileCleared, - UserCreated, - CommunityDeleted, - OwnershipTransferred, - SettingsChanged, - UserRenamed, - UserTimedOut, - UserBanned, - BanRemoved, - InviteCreated, - InviteDeleted, - ReportHandled, - MessageDeleted, - UserPurged, - VoiceKicked, - VoiceMuted, - CommunityVoiceSet, - AttachmentDeleted, - GhostEnabled, - GhostDisabled, - GhostVisit, - GhostVoice, - BackupCreated, - BackupDeleted, - BackupDownloaded, -} - -impl AdminActionKind { - pub const ALL: [Self; 31] = [ - AdminActionKind::RoleChanged, - AdminActionKind::UserDeleted, - AdminActionKind::UserSuspended, - AdminActionKind::UserUnsuspended, - AdminActionKind::SessionsRevoked, - AdminActionKind::PasswordReset, - AdminActionKind::ProfileCleared, - AdminActionKind::UserCreated, - AdminActionKind::CommunityDeleted, - AdminActionKind::OwnershipTransferred, - AdminActionKind::SettingsChanged, - AdminActionKind::UserRenamed, - AdminActionKind::UserTimedOut, - AdminActionKind::UserBanned, - AdminActionKind::BanRemoved, - AdminActionKind::InviteCreated, - AdminActionKind::InviteDeleted, - AdminActionKind::ReportHandled, - AdminActionKind::MessageDeleted, - AdminActionKind::UserPurged, - AdminActionKind::VoiceKicked, - AdminActionKind::VoiceMuted, - AdminActionKind::CommunityVoiceSet, - AdminActionKind::AttachmentDeleted, - AdminActionKind::GhostEnabled, - AdminActionKind::GhostDisabled, - AdminActionKind::GhostVisit, - AdminActionKind::GhostVoice, - AdminActionKind::BackupCreated, - AdminActionKind::BackupDeleted, - AdminActionKind::BackupDownloaded, - ]; - - pub const fn as_str(self) -> &'static str { - match self { - AdminActionKind::RoleChanged => "role_changed", - AdminActionKind::UserDeleted => "user_deleted", - AdminActionKind::UserSuspended => "user_suspended", - AdminActionKind::UserUnsuspended => "user_unsuspended", - AdminActionKind::SessionsRevoked => "sessions_revoked", - AdminActionKind::PasswordReset => "password_reset", - AdminActionKind::ProfileCleared => "profile_cleared", - AdminActionKind::UserCreated => "user_created", - AdminActionKind::CommunityDeleted => "community_deleted", - AdminActionKind::OwnershipTransferred => "ownership_transferred", - AdminActionKind::SettingsChanged => "settings_changed", - AdminActionKind::UserRenamed => "user_renamed", - AdminActionKind::UserTimedOut => "user_timed_out", - AdminActionKind::UserBanned => "user_banned", - AdminActionKind::BanRemoved => "ban_removed", - AdminActionKind::InviteCreated => "invite_created", - AdminActionKind::InviteDeleted => "invite_deleted", - AdminActionKind::ReportHandled => "report_handled", - AdminActionKind::MessageDeleted => "message_deleted", - AdminActionKind::UserPurged => "user_purged", - AdminActionKind::VoiceKicked => "voice_kicked", - AdminActionKind::VoiceMuted => "voice_muted", - AdminActionKind::CommunityVoiceSet => "community_voice_set", - AdminActionKind::AttachmentDeleted => "attachment_deleted", - AdminActionKind::GhostEnabled => "ghost_enabled", - AdminActionKind::GhostDisabled => "ghost_disabled", - AdminActionKind::GhostVisit => "ghost_visit", - AdminActionKind::GhostVoice => "ghost_voice", - AdminActionKind::BackupCreated => "backup_created", - AdminActionKind::BackupDeleted => "backup_deleted", - AdminActionKind::BackupDownloaded => "backup_downloaded", - } - } - - pub fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|kind| kind.as_str() == text) +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + AdminActionKind { + RoleChanged => "role_changed", + UserDeleted => "user_deleted", + UserSuspended => "user_suspended", + UserUnsuspended => "user_unsuspended", + SessionsRevoked => "sessions_revoked", + PasswordReset => "password_reset", + ProfileCleared => "profile_cleared", + UserCreated => "user_created", + CommunityDeleted => "community_deleted", + OwnershipTransferred => "ownership_transferred", + SettingsChanged => "settings_changed", + UserRenamed => "user_renamed", + UserTimedOut => "user_timed_out", + UserBanned => "user_banned", + BanRemoved => "ban_removed", + InviteCreated => "invite_created", + InviteDeleted => "invite_deleted", + ReportHandled => "report_handled", + MessageDeleted => "message_deleted", + UserPurged => "user_purged", + VoiceKicked => "voice_kicked", + VoiceMuted => "voice_muted", + CommunityVoiceSet => "community_voice_set", + AttachmentDeleted => "attachment_deleted", + GhostEnabled => "ghost_enabled", + GhostDisabled => "ghost_disabled", + GhostVisit => "ghost_visit", + GhostVoice => "ghost_voice", + BackupCreated => "backup_created", + BackupDeleted => "backup_deleted", + BackupDownloaded => "backup_downloaded", } } @@ -397,22 +320,10 @@ impl AdminAction { AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, } } -} -const fn action_names() -> [&'static str; 31] { - let mut names = [""; 31]; - let mut index = 0; - while index < 31 { - names[index] = AdminActionKind::ALL[index].as_str(); - index += 1; + pub fn name(&self) -> &'static str { + self.kind().as_str() } - names -} - -pub const ACTION_NAMES: [&str; 31] = action_names(); - -pub fn action_name(action: &AdminAction) -> &'static str { - action.kind().as_str() } pub fn action_detail(action: &AdminAction) -> Option { @@ -442,28 +353,16 @@ pub struct AdminLogEntry { pub action: AdminAction, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] -pub enum ReportStatus { - Open, - Resolved, - Dismissed, +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] + ReportStatus { + Open => "open", + Resolved => "resolved", + Dismissed => "dismissed", + } } impl ReportStatus { - pub const ALL: [Self; 3] = [ - ReportStatus::Open, - ReportStatus::Resolved, - ReportStatus::Dismissed, - ]; - - pub fn as_str(self) -> &'static str { - match self { - ReportStatus::Open => "open", - ReportStatus::Resolved => "resolved", - ReportStatus::Dismissed => "dismissed", - } - } - pub fn label(self) -> &'static str { match self { ReportStatus::Open => "Open", @@ -471,10 +370,6 @@ impl ReportStatus { ReportStatus::Dismissed => "Dismissed", } } - - pub fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|status| status.as_str() == text) - } } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -559,24 +454,11 @@ pub struct CommunityUsage { pub count: u64, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] -pub enum ServerBanKind { - Username, - Ip, -} - -impl ServerBanKind { - pub const ALL: [Self; 2] = [ServerBanKind::Username, ServerBanKind::Ip]; - - pub fn as_str(self) -> &'static str { - match self { - ServerBanKind::Username => "username", - ServerBanKind::Ip => "ip", - } - } - - pub fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|kind| kind.as_str() == text) +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] + ServerBanKind { + Username => "username", + Ip => "ip", } } @@ -627,33 +509,13 @@ pub struct Friends { pub outgoing: Vec, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] -pub enum AttachmentKind { - Image, - Video, - Audio, - File, -} - -impl AttachmentKind { - pub const ALL: [Self; 4] = [ - AttachmentKind::Image, - AttachmentKind::Video, - AttachmentKind::Audio, - AttachmentKind::File, - ]; - - pub fn as_str(self) -> &'static str { - match self { - AttachmentKind::Image => "image", - AttachmentKind::Video => "video", - AttachmentKind::Audio => "audio", - AttachmentKind::File => "file", - } - } - - pub fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|kind| kind.as_str() == text) +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] + AttachmentKind { + Image => "image", + Video => "video", + Audio => "audio", + File => "file", } } diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs index 438fdba..6da7d44 100644 --- a/crates/common/src/network.rs +++ b/crates/common/src/network.rs @@ -8,7 +8,7 @@ use crate::{ }, error::Error, event::Event, - request::{DownloadRequest, Request, UploadHeader}, + request::{Request, UploadHeader}, response::Response, }; @@ -90,11 +90,8 @@ pub async fn receive_download_status( DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0]))) } -pub async fn send_upload_header( - header: &UploadHeader, - send_stream: &mut SendStream, -) -> Result<(), Error> { - let payload = bitcode::encode(header); +async fn send_framed(value: &T, send_stream: &mut SendStream) -> Result<(), Error> { + let payload = bitcode::encode(value); send_stream .write_all(&(payload.len() as u32).to_le_bytes()) .await?; @@ -102,15 +99,18 @@ pub async fn send_upload_header( Ok(()) } -pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result { +async fn receive_framed( + receive_stream: &mut RecvStream, + maximum: usize, +) -> Result { let mut length_bytes = [0u8; 4]; receive_stream.read_exact(&mut length_bytes).await?; let length = u32::from_le_bytes(length_bytes) as usize; - if length > UPLOAD_HEADER_MAX_LENGTH { + if length > maximum { return Err(Error::ReadBoundExceed { actual: length, - maximum: UPLOAD_HEADER_MAX_LENGTH, + maximum, }); } @@ -119,21 +119,15 @@ pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result Result<(), Error> { - send_stream.write_all(&bitcode::encode(request)).await?; - Ok(()) + send_framed(header, send_stream).await } -pub async fn receive_download_request( - receive_stream: &mut RecvStream, -) -> Result { - let bytes = receive_stream - .read_to_end(DOWNLOAD_REQUEST_MAX_READ_LENGTH) - .await?; - Ok(bitcode::decode(&bytes)?) +pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result { + receive_framed(receive_stream, UPLOAD_HEADER_MAX_LENGTH).await } pub async fn send_encoded(value: &T, send_stream: &mut SendStream) -> Result<(), Error> { @@ -155,13 +149,6 @@ pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Ok(()) } -pub async fn receive_request( - mut receive_stream: RecvStream, - limit: usize, -) -> Result { - receive_decoded(&mut receive_stream, limit).await -} - pub async fn send_request( request: &Request, mut send_stream: SendStream, @@ -175,27 +162,9 @@ pub async fn send_request( } pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> { - let payload = bitcode::encode(event); - send_stream - .write_all(&(payload.len() as u32).to_le_bytes()) - .await?; - send_stream.write_all(&payload).await?; - Ok(()) + send_framed(event, send_stream).await } pub async fn receive_event(receive_stream: &mut RecvStream) -> Result { - let mut length_bytes = [0u8; 4]; - receive_stream.read_exact(&mut length_bytes).await?; - - let length = u32::from_le_bytes(length_bytes) as usize; - if length > EVENT_MAX_ENCODED_LENGTH { - return Err(Error::ReadBoundExceed { - actual: length, - maximum: EVENT_MAX_ENCODED_LENGTH, - }); - } - - let mut payload = vec![0u8; length]; - receive_stream.read_exact(&mut payload).await?; - Ok(bitcode::decode(&payload)?) + receive_framed(receive_stream, EVENT_MAX_ENCODED_LENGTH).await } diff --git a/crates/common/src/permission.rs b/crates/common/src/permission.rs index c72a672..babb74c 100644 --- a/crates/common/src/permission.rs +++ b/crates/common/src/permission.rs @@ -4,10 +4,6 @@ pub fn is_builder(role: Role) -> bool { role == Role::Builder } -pub fn bypasses_limits(role: Role) -> bool { - is_builder(role) -} - pub fn effective_rank(role: Role, rank: Option) -> Option { match role { Role::Builder => Some(Rank::Builder), @@ -31,10 +27,6 @@ pub fn can_join(role: Role, banned: bool) -> bool { !banned || is_builder(role) } -pub fn can_edit_message(is_author: bool) -> bool { - is_author -} - pub fn can_pin(actor: Option, direct: bool) -> bool { actor >= Some(Rank::Moderator) || (direct && actor.is_some()) } diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index 77c88d5..650fe5c 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -1,6 +1,6 @@ use bitcode::{Decode, Encode}; -use crate::model::{Presence, Rank, ReportStatus, Role, ServerSettings}; +use crate::model::{BanScope, Presence, Rank, ReportStatus, Role, ServerSettings}; #[derive(Debug, Clone, Encode, Decode)] pub struct UploadHeader { @@ -256,7 +256,7 @@ pub enum Request { BanUser { user_id: String, reason: Option, - ip: bool, + scope: BanScope, }, ServerBans, RemoveServerBan { diff --git a/crates/common/src/time.rs b/crates/common/src/time.rs index dd296a1..ea36244 100644 --- a/crates/common/src/time.rs +++ b/crates/common/src/time.rs @@ -20,3 +20,13 @@ pub fn created_at_ms(id: &str) -> Option { pub fn id_bound(ms: u64) -> String { format!("{:08x}-{:04x}", ms >> 16, ms & 0xffff) } + +pub fn range_bounds( + after_ms: Option, + before_ms: Option, +) -> (Option, Option) { + ( + after_ms.map(id_bound), + before_ms.map(|before| id_bound(before + 1)), + ) +} diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index 5e52a65..04d869e 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -27,6 +27,10 @@ fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), Inv Ok(()) } +fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { + check_length(text.chars().count(), minimum, maximum) +} + fn check( input: &str, minimum: usize, @@ -75,21 +79,20 @@ pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> { } pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> { - if attachments == 0 { - return validate_message_body(body, maximum); - } - - check(body, 0, maximum, false).map_err(Error::Message) + let minimum = if attachments == 0 { + MINIMUM_MESSAGE_LENGTH + } else { + 0 + }; + check(body, minimum, maximum, false).map_err(Error::Message) } pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { - check_length(question.chars().count(), 1, MAXIMUM_POLL_QUESTION_LENGTH) - .map_err(Error::Message)?; + check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(Error::Message)?; check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS) .map_err(Error::Message)?; for option in options { - check_length(option.chars().count(), 1, MAXIMUM_POLL_OPTION_LENGTH) - .map_err(Error::Message)?; + check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(Error::Message)?; } Ok(()) @@ -117,8 +120,7 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> { } pub fn validate_attachment_name(name: &str) -> Result<(), Error> { - check_length(name.chars().count(), 1, MAXIMUM_ATTACHMENT_NAME_LENGTH) - .map_err(Error::AttachmentName)?; + check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(Error::AttachmentName)?; if name.contains(['/', '\\']) || name.chars().any(char::is_control) { return Err(Error::AttachmentName(InvalidInput::ForbiddenCharacter)); @@ -186,7 +188,7 @@ pub fn validate_announcement(text: &str) -> Result<(), Error> { return Err(Error::Announcement(InvalidInput::MultiLine)); } - check_length(text.chars().count(), 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(Error::Announcement) + check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(Error::Announcement) } pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> { @@ -214,7 +216,7 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> { if reason.contains(['\n', '\r']) { return Err(Error::Reason(InvalidInput::MultiLine)); } - check_length(reason.chars().count(), 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason) + check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason) } pub fn validate_forward(count: usize) -> Result<(), Error> { @@ -226,11 +228,11 @@ pub fn validate_status(status: &str) -> Result<(), Error> { return Err(Error::Status(InvalidInput::MultiLine)); } - check_length(status.chars().count(), 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status) + check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status) } pub fn validate_device(name: &str) -> Result<(), Error> { - check_length(name.chars().count(), 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(Error::Device) + check_text(name, 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(Error::Device) } pub fn validate_avatar_size(bytes: &[u8], maximum: u64) -> Result<(), Error> { diff --git a/crates/server/src/admin_log.rs b/crates/server/src/admin_log.rs index 25617ad..df8647b 100644 --- a/crates/server/src/admin_log.rs +++ b/crates/server/src/admin_log.rs @@ -1,8 +1,6 @@ use common::{ constant::LOG_PAGE_LIMIT, - model::{ - AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail, action_name, - }, + model::{AdminAction, AdminLogEntry, ReportStatus, Role, action_detail}, time, }; use turso::Connection; @@ -10,53 +8,53 @@ use turso::Connection; use crate::{database::new_id, error::Error, user}; fn action_of(text: &str, detail: Option) -> Option { - let kind = AdminActionKind::parse(text)?; - Some(match kind { - AdminActionKind::RoleChanged => AdminAction::RoleChanged { + Some(match text { + "role_changed" => AdminAction::RoleChanged { role: Role::parse(&detail?)?, }, - AdminActionKind::UserDeleted => AdminAction::UserDeleted, - AdminActionKind::UserSuspended => AdminAction::UserSuspended, - AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended, - AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked, - AdminActionKind::PasswordReset => AdminAction::PasswordReset, - AdminActionKind::ProfileCleared => AdminAction::ProfileCleared, - AdminActionKind::UserCreated => AdminAction::UserCreated, - AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted, - AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred, - AdminActionKind::SettingsChanged => AdminAction::SettingsChanged, - AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? }, - AdminActionKind::UserTimedOut => AdminAction::UserTimedOut { + "user_deleted" => AdminAction::UserDeleted, + "user_suspended" => AdminAction::UserSuspended, + "user_unsuspended" => AdminAction::UserUnsuspended, + "sessions_revoked" => AdminAction::SessionsRevoked, + "password_reset" => AdminAction::PasswordReset, + "profile_cleared" => AdminAction::ProfileCleared, + "user_created" => AdminAction::UserCreated, + "community_deleted" => AdminAction::CommunityDeleted, + "ownership_transferred" => AdminAction::OwnershipTransferred, + "settings_changed" => AdminAction::SettingsChanged, + "user_renamed" => AdminAction::UserRenamed { from: detail? }, + "user_timed_out" => AdminAction::UserTimedOut { minutes: detail?.parse().ok()?, }, - AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail }, - AdminActionKind::BanRemoved => AdminAction::BanRemoved, - AdminActionKind::InviteCreated => AdminAction::InviteCreated, - AdminActionKind::InviteDeleted => AdminAction::InviteDeleted, - AdminActionKind::ReportHandled => AdminAction::ReportHandled { + "user_banned" => AdminAction::UserBanned { reason: detail }, + "ban_removed" => AdminAction::BanRemoved, + "invite_created" => AdminAction::InviteCreated, + "invite_deleted" => AdminAction::InviteDeleted, + "report_handled" => AdminAction::ReportHandled { status: ReportStatus::parse(&detail?)?, }, - AdminActionKind::MessageDeleted => AdminAction::MessageDeleted, - AdminActionKind::UserPurged => AdminAction::UserPurged { + "message_deleted" => AdminAction::MessageDeleted, + "user_purged" => AdminAction::UserPurged { messages: detail?.parse().ok()?, }, - AdminActionKind::VoiceKicked => AdminAction::VoiceKicked, - AdminActionKind::VoiceMuted => AdminAction::VoiceMuted { + "voice_kicked" => AdminAction::VoiceKicked, + "voice_muted" => AdminAction::VoiceMuted { muted: detail?.parse().ok()?, }, - AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet { + "community_voice_set" => AdminAction::CommunityVoiceSet { enabled: detail?.parse().ok()?, }, - AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted, - AdminActionKind::GhostEnabled => AdminAction::GhostEnabled, - AdminActionKind::GhostDisabled => AdminAction::GhostDisabled, - AdminActionKind::GhostVisit => AdminAction::GhostVisit, - AdminActionKind::GhostVoice => AdminAction::GhostVoice { + "attachment_deleted" => AdminAction::AttachmentDeleted, + "ghost_enabled" => AdminAction::GhostEnabled, + "ghost_disabled" => AdminAction::GhostDisabled, + "ghost_visit" => AdminAction::GhostVisit, + "ghost_voice" => AdminAction::GhostVoice { seconds: detail?.parse().ok()?, }, - AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? }, - AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? }, - AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? }, + "backup_created" => AdminAction::BackupCreated { name: detail? }, + "backup_deleted" => AdminAction::BackupDeleted { name: detail? }, + "backup_downloaded" => AdminAction::BackupDownloaded { name: detail? }, + _ => return None, }) } @@ -76,7 +74,7 @@ pub async fn record( actor_id, target_id, community, - action_name(action), + action.name(), detail.as_deref(), ), ) @@ -93,16 +91,11 @@ pub async fn list( before_ms: Option, conn: &Connection, ) -> Result, Error> { + let (after, before) = time::range_bounds(after_ms, before_ms); let mut rows = conn .query( &format!("SELECT l.id, l.action, l.detail, {}, {}, l.community FROM admin_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.action = ?3) AND (?4 IS NULL OR l.id >= ?4) AND (?5 IS NULL OR l.id < ?5) ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")), - ( - actor_id, - target_id, - action, - after_ms.map(time::id_bound), - before_ms.map(|before| time::id_bound(before + 1)), - ), + (actor_id, target_id, action, after, before), ) .await?; diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index 7319510..ece590e 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -15,13 +15,13 @@ use common::{ Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, }, network::{ - DownloadStatus, receive_download_request, receive_upload_header, send_download_status, - send_encoded, send_response, + DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, receive_upload_header, + send_download_status, send_encoded, send_response, }, permission, request::{DownloadRequest, UploadHeader}, response::Response, - time::HOUR_MILLIS, + time::{self, HOUR_MILLIS}, validate::{validate_attachment_name, validate_attachment_size}, }; use image::{ImageFormat, ImageReader, Limits}; @@ -32,41 +32,45 @@ use tokio::{ }; use tracing::error; use turso::{Connection, Row}; -use uuid::{Timestamp, Uuid}; use crate::{ community, database::{self, DB, new_id}, error::Error, + message, request::{actor_rank, ensure}, server_settings, user, }; const COLLECT_INTERVAL: Duration = Duration::from_secs(600); -const STALE_AGE: Duration = Duration::from_millis(HOUR_MILLIS); const MAXIMUM_IMAGE_SIDE: u32 = 16384; const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; const LIST_LIMIT: i64 = 200; const USAGE_LIMIT: i64 = 50; +const THUMB_SUFFIX: &str = ".thumb"; +const PART_SUFFIX: &str = ".part"; pub struct Stored { pub attachment: Attachment, pub uploader_id: String, pub community_id: String, pub message_id: Option, - pub bound: bool, } -pub fn directory(database_path: &str) -> Result { +pub fn sibling_directory(database_path: &str, name: &str) -> Result { let directory = Path::new(database_path) .parent() .unwrap_or_else(|| Path::new("")) - .join("attachments"); + .join(name); std::fs::create_dir_all(&directory)?; Ok(directory) } +pub fn directory(database_path: &str) -> Result { + sibling_directory(database_path, "attachments") +} + fn from_row(row: &Row) -> Result { let size: i64 = row.get(2)?; let kind: String = row.get(3)?; @@ -121,14 +125,20 @@ pub async fn bind( (message_id, attachment_id.as_str(), user_id, community_id), ) .await?; - if bound != 1 { - return Err(CommonError::NotFound.into()); - } + message::expect_one(bound)?; } Ok(()) } +fn thumb_path(directory: &Path, id: &str) -> PathBuf { + directory.join(format!("{id}{THUMB_SUFFIX}")) +} + +fn part_path(directory: &Path, id: &str) -> PathBuf { + directory.join(format!("{id}{PART_SUFFIX}")) +} + fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> { std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop)) } @@ -142,6 +152,17 @@ async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> { Ok(()) } +async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), Error> { + if tokio::fs::try_exists(&source) + .await + .map_err(|_| CommonError::Server)? + { + duplicate(source, target).await?; + } + + Ok(()) +} + pub async fn copy( attachment: &Attachment, message_id: &str, @@ -170,31 +191,20 @@ pub async fn copy( .await?; duplicate(directory.join(&attachment.id), directory.join(&id)).await?; - let thumbnail = directory.join(format!("{}.thumb", attachment.id)); - if tokio::fs::try_exists(&thumbnail) - .await - .map_err(|_| CommonError::Server)? - { - duplicate(thumbnail, directory.join(format!("{id}.thumb"))).await?; - } - - Ok(()) + duplicate_if_exists( + thumb_path(directory, &attachment.id), + thumb_path(directory, &id), + ) + .await } pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result, Error> { - let mut rows = conn - .query( - "SELECT id FROM attachment WHERE message_id = ?1", - (message_id,), - ) - .await?; - - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get(0)?); - } - - Ok(ids) + message::ids_where( + "SELECT id FROM attachment WHERE message_id = ?1", + message_id, + conn, + ) + .await } pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), Error> { @@ -278,15 +288,24 @@ pub async fn usage(conn: &Connection) -> Result<(Vec, Vec Ok((users, communities)) } -async fn bytes_of(sql: &str, id: &str, conn: &Connection) -> Result { - let mut rows = conn.query(sql, (id,)).await?; +async fn over_quota( + sql: &str, + key: &str, + limit: u64, + size: u64, + conn: &Connection, +) -> Result { + if limit == 0 { + return Ok(false); + } + let mut rows = conn.query(sql, (key,)).await?; let row = rows .next() .await? .ok_or(turso::Error::QueryReturnedNoRows)?; - let bytes: i64 = row.get(0)?; + let used: i64 = row.get(0)?; - Ok(bytes as u64) + Ok(used as u64 + size > limit) } async fn ensure_quota( @@ -296,47 +315,39 @@ async fn ensure_quota( settings: &ServerSettings, conn: &Connection, ) -> Result<(), Error> { - if settings.user_quota_bytes > 0 { - let used = bytes_of( - "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1", - user_id, - conn, - ) - .await?; - if used + size > settings.user_quota_bytes { - return Err(CommonError::QuotaExceeded.into()); - } + if over_quota( + "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1", + user_id, + settings.user_quota_bytes, + size, + conn, + ) + .await? + { + return Err(CommonError::QuotaExceeded.into()); } - - if settings.community_quota_bytes > 0 { - let used = bytes_of( - "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?1", - community_id, - conn, - ) - .await?; - if used + size > settings.community_quota_bytes { - return Err(CommonError::QuotaExceeded.into()); - } + if over_quota( + "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?1", + community_id, + settings.community_quota_bytes, + size, + conn, + ) + .await? + { + return Err(CommonError::QuotaExceeded.into()); } Ok(()) } pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result, Error> { - let mut rows = conn - .query( - "SELECT id FROM attachment WHERE uploader_id = ?1", - (user_id,), - ) - .await?; - - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get(0)?); - } - - Ok(ids) + message::ids_where( + "SELECT id FROM attachment WHERE uploader_id = ?1", + user_id, + conn, + ) + .await } pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Error> { @@ -349,26 +360,24 @@ pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Erro pub fn remove_files(attachment_ids: &[String], directory: &Path) { for id in attachment_ids { let _ = std::fs::remove_file(directory.join(id)); - let _ = std::fs::remove_file(directory.join(format!("{id}.thumb"))); + let _ = std::fs::remove_file(thumb_path(directory, id)); } } pub async fn read(attachment_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id IS NOT NULL, message_id FROM attachment WHERE id = ?1", + "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id FROM attachment WHERE id = ?1", (attachment_id,), ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let bound: i64 = row.get(8)?; Ok(Stored { attachment: from_row(&row)?, uploader_id: row.get(6)?, community_id: row.get(7)?, - message_id: row.get(9)?, - bound: bound != 0, + message_id: row.get(8)?, }) } @@ -488,7 +497,7 @@ pub async fn store( .await?; let id = new_id(); - let part = directory.join(format!("{id}.part")); + let part = part_path(directory, &id); let path = directory.join(&id); let head = match receive_body(reader, &part, header.size).await { Ok(head) => head, @@ -501,7 +510,7 @@ pub async fn store( let described = if is_image(&head) { let source = path.clone(); - let thumbnail = directory.join(format!("{id}.thumb")); + let thumbnail = thumb_path(directory, &id); tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail)) .await .ok() @@ -571,10 +580,10 @@ async fn locate( let rank = actor_rank(user, &stored.community_id, &conn).await?; ensure(permission::can_read(rank))?; - ensure(stored.bound || stored.uploader_id == user.id)?; + ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; let path = if request.thumbnail { - directory.join(format!("{}.thumb", stored.attachment.id)) + thumb_path(directory, &stored.attachment.id) } else { directory.join(&stored.attachment.id) }; @@ -606,7 +615,8 @@ pub async fn download( db: &DB, directory: &Path, ) -> Result<(), Error> { - let request = receive_download_request(&mut receive_stream).await?; + let request: DownloadRequest = + receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; match locate(user, &request, db, directory).await { Ok((path, length)) => { @@ -637,12 +647,9 @@ pub async fn collect(db: DB, directory: PathBuf) { async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { let conn = database::connect(db).await?; - let stale_at = SystemTime::now() - STALE_AGE; - let stale_secs = stale_at - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - let stale_id = Uuid::new_v7(Timestamp::from_unix_time(stale_secs, 0, 0, 0)).to_string(); + let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS); + let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms); + let stale_id = time::id_bound(stale_ms); conn.execute( "DELETE FROM attachment WHERE message_id IS NULL AND id < ?1", @@ -661,8 +668,8 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); let id = name - .strip_suffix(".thumb") - .or_else(|| name.strip_suffix(".part")) + .strip_suffix(THUMB_SUFFIX) + .or_else(|| name.strip_suffix(PART_SUFFIX)) .unwrap_or(&name); let stale = entry.metadata()?.modified()? < stale_at; @@ -685,7 +692,7 @@ mod tests { use image::{ImageFormat, RgbImage}; use crate::{ - attachment::store, + attachment::{store, thumb_path}, community, database, message, network::{Services, State}, request::handle, @@ -749,6 +756,6 @@ mod tests { assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); std::fs::remove_file(directory.join(&attachment.id)).unwrap(); - std::fs::remove_file(directory.join(format!("{}.thumb", attachment.id))).unwrap(); + std::fs::remove_file(thumb_path(directory, &attachment.id)).unwrap(); } } diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 3223cc1..5de60a1 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -124,7 +124,7 @@ pub async fn create_account( validate_username(username)?; validate_password(password)?; - if user::by_username(username, conn).await?.is_some() { + if user::is_taken(username, None, conn).await? { return Err(CommonError::Taken.into()); } @@ -176,7 +176,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { if user::suspended(&user.id, conn).await? { return Err(CommonError::Suspended.into()); } - if !permission::bypasses_limits(user.role) && server_settings::read(conn).await?.maintenance { + if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance { return Err(CommonError::Maintenance.into()); } @@ -184,16 +184,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { } pub async fn resume(token: &str, conn: &Connection) -> Result { - let user = { - let mut rows = conn - .query( - &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user::user_columns("user")), - (token,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?; - user::from_row(&row)? - }; + let user = user::by_session_token(token, conn).await?; admit(&user, conn).await?; seen(&user.id, token, conn).await?; diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs index c471344..3474ef4 100644 --- a/crates/server/src/backup.rs +++ b/crates/server/src/backup.rs @@ -4,7 +4,7 @@ use common::{ error::Error as CommonError, model::{AdminAction, BackupInfo, User}, network::{ - DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_request, send_download_status, + DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, send_download_status, send_encoded, }, permission, @@ -27,13 +27,7 @@ const PREFIX: &str = "yumush-"; const EXTENSION: &str = ".db"; pub fn directory(database_path: &str) -> Result { - let directory = Path::new(database_path) - .parent() - .unwrap_or_else(|| Path::new("")) - .join("backups"); - std::fs::create_dir_all(&directory)?; - - Ok(directory) + attachment::sibling_directory(database_path, "backups") } fn created_secs(name: &str) -> Option { @@ -125,12 +119,13 @@ async fn locate( pub async fn download( user: Option<&User>, - receive_stream: RecvStream, + mut receive_stream: RecvStream, mut send_stream: SendStream, db: &DB, directory: &Path, ) -> Result<(), Error> { - let request = receive_request(receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; + let request: Request = + receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; match locate(user, request, db, directory).await { Ok((path, length)) => { diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs index e0144e1..bc44834 100644 --- a/crates/server/src/community.rs +++ b/crates/server/src/community.rs @@ -1,32 +1,19 @@ use common::{ error::Error as CommonError, model::{Community, CommunityKind, User}, + string_enum, validate::validate_community_name, }; use turso::{Connection, Row}; use crate::{database::new_id, error::Error, user}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Group, - Direct, - Notes, -} - -impl Kind { - const ALL: [Self; 3] = [Kind::Group, Kind::Direct, Kind::Notes]; - - pub fn as_str(self) -> &'static str { - match self { - Kind::Group => "group", - Kind::Direct => "direct", - Kind::Notes => "notes", - } - } - - fn parse(text: &str) -> Option { - Self::ALL.into_iter().find(|kind| kind.as_str() == text) +string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + Kind { + Group => "group", + Direct => "direct", + Notes => "notes", } } @@ -35,14 +22,13 @@ type Raw = (String, String, Kind, Option, bool); fn raw_of(row: &Row) -> Result { let text: String = row.get(2)?; let kind = Kind::parse(&text).ok_or(CommonError::Server)?; - let voice_enabled: i64 = row.get(4)?; Ok(( row.get(0)?, row.get(1)?, kind, row.get(3)?, - voice_enabled != 0, + user::bool_at(row, 4)?, )) } @@ -191,20 +177,20 @@ pub async fn communities_of(user_id: &str, conn: &Connection) -> Result Result, Error> { let mut rows = conn .query( - "SELECT id, name, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE", + "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE", (Kind::Group.as_str(),), ) .await?; let mut communities = Vec::new(); while let Some(row) = rows.next().await? { - let voice_enabled: i64 = row.get(3)?; + let (id, name, _, avatar_id, voice_enabled) = raw_of(&row)?; communities.push(Community { - id: row.get(0)?, - name: row.get(1)?, + id, + name, kind: CommunityKind::Group, - avatar_id: row.get(2)?, - voice_enabled: voice_enabled != 0, + avatar_id, + voice_enabled, }); } @@ -290,10 +276,7 @@ pub async fn is_direct(community_id: &str, conn: &Connection) -> Result Result { - Ok(matches!( - kind(community_id, conn).await?, - Kind::Direct | Kind::Notes - )) + Ok(kind(community_id, conn).await? != Kind::Group) } pub async fn set_voice_enabled( @@ -303,7 +286,7 @@ pub async fn set_voice_enabled( ) -> Result<(), Error> { conn.execute( "UPDATE community SET voice_enabled = ?2 WHERE id = ?1", - (community_id, enabled as i64), + (community_id, i64::from(enabled)), ) .await?; @@ -318,9 +301,8 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result Result { diff --git a/crates/server/src/database.rs b/crates/server/src/database.rs index bb1664e..0c2795f 100644 --- a/crates/server/src/database.rs +++ b/crates/server/src/database.rs @@ -306,6 +306,20 @@ pub async fn connect(db: &DB) -> Result { Ok(conn) } +pub async fn scalar_i64( + conn: &Connection, + sql: &str, + params: impl turso::IntoParams, +) -> Result { + let mut rows = conn.query(sql, params).await?; + let row = rows + .next() + .await? + .ok_or(turso::Error::QueryReturnedNoRows)?; + + Ok(row.get(0)?) +} + async fn migrate(db: &DB) -> Result<(), Error> { let mut conn = connect(db).await?; let applied = user_version(&conn).await?; diff --git a/crates/server/src/direct.rs b/crates/server/src/direct.rs index 29bfe71..7633c8c 100644 --- a/crates/server/src/direct.rs +++ b/crates/server/src/direct.rs @@ -1,10 +1,7 @@ -use common::{ - error::Error as CommonError, - model::{Community, Rank}, -}; +use common::model::{Community, Rank}; use turso::Connection; -use crate::{community, error::Error, user, user_community}; +use crate::{community, error::Error, request::ensure, user, user_community}; async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result, Error> { let mut rows = conn @@ -17,14 +14,13 @@ async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result Result<(Community, bool), Error> { - if me == other { - return Err(CommonError::Forbidden.into()); - } +pub enum Opening { + Created(Community), + Existing(Community), +} + +pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result { + ensure(me != other)?; user::read(other, conn).await?; let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; @@ -33,7 +29,7 @@ pub async fn open( let community = community::read(&community_id, me, &tx).await?; tx.commit().await?; - return Ok((community, false)); + return Ok(Opening::Existing(community)); } let community_id = community::create_direct(&tx).await?; @@ -47,5 +43,5 @@ pub async fn open( let community = community::read(&community_id, me, &tx).await?; tx.commit().await?; - Ok((community, true)) + Ok(Opening::Created(community)) } diff --git a/crates/server/src/friend.rs b/crates/server/src/friend.rs index 4e7dd2c..a847fcf 100644 --- a/crates/server/src/friend.rs +++ b/crates/server/src/friend.rs @@ -4,7 +4,7 @@ use common::{ }; use turso::Connection; -use crate::{error::Error, user}; +use crate::{database, error::Error, request::ensure_with, user}; async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn.query(sql, (user_id,)).await?; @@ -23,9 +23,7 @@ async fn pair_exists( second: &str, conn: &Connection, ) -> Result { - let mut rows = conn.query(sql, (first, second)).await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let count: i64 = row.get(0)?; + let count = database::scalar_i64(conn, sql, (first, second)).await?; Ok(count > 0) } @@ -94,15 +92,14 @@ pub async fn state(user_id: &str, conn: &Connection) -> Result { } pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> { - if me == other { - return Err(CommonError::Forbidden.into()); - } + ensure_with(me != other, CommonError::Forbidden)?; user::read(other, conn).await?; let tx = conn.transaction().await?; - if is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await? { - return Err(CommonError::Taken.into()); - } + ensure_with( + !(is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await?), + CommonError::Taken, + )?; if is_requested(other, me, &tx).await? { befriend(me, other, &tx).await?; } else { diff --git a/crates/server/src/invitation.rs b/crates/server/src/invitation.rs index 0f7b4f5..1b217b4 100644 --- a/crates/server/src/invitation.rs +++ b/crates/server/src/invitation.rs @@ -1,7 +1,7 @@ use common::{error::Error as CommonError, model::Invitation}; use turso::Connection; -use crate::{community, error::Error, user}; +use crate::{community, database, error::Error, user}; pub async fn of(user_id: &str, conn: &Connection) -> Result, Error> { let pairs = { @@ -32,14 +32,12 @@ pub async fn of(user_id: &str, conn: &Connection) -> Result, Err } pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2", - (community_id, user_id), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let count: i64 = row.get(0)?; + let count = database::scalar_i64( + conn, + "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2", + (community_id, user_id), + ) + .await?; Ok(count > 0) } @@ -60,14 +58,13 @@ pub async fn insert( } pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), Error> { - if !exists(community_id, user_id, conn).await? { - return Err(CommonError::NotFound.into()); - } - conn.execute( - "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2", - (community_id, user_id), - ) - .await?; + let mut rows = conn + .query( + "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2 RETURNING community_id", + (community_id, user_id), + ) + .await?; + rows.next().await?.ok_or(CommonError::NotFound)?; Ok(()) } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 6eb51d2..74cdf85 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -29,7 +29,7 @@ pub mod voice; #[cfg(test)] mod test; -use common::{config::Config, model::Role}; +use common::{config::Config, error::Error as CommonError, model::Role}; use crate::error::Error; @@ -45,23 +45,16 @@ pub struct ServerConfig { pub key_path: String, } -impl ServerConfig { - fn parse(content: &str) -> Result { - let config = Config::parse(content)?; - - Ok(Self { - database_path: config.get("database_path")?, - server_address: config.get("server_address")?, - certificate_path: config.get("certificate_path")?, - key_path: config.get("key_path")?, - }) - } -} - fn load_config() -> Result { let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?; + let config = Config::parse(&content)?; - ServerConfig::parse(&content) + Ok(ServerConfig { + database_path: config.get("database_path")?, + server_address: config.get("server_address")?, + certificate_path: config.get("certificate_path")?, + key_path: config.get("key_path")?, + }) } pub async fn showtime() -> Result<(), Error> { @@ -90,7 +83,10 @@ pub async fn set_role(username: &str, role: Role) -> Result<(), Error> { let config = load_config()?; let database = database::open(&config.database_path).await?; let conn = database::connect(&database).await?; - user::set_role(username, role, &conn).await?; + let user = user::by_username(username, &conn) + .await? + .ok_or(CommonError::NotFound)?; + user::set_role_by_id(&user.id, role, &conn).await?; Ok(()) } diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index a043bd2..c553b91 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -259,6 +259,25 @@ async fn insert( Ok(message_id) } +pub fn expect_one(affected: u64) -> Result<(), Error> { + if affected != 1 { + return Err(CommonError::NotFound.into()); + } + + Ok(()) +} + +pub async fn ids_where(sql: &str, value: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn.query(sql, (value,)).await?; + + let mut ids = Vec::new(); + while let Some(row) = rows.next().await? { + ids.push(row.get(0)?); + } + + Ok(ids) +} + pub async fn ensure_in_community( message_id: &str, community_id: &str, @@ -410,9 +429,7 @@ pub async fn close_poll(message_id: &str, conn: &Connection) -> Result Result Result Result, Error> { - let mut rows = conn - .query("SELECT id FROM message WHERE user_id = ?1", (user_id,)) - .await?; - - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get(0)?); - } - - Ok(ids) + ids_where("SELECT id FROM message WHERE user_id = ?1", user_id, conn).await } pub async fn search( @@ -512,6 +518,7 @@ pub async fn search( before_ms: Option, conn: &Connection, ) -> Result, Error> { + let (after, before) = time::range_bounds(after_ms, before_ms); let mut rows = conn .query( "SELECT id FROM message WHERE (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR id >= ?4) AND (?5 IS NULL OR id < ?5) ORDER BY id DESC LIMIT ?6", @@ -519,8 +526,8 @@ pub async fn search( text, user_id, community_id, - after_ms.map(time::id_bound), - before_ms.map(|before| time::id_bound(before + 1)), + after, + before, SEARCH_LIMIT as i64, ), ) @@ -548,7 +555,10 @@ pub async fn search( } async fn origin(sources: &[Message], conn: &Connection) -> Result, Error> { - let community_id = &sources[0].community_id; + let Some(first) = sources.first() else { + return Ok(None); + }; + let community_id = &first.community_id; if sources .iter() .any(|source| &source.community_id != community_id) @@ -632,15 +642,21 @@ async fn write_snippet( Ok(()) } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForwardMode { + Copy, + Snippet, +} + pub async fn forward( user: &User, community_id: &str, sources: &[Message], - snippet: bool, + mode: ForwardMode, directory: &Path, conn: &Connection, ) -> Result, Error> { - if !snippet { + if mode == ForwardMode::Copy { let mut created = Vec::new(); for source in sources { let message_id = insert(&user.id, community_id, &source.body, None, conn).await?; @@ -840,7 +856,7 @@ mod tests { &user, &community.id, &[first, second], - true, + message::ForwardMode::Snippet, &test::directory(), &conn, ) diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index 0623525..b59c439 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -8,9 +8,10 @@ use common::{ event::Event as Push, model::User, network::{ - REQUEST_MAX_READ_LENGTH, StreamKind, receive_request, receive_stream_kind, send_event, + REQUEST_MAX_READ_LENGTH, StreamKind, receive_decoded, receive_stream_kind, send_event, send_response, }, + request::Request, voice::decode_packet, }; use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream}; @@ -30,7 +31,11 @@ use crate::{ const CHANNEL_LENGTH: usize = 2048; const SESSION_LENGTH: usize = 64; -type Signed = (String, String, Connection); +struct Signed { + user_id: String, + token: String, + connection: Connection, +} #[derive(Clone, Default)] pub struct Presence(Arc>>); @@ -91,7 +96,11 @@ impl Presence { pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) { self.0.lock().unwrap().insert( connection.stable_id(), - (user_id.to_string(), token.to_string(), connection.clone()), + Signed { + user_id: user_id.to_string(), + token: token.to_string(), + connection: connection.clone(), + }, ); } @@ -105,7 +114,7 @@ impl Presence { .lock() .unwrap() .values() - .map(|(user_id, _, _)| user_id.clone()) + .map(|signed| signed.user_id.clone()) .collect(); user_ids.sort(); user_ids.dedup(); @@ -117,46 +126,30 @@ impl Presence { self.user_ids().len() } - pub fn disconnect(&self, user_id: &str) { + fn close_where(&self, matches: impl Fn(&Signed) -> bool, reason: &[u8]) { let connections: Vec = self .0 .lock() .unwrap() .values() - .filter(|(signed_id, _, _)| signed_id == user_id) - .map(|(_, _, connection)| connection.clone()) + .filter(|signed| matches(signed)) + .map(|signed| signed.connection.clone()) .collect(); for connection in connections { - connection.close(0u32.into(), b"signed out"); + connection.close(0u32.into(), reason); } } + pub fn disconnect(&self, user_id: &str) { + self.close_where(|signed| signed.user_id == user_id, b"signed out"); + } + pub fn disconnect_except(&self, keep: &[String], reason: &[u8]) { - let connections: Vec = self - .0 - .lock() - .unwrap() - .values() - .filter(|(signed_id, _, _)| !keep.contains(signed_id)) - .map(|(_, _, connection)| connection.clone()) - .collect(); - for connection in connections { - connection.close(0u32.into(), reason); - } + self.close_where(|signed| !keep.contains(&signed.user_id), reason); } pub fn disconnect_token(&self, token: &str) { - let connections: Vec = self - .0 - .lock() - .unwrap() - .values() - .filter(|(_, signed_token, _)| signed_token == token) - .map(|(_, _, connection)| connection.clone()) - .collect(); - for connection in connections { - connection.close(0u32.into(), b"session revoked"); - } + self.close_where(|signed| signed.token == token, b"session revoked"); } } @@ -279,12 +272,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro .await?; broadcasts .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); - for broadcast in broadcasts { - let _ = shared - .event_sender - .send(Event::Broadcast(Box::new(broadcast))) - .await; - } + publish(&shared, broadcasts).await; } Ok(()) @@ -347,10 +335,10 @@ async fn route( async fn answer( connection: Connection, state: Arc>, - (send_stream, receive_stream): (SendStream, RecvStream), + (send_stream, mut receive_stream): (SendStream, RecvStream), shared: Shared, ) -> Result<(), Error> { - let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?; + let request: Request = receive_decoded(&mut receive_stream, REQUEST_MAX_READ_LENGTH).await?; let before = signed_in(&state); let (response, broadcasts) = request::handle( @@ -393,16 +381,20 @@ async fn answer( } } + publish(&shared, broadcasts).await; + + send_response(&response, send_stream).await?; + + Ok(()) +} + +async fn publish(shared: &Shared, broadcasts: Vec) { for broadcast in broadcasts { let _ = shared .event_sender .send(Event::Broadcast(Box::new(broadcast))) .await; } - - send_response(&response, send_stream).await?; - - Ok(()) } async fn broadcast_presence(shared: &Shared, user_id: &str) { @@ -411,14 +403,7 @@ async fn broadcast_presence(shared: &Shared, user_id: &str) { Err(error) => Err(error), }; match broadcasts { - Ok(broadcasts) => { - for broadcast in broadcasts { - let _ = shared - .event_sender - .send(Event::Broadcast(Box::new(broadcast))) - .await; - } - } + Ok(broadcasts) => publish(shared, broadcasts).await, Err(error) => warn!("presence: {error}"), } } diff --git a/crates/server/src/report.rs b/crates/server/src/report.rs index 4b42f48..c67e907 100644 --- a/crates/server/src/report.rs +++ b/crates/server/src/report.rs @@ -5,7 +5,11 @@ use common::{ }; use turso::Connection; -use crate::{database::new_id, error::Error, user}; +use crate::{ + database::{self, new_id}, + error::Error, + user, +}; pub async fn is_open( reporter_id: &str, @@ -13,17 +17,12 @@ pub async fn is_open( message_id: Option<&str>, conn: &Connection, ) -> Result { - let mut rows = conn - .query( - "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND COALESCE(message_id, '') = COALESCE(?3, '') AND status = ?4)", - (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), - ) - .await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let found: i64 = row.get(0)?; + let found = database::scalar_i64( + conn, + "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", + (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), + ) + .await?; Ok(found != 0) } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 2ae24e6..74fa066 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -8,8 +8,8 @@ use common::{ error::Error as CommonError, event::Event, model::{ - AdminAction, CallLog, CommunityKind, CommunitySummary, LogAction, Member, Presence, Rank, - ReportStatus, ServerBanKind, ServerSettings, User, VoiceRoom, + AdminAction, BanScope, CallLog, CommunitySummary, LogAction, Member, Message, Presence, + Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom, }, permission, request::Request, @@ -32,7 +32,7 @@ use crate::{ notes, overview, rate_limit::RateLimit, report, server_ban, server_settings, stats, user, user_community, - voice::{CallEnd, GhostChange, Left, Voice}, + voice::{CallEnd, Left, Voice}, }; pub struct Broadcast { @@ -109,7 +109,8 @@ async fn dispatch( (Response::Done, broadcasts) } Request::Logout => { - let (_, token) = authenticated(state, &conn).await?; + authenticated(state, &conn).await?; + let token = session_token(state)?; authentication::logout(&token, &conn).await?; let broadcasts = leave_connection_voice(voice, connection, &conn).await?; set_state(state, State::Anonymous); @@ -123,15 +124,9 @@ async fn dispatch( ) } Request::UpdateUser { username } => { - let (me, token) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let user = user::update(&me.id, &username, &conn).await?; - set_state( - state, - State::Authenticated { - user: user.clone(), - token, - }, - ); + cache_user(state, user.clone()); let broadcasts = user_updated(&user, &conn).await?; (Response::User(user), broadcasts) } @@ -140,8 +135,7 @@ async fn dispatch( Vec::new(), ), Request::UpdateServerSettings { settings } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; validate_server_settings(&settings)?; let previous = server_settings::read(&conn).await?; server_settings::update(&settings, &conn).await?; @@ -170,12 +164,13 @@ async fn dispatch( (Response::ServerSettings(settings), broadcasts) } Request::SetDevice { name } => { - let (_, token) = authenticated(state, &conn).await?; + authenticated(state, &conn).await?; + let token = session_token(state)?; authentication::set_device(&token, &name, &conn).await?; (Response::Done, Vec::new()) } Request::Sessions { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; ( Response::Sessions(authentication::sessions(&user_id, &conn).await?), @@ -186,7 +181,7 @@ async fn dispatch( user_id, session_id, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; let token = authentication::revoke_session(&user_id, &session_id, &conn).await?; presence.disconnect_token(&token); @@ -201,7 +196,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::RenameUser { user_id, username } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let target = managed(&me, &user_id, &conn).await?; let user = user::update(&user_id, &username, &conn).await?; admin_log::record( @@ -218,8 +213,7 @@ async fn dispatch( (Response::User(user), broadcasts) } Request::CreateUser { username, password } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; let user = authentication::create_account(&username, &password, &conn).await?; admin_log::record( Some(&me.id), @@ -232,8 +226,7 @@ async fn dispatch( (Response::User(user), Vec::new()) } Request::Users => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; (Response::Users(user::all(&conn).await?), Vec::new()) } Request::AdminLogs { @@ -243,8 +236,7 @@ async fn dispatch( after_ms, before_ms, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::AdminLogs( admin_log::list( @@ -261,23 +253,21 @@ async fn dispatch( ) } Request::DailyStats { days } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::DailyStats(stats::daily(days, &conn).await?), Vec::new(), ) } Request::Overview => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::Overview(overview::read(presence, voice, &conn).await?), Vec::new(), ) } Request::SuspendUser { user_id, suspended } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; user::set_suspended(&user_id, suspended, &conn).await?; let action = if suspended { @@ -293,7 +283,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::RevokeSessions { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; authentication::revoke_sessions(&user_id, &conn).await?; presence.disconnect(&user_id); @@ -308,7 +298,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::ResetPassword { user_id, password } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; authentication::reset_password(&user_id, &password, &conn).await?; presence.disconnect(&user_id); @@ -323,9 +313,9 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::ClearProfile { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; - user::remove_avatar(&user_id, &mut conn).await?; + user::set_avatar(&user_id, None, &mut conn).await?; let user = user::update_status(&user_id, "", &conn).await?; admin_log::record( Some(&me.id), @@ -339,7 +329,7 @@ async fn dispatch( (Response::User(user), broadcasts) } Request::SetRole { user_id, role } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ensure(permission::can_set_role(me.role, me.id == user_id))?; let user = user::set_role_by_id(&user_id, role, &conn).await?; admin_log::record( @@ -357,26 +347,20 @@ async fn dispatch( (Response::User(user), broadcasts) } Request::UpdateStatus { status } => { - let (me, token) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let user = user::update_status(&me.id, &status, &conn).await?; - set_state( - state, - State::Authenticated { - user: user.clone(), - token, - }, - ); + cache_user(state, user.clone()); let broadcasts = user_updated(&user, &conn).await?; (Response::User(user), broadcasts) } Request::UpdatePresence { presence: chosen } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; user::update_presence(&me.id, chosen, &conn).await?; let broadcasts = presence_changed(presence, &me.id, &conn).await?; (Response::Done, broadcasts) } Request::ReadPresences => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let mut presences = Vec::new(); for user_id in related_user_ids(&me.id, &conn).await? { let effective = effective_presence(presence, &user_id, &conn).await?; @@ -387,29 +371,17 @@ async fn dispatch( (Response::Presences(presences), Vec::new()) } Request::UpdateAvatar { image } => { - let (me, token) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?; - let user = user::set_avatar(&me.id, &image, &mut conn).await?; - set_state( - state, - State::Authenticated { - user: user.clone(), - token, - }, - ); + let user = user::set_avatar(&me.id, Some(&image), &mut conn).await?; + cache_user(state, user.clone()); let broadcasts = user_updated(&user, &conn).await?; (Response::User(user), broadcasts) } Request::RemoveAvatar => { - let (me, token) = authenticated(state, &conn).await?; - let user = user::remove_avatar(&me.id, &mut conn).await?; - set_state( - state, - State::Authenticated { - user: user.clone(), - token, - }, - ); + let me = authenticated(state, &conn).await?; + let user = user::set_avatar(&me.id, None, &mut conn).await?; + cache_user(state, user.clone()); let broadcasts = user_updated(&user, &conn).await?; (Response::User(user), broadcasts) } @@ -421,7 +393,7 @@ async fn dispatch( ) } Request::DeleteUser { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_delete_user( me.role, @@ -445,19 +417,19 @@ async fn dispatch( broadcasts.extend(voice_closed(voice, &community_id, &tx).await?); community::delete(&community_id, &user_id, &tx).await?; let event = Event::CommunityDeleted { community_id }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); } for community in community::communities_of(&user_id, &tx).await? { let members = user_community::members(&community.id, &tx).await?; - if matches!(community.kind, CommunityKind::Direct { .. }) { + if community.kind.is_direct() { community::delete(&community.id, &user_id, &tx).await?; } let event = Event::UserDeleted { user_id: user_id.clone(), }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); } - broadcasts.extend(leave_voice(voice, &user_id, &tx).await?); + broadcasts.extend(leave_user_voice(voice, &user_id, &tx).await?); let deleted = user::delete(&user_id, &tx).await?; tx.commit().await?; if me.id == user_id { @@ -466,10 +438,10 @@ async fn dispatch( (Response::User(deleted), broadcasts) } Request::CreateCommunity { name } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let limit = server_settings::read(&conn).await?.max_communities_per_user; let owned = user_community::owned_groups(&me.id, &conn).await?; - ensure_or( + ensure_with( limit == 0 || owned < limit as usize, CommonError::LimitReached, )?; @@ -481,21 +453,17 @@ async fn dispatch( (Response::Community(community), Vec::new()) } Request::ReadCommunity { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Community(community::read(&community_id, &me.id, &conn).await?), Vec::new(), ) } Request::UpdateCommunity { community_id, name } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; - ensure(permission::can_rename_community( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_rename_community).await?; let updated = community::update(&community_id, &name, &me.id, &conn).await?; let action = LogAction::Renamed { name: updated.name.clone(), @@ -503,17 +471,15 @@ async fn dispatch( log::record(&community_id, Some(&me.id), None, &action, &conn).await?; let members = user_community::members(&community_id, &conn).await?; let event = Event::CommunityUpdated(updated.clone()); - (Response::Community(updated), broadcast(event, &members)) + (Response::Community(updated), vec![broadcast(event, &members)]) } Request::UpdateCommunityAvatar { community_id, image, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; - ensure(permission::can_rename_community( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_rename_community).await?; if let Some(bytes) = &image { validate_avatar_size(bytes, server_settings::read(&conn).await?.max_avatar_bytes)?; } @@ -527,14 +493,12 @@ async fn dispatch( log::record(&community_id, Some(&me.id), None, &action, &conn).await?; let members = user_community::members(&community_id, &conn).await?; let event = Event::CommunityUpdated(updated.clone()); - (Response::Community(updated), broadcast(event, &members)) + (Response::Community(updated), vec![broadcast(event, &members)]) } Request::DeleteCommunity { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; - ensure(permission::can_delete_community( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_delete_community).await?; let tx = conn.transaction().await?; let members = user_community::members(&community_id, &tx).await?; let owned = @@ -555,15 +519,13 @@ async fn dispatch( let event = Event::CommunityDeleted { community_id: deleted.id.clone(), }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); (Response::Community(deleted), broadcasts) } Request::LeaveCommunity { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; - ensure(permission::can_leave( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_leave).await?; let tx = conn.transaction().await?; user_community::leave(&me.id, &community_id, &tx).await?; log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?; @@ -572,26 +534,24 @@ async fn dispatch( community::delete(&community_id, &me.id, &tx).await?; } tx.commit().await?; - let mut broadcasts = voice_leave(voice, &community_id, &me.id, &conn).await?; + let mut broadcasts = leave_room_voice(voice, &community_id, &me.id, &conn).await?; let event = Event::MemberLeft { community_id, user_id: me.id, }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); (Response::Done, broadcasts) } Request::Communities => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ( Response::Communities(community::communities_of(&me.id, &conn).await?), Vec::new(), ) } Request::Members { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Members(user_community::members(&community_id, &conn).await?), Vec::new(), @@ -602,14 +562,14 @@ async fn dispatch( user_id, reason, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; remove_member( &me, Removal { community_id, user_id, reason, - banned: false, + sanction: Sanction::Kick, }, voice, &mut conn, @@ -621,14 +581,14 @@ async fn dispatch( user_id, reason, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; remove_member( &me, Removal { community_id, user_id, reason, - banned: true, + sanction: Sanction::Ban, }, voice, &mut conn, @@ -639,10 +599,8 @@ async fn dispatch( community_id, user_id, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_unban( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_unban).await?; user_community::unban(&user_id, &community_id, &conn).await?; log::record( &community_id, @@ -655,10 +613,8 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::Bans { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_unban( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_unban).await?; ( Response::Bans(user_community::bans(&community_id, &conn).await?), Vec::new(), @@ -669,8 +625,8 @@ async fn dispatch( user_id, rank, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_set_rank( actor_rank(&me, &community_id, &conn).await?, @@ -692,7 +648,7 @@ async fn dispatch( user_id, rank, }; - (Response::Done, broadcast(event, &members)) + (Response::Done, vec![broadcast(event, &members)]) } Request::CreateMessage { community_id, @@ -700,7 +656,7 @@ async fn dispatch( attachments, reply_to, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let settings = server_settings::read(&conn).await?; limit_messages(&me, rate_limit, &settings)?; validate_new_message( @@ -708,9 +664,7 @@ async fn dispatch( attachments.len(), settings.max_message_length as usize, )?; - ensure(permission::can_post( - actor_rank(&me, &community_id, &conn).await?, - ))?; + allowed(&me, &community_id, &conn, permission::can_post).await?; let tx = conn.transaction().await?; let created = message::create( &me.id, @@ -723,19 +677,16 @@ async fn dispatch( .await?; stats::mark_active(&me.id, &tx).await?; tx.commit().await?; - let members = user_community::members(&community_id, &conn).await?; - let event = Event::MessageCreated(created.clone()); - ( - Response::Message(created), - broadcast_with(event, &members, &me.id), - ) + let broadcast = + message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?; + (Response::Message(created), vec![broadcast]) } Request::ForwardMessages { message_ids, community_id, snippet, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?; validate_forward(message_ids.len())?; ensure(permission::can_post( @@ -750,32 +701,34 @@ async fn dispatch( ))?; sources.push(source); } + let mode = if snippet { + message::ForwardMode::Snippet + } else { + message::ForwardMode::Copy + }; let created = - message::forward(&me, &community_id, &sources, snippet, directory, &tx).await?; + message::forward(&me, &community_id, &sources, mode, directory, &tx).await?; tx.commit().await?; let members = user_community::members(&community_id, &conn).await?; let mut broadcasts = Vec::new(); for message in &created { let event = Event::MessageCreated(message.clone()); - broadcasts.extend(broadcast_with(event, &members, &me.id)); + broadcasts.push(broadcast_with(event, &members, &me.id)); } (Response::Messages(created), broadcasts) } Request::UpdateMessage { message_id, body } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; - ensure(permission::can_edit_message(existing.user_id == me.id))?; + ensure(existing.user_id == me.id)?; validate_message_body( &body, server_settings::read(&conn).await?.max_message_length as usize, )?; let updated = message::update(&message_id, &body, &conn).await?; - let members = user_community::members(&updated.community_id, &conn).await?; - let event = Event::MessageUpdated(updated.clone()); - ( - Response::Message(updated), - broadcast_with(event, &members, &me.id), - ) + let broadcast = + message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + (Response::Message(updated), vec![broadcast]) } Request::CreatePoll { community_id, @@ -783,31 +736,26 @@ async fn dispatch( options, multiple, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let settings = server_settings::read(&conn).await?; limit_messages(&me, rate_limit, &settings)?; validate_poll(&question, &options)?; - ensure(permission::can_post( - actor_rank(&me, &community_id, &conn).await?, - ))?; + allowed(&me, &community_id, &conn, permission::can_post).await?; let tx = conn.transaction().await?; let created = message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx) .await?; stats::mark_active(&me.id, &tx).await?; tx.commit().await?; - let members = user_community::members(&community_id, &conn).await?; - let event = Event::MessageCreated(created.clone()); - ( - Response::Message(created), - broadcast_with(event, &members, &me.id), - ) + let broadcast = + message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?; + (Response::Message(created), vec![broadcast]) } Request::Vote { message_id, positions, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_read( actor_rank(&me, &existing.community_id, &conn).await?, @@ -815,36 +763,36 @@ async fn dispatch( let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?; validate_vote(poll, &positions)?; let updated = message::vote(&message_id, &me.id, &positions, &conn).await?; - let members = user_community::members(&updated.community_id, &conn).await?; - let event = Event::MessageUpdated(updated); - (Response::Done, broadcast_with(event, &members, &me.id)) + let broadcast = + message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + (Response::Done, vec![broadcast]) } Request::ClosePoll { message_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_close_poll( actor_rank(&me, &existing.community_id, &conn).await?, existing.user_id == me.id, ))?; let updated = message::close_poll(&message_id, &conn).await?; - let members = user_community::members(&updated.community_id, &conn).await?; - let event = Event::MessageUpdated(updated); - (Response::Done, broadcast_with(event, &members, &me.id)) + let broadcast = + message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + (Response::Done, vec![broadcast]) } Request::React { message_id, emoji } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; validate_reaction(&emoji)?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_read( actor_rank(&me, &existing.community_id, &conn).await?, ))?; let updated = message::react(&message_id, &me.id, &emoji, &conn).await?; - let members = user_community::members(&updated.community_id, &conn).await?; - let event = Event::MessageUpdated(updated); - (Response::Done, broadcast_with(event, &members, &me.id)) + let broadcast = + message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + (Response::Done, vec![broadcast]) } Request::Pin { message_id, pinned } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; let direct = community::is_direct(&existing.community_id, &conn).await?; ensure(permission::can_pin( @@ -852,12 +800,12 @@ async fn dispatch( direct, ))?; let updated = message::pin(&message_id, pinned, &conn).await?; - let members = user_community::members(&updated.community_id, &conn).await?; - let event = Event::MessageUpdated(updated); - (Response::Done, broadcast_with(event, &members, &me.id)) + let broadcast = + message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?; + (Response::Done, vec![broadcast]) } Request::Unreads => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ( Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?), Vec::new(), @@ -867,28 +815,22 @@ async fn dispatch( community_id, message_id, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure( - user_community::rank(&me.id, &community_id, &conn) - .await? - .is_some(), - )?; + let me = authenticated(state, &conn).await?; + ensure(!is_outsider(&me.id, &community_id, &conn).await?)?; message::ensure_in_community(&message_id, &community_id, &conn).await?; user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?; (Response::Done, Vec::new()) } Request::Pins { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Messages(message::pinned(&community_id, &conn).await?), Vec::new(), ) } Request::DeleteMessage { message_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; let author = user::read(&existing.user_id, &conn).await?; ensure(permission::can_delete_message( @@ -918,24 +860,17 @@ async fn dispatch( ) .await?; } - let members = user_community::members(&deleted.community_id, &conn).await?; - let event = Event::MessageDeleted(deleted.clone()); - ( - Response::Message(deleted), - broadcast_with(event, &members, &me.id), - ) + let broadcast = + message_broadcast(&deleted, Event::MessageDeleted, &me.id, &conn).await?; + (Response::Message(deleted), vec![broadcast]) } Request::ReadMessages { community_id, before, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; - let outsider = user_community::rank(&me.id, &community_id, &conn) - .await? - .is_none(); + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; + let outsider = is_outsider(&me.id, &community_id, &conn).await?; if before.is_none() && let Some(connection) = connection { @@ -966,10 +901,8 @@ async fn dispatch( (Response::Messages(messages), Vec::new()) } Request::JoinVoice { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_join_voice( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_join_voice).await?; ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?; ensure( permission::is_builder(me.role) @@ -980,9 +913,7 @@ async fn dispatch( }; let members = user_community::members(&community_id, &conn).await?; let muted = user::voice_muted(&me.id, &conn).await?; - let outsider = user_community::rank(&me.id, &community_id, &conn) - .await? - .is_none(); + let outsider = is_outsider(&me.id, &community_id, &conn).await?; let ghost = outsider || user::is_ghost(&me.id, &conn).await?; let starts_call = !ghost && community::is_direct(&community_id, &conn).await? @@ -996,21 +927,10 @@ async fn dispatch( let created = message::create_call_log(&community_id, &me.id, CallLog::Started, &conn) .await?; - broadcasts.extend(broadcast(Event::MessageCreated(created), &members)); + broadcasts.push(broadcast(Event::MessageCreated(created), &members)); } if !ghost { - let event = Event::VoiceJoined { - community_id: community_id.clone(), - user_id: me.id.clone(), - }; - broadcasts.extend(broadcast(event, &members)); - if muted { - let event = Event::VoiceMuted { - user_id: me.id.clone(), - muted, - }; - broadcasts.extend(broadcast(event, &members)); - } + broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members)); } ( Response::Voice(voice.participants(&community_id)), @@ -1018,10 +938,8 @@ async fn dispatch( ) } Request::Typing { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; let broadcasts = if user::is_ghost(&me.id, &conn).await? { Vec::new() } else { @@ -1034,7 +952,7 @@ async fn dispatch( community_id, user_id: me.id.clone(), }; - broadcast(event, &members) + vec![broadcast(event, &members)] }; (Response::Done, broadcasts) } @@ -1046,11 +964,9 @@ async fn dispatch( ) } Request::DeclineCall { community_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ensure(community::is_direct(&community_id, &conn).await?)?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + allowed(&me, &community_id, &conn, permission::can_read).await?; let participants = voice.participants(&community_id); ensure(!participants.is_empty() && !participants.contains(&me.id))?; voice.decline(&community_id); @@ -1059,21 +975,19 @@ async fn dispatch( let members = user_community::members(&community_id, &conn).await?; ( Response::Done, - broadcast(Event::MessageCreated(created), &members), + vec![broadcast(Event::MessageCreated(created), &members)], ) } Request::VoiceParticipants { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; ( Response::Voice(voice.participants(&community_id)), Vec::new(), ) } Request::FindUser { username } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let found = user::by_username(&username, &conn) .await? .filter(|found| found.id != me.id) @@ -1081,47 +995,51 @@ async fn dispatch( (Response::User(found), Vec::new()) } Request::OpenDirect { user_id } => { - let (me, _) = authenticated(state, &conn).await?; - let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?; - let broadcasts = if created { - let peer_view = community::read(&community.id, &user_id, &conn).await?; - vec![Broadcast { - event: Event::CommunityAdded(peer_view), - user_ids: vec![user_id], - }] - } else { - Vec::new() - }; - (Response::Community(community), broadcasts) + let me = authenticated(state, &conn).await?; + match direct::open(&me.id, &user_id, &mut conn).await? { + direct::Opening::Created(community) => { + let peer_view = community::read(&community.id, &user_id, &conn).await?; + ( + Response::Community(community), + vec![Broadcast { + event: Event::CommunityAdded(peer_view), + user_ids: vec![user_id], + }], + ) + } + direct::Opening::Existing(community) => { + (Response::Community(community), Vec::new()) + } + } } Request::OpenNotes => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ( Response::Community(notes::open(&me.id, &mut conn).await?), Vec::new(), ) } Request::Friends => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ( Response::Friends(friend::state(&me.id, &conn).await?), Vec::new(), ) } Request::AddFriend { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; friend::add(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) } Request::AcceptFriend { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; friend::accept(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) } Request::RemoveFriend { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; friend::remove(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) @@ -1130,11 +1048,9 @@ async fn dispatch( community_id, user_id, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; let target = user::read(&user_id, &conn).await?; if user_community::rank(&user_id, &community_id, &conn) .await? @@ -1160,14 +1076,14 @@ async fn dispatch( (Response::Done, vec![broadcast]) } Request::Invitations => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ( Response::Invitations(invitation::of(&me.id, &conn).await?), Vec::new(), ) } Request::AcceptInvitation { community_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let tx = conn.transaction().await?; invitation::take(&community_id, &me.id, &tx).await?; let banned = user_community::is_banned(&me.id, &community_id, &tx).await?; @@ -1184,12 +1100,12 @@ async fn dispatch( rank: Rank::Member, }, }; - let mut broadcasts = broadcast(event, &members); + let mut broadcasts = vec![broadcast(event, &members)]; broadcasts.push(invitations_updated(&me.id, &conn).await?); (Response::Community(community), broadcasts) } Request::DeclineInvitation { community_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; invitation::take(&community_id, &me.id, &conn).await?; ( Response::Done, @@ -1197,18 +1113,15 @@ async fn dispatch( ) } Request::Logs { community_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read_logs( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read_logs).await?; ( Response::Logs(log::list(&community_id, &conn).await?), Vec::new(), ) } Request::AllCommunities => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; let mut summaries = Vec::new(); for community in community::groups(&conn).await? { let members = user_community::members(&community.id, &conn).await?; @@ -1228,11 +1141,9 @@ async fn dispatch( community_id, user_id, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_fixed(&community_id, &conn).await?)?; - ensure(permission::can_transfer_ownership( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + ensure_editable(&community_id, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_transfer_ownership).await?; let tx = conn.transaction().await?; let members = user_community::members(&community_id, &tx).await?; let target = members @@ -1282,12 +1193,12 @@ async fn dispatch( user_id: changed_id, rank, }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); } (Response::Done, broadcasts) } Request::TimeoutUser { user_id, minutes } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); user::set_timeout(&user_id, until, &conn).await?; @@ -1308,9 +1219,9 @@ async fn dispatch( Request::BanUser { user_id, reason, - ip, + scope, } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let target = managed(&me, &user_id, &conn).await?; validate_reason(reason.as_deref())?; let tx = conn.transaction().await?; @@ -1324,7 +1235,9 @@ async fn dispatch( &tx, ) .await?; - if ip && let Some(address) = user::last_ip(&user_id, &tx).await? { + if scope == BanScope::AccountAndIp + && let Some(address) = user::last_ip(&user_id, &tx).await? + { server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx) .await?; } @@ -1341,50 +1254,47 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::ServerBans => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::ServerBans(server_ban::list(&conn).await?), Vec::new(), ) } Request::RemoveServerBan { id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; server_ban::remove(&id, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?; (Response::Done, Vec::new()) } Request::CreateInviteCode { uses, hours } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ensure(permission::is_builder(me.role) && uses > 0)?; let code = invite::create(uses, hours, &me, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?; (Response::InviteCode(code), Vec::new()) } Request::InviteCodes => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::InviteCodes(invite::list(&conn).await?), Vec::new(), ) } Request::DeleteInviteCode { code } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; invite::delete(&code, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?; (Response::Done, Vec::new()) } Request::ReportMessage { message_id, reason } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; let message = message::read(&message_id, &conn).await?; let actor = actor_rank(&me, &message.community_id, &conn).await?; ensure(permission::can_read(actor) && me.id != message.user_id)?; validate_reason(Some(&reason))?; - ensure_untaken( - report::is_open(&me.id, &message.user_id, Some(&message_id), &conn).await?, + ensure_with( + !report::is_open(&me.id, &message.user_id, Some(&message_id), &conn).await?, + CommonError::Taken, )?; report::insert( &me.id, @@ -1396,27 +1306,29 @@ async fn dispatch( &conn, ) .await?; - (Response::Done, report_created(&conn).await?) + (Response::Done, vec![report_created(&conn).await?]) } Request::ReportUser { user_id, reason } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; user::read(&user_id, &conn).await?; ensure(me.id != user_id)?; validate_reason(Some(&reason))?; - ensure_untaken(report::is_open(&me.id, &user_id, None, &conn).await?)?; + ensure_with( + !report::is_open(&me.id, &user_id, None, &conn).await?, + CommonError::Taken, + )?; report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?; - (Response::Done, report_created(&conn).await?) + (Response::Done, vec![report_created(&conn).await?]) } Request::Reports { status } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::Reports(report::list(status, &conn).await?), Vec::new(), ) } Request::HandleReport { report_id, status } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?; let target = report::handle(&report_id, status, &me.id, &conn).await?; admin_log::record( @@ -1436,8 +1348,7 @@ async fn dispatch( after_ms, before_ms, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; let hits = message::search( text.as_deref(), user_id.as_deref(), @@ -1450,16 +1361,14 @@ async fn dispatch( (Response::MessageHits(hits), Vec::new()) } Request::SearchCommunity { community_id, text } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_read( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_read).await?; let hits = message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?; (Response::MessageHits(hits), Vec::new()) } Request::PurgeUser { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; let tx = conn.transaction().await?; let upload_ids = attachment::uploads_of(&user_id, &tx).await?; @@ -1475,7 +1384,7 @@ async fn dispatch( } let community_members = &members[&deleted.community_id]; let event = Event::MessageDeleted(deleted); - broadcasts.extend(broadcast(event, community_members)); + broadcasts.push(broadcast(event, community_members)); } attachment::delete_uploads(&user_id, &tx).await?; admin_log::record( @@ -1496,8 +1405,7 @@ async fn dispatch( user_id, community_id, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::AttachmentInfos( attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?, @@ -1506,8 +1414,7 @@ async fn dispatch( ) } Request::DeleteAttachment { attachment_id } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; let stored = attachment::read(&attachment_id, &conn).await?; let community = community::label(&stored.community_id, &conn).await?; let tx = conn.transaction().await?; @@ -1524,21 +1431,19 @@ async fn dispatch( if let Some(message_id) = &stored.message_id { let updated = message::read(message_id, &tx).await?; let members = user_community::members(&updated.community_id, &tx).await?; - broadcasts = broadcast(Event::MessageUpdated(updated), &members); + broadcasts = vec![broadcast(Event::MessageUpdated(updated), &members)]; } tx.commit().await?; attachment::remove_files(&[attachment_id], directory); (Response::Done, broadcasts) } Request::StorageUsage => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; let (users, communities) = attachment::usage(&conn).await?; (Response::StorageUsage { users, communities }, Vec::new()) } Request::CreateBackup => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; let backup = backup::create(&conn, backups).await?; let action = AdminAction::BackupCreated { name: backup.name.clone(), @@ -1547,13 +1452,11 @@ async fn dispatch( (Response::Backup(backup), Vec::new()) } Request::Backups => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; (Response::Backups(backup::list(backups)?), Vec::new()) } Request::DeleteBackup { name } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; backup::delete(&name, backups)?; let action = AdminAction::BackupDeleted { name }; admin_log::record(Some(&me.id), None, None, &action, &conn).await?; @@ -1563,17 +1466,16 @@ async fn dispatch( return Err(CommonError::Server.into()); } Request::VoiceRooms => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + builder(state, &conn).await?; ( Response::VoiceRooms(voice_rooms(voice, &conn).await?), Vec::new(), ) } Request::KickFromVoice { user_id } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; - let broadcasts = leave_voice(voice, &user_id, &conn).await?; + let broadcasts = leave_user_voice(voice, &user_id, &conn).await?; if !broadcasts.is_empty() { admin_log::record( Some(&me.id), @@ -1587,7 +1489,7 @@ async fn dispatch( (Response::Done, broadcasts) } Request::ServerMute { user_id, muted } => { - let (me, _) = authenticated(state, &conn).await?; + let me = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; user::set_voice_muted(&user_id, muted, &conn).await?; admin_log::record( @@ -1619,10 +1521,8 @@ async fn dispatch( community_id, enabled, } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::can_manage_voice( - actor_rank(&me, &community_id, &conn).await?, - ))?; + let me = authenticated(state, &conn).await?; + allowed(&me, &community_id, &conn, permission::can_manage_voice).await?; let tx = conn.transaction().await?; community::set_voice_enabled(&community_id, enabled, &tx).await?; let updated = community::read(&community_id, &me.id, &tx).await?; @@ -1643,13 +1543,12 @@ async fn dispatch( broadcasts.extend(voice_silenced(voice, &community_id, &conn).await?); } let event = Event::CommunityUpdated(updated.clone()); - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); (Response::Community(updated), broadcasts) } Request::SetGhost { enabled } => { - let (me, _) = authenticated(state, &conn).await?; - ensure(permission::is_builder(me.role))?; + let me = builder(state, &conn).await?; user::set_ghost(&me.id, enabled, &conn).await?; let action = if enabled { AdminAction::GhostEnabled @@ -1659,16 +1558,15 @@ async fn dispatch( admin_log::record(Some(&me.id), None, None, &action, &conn).await?; let mut broadcasts = Vec::new(); let outsider = match voice.room_of(&me.id) { - Some(community_id) => user_community::rank(&me.id, &community_id, &conn) - .await? - .is_none(), + Some(community_id) => is_outsider(&me.id, &community_id, &conn).await?, None => false, }; if !outsider - && let Some(GhostChange { + && let Some(Left { community_id, ghost_seconds: seconds, call, + .. }) = voice.set_ghost(&me.id, enabled) { let members = user_community::members(&community_id, &conn).await?; @@ -1687,32 +1585,10 @@ async fn dispatch( .collect(), }); } else { - broadcasts.extend(broadcast( - Event::VoiceJoined { - community_id: community_id.clone(), - user_id: me.id.clone(), - }, - &members, - )); - if user::voice_muted(&me.id, &conn).await? { - broadcasts.extend(broadcast( - Event::VoiceMuted { - user_id: me.id.clone(), - muted: true, - }, - &members, - )); - } + let muted = user::voice_muted(&me.id, &conn).await?; + broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members)); if let Some(seconds) = seconds { - let community = community::label(&community_id, &conn).await?; - admin_log::record( - Some(&me.id), - None, - Some(&community), - &AdminAction::GhostVoice { seconds }, - &conn, - ) - .await?; + record_ghost_voice(&me.id, &community_id, seconds, &conn).await?; } } } @@ -1749,25 +1625,15 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result, Ok(rooms) } -async fn report_created(conn: &Connection) -> Result, Error> { - Ok(vec![Broadcast { +async fn report_created(conn: &Connection) -> Result { + Ok(Broadcast { event: Event::ReportCreated, user_ids: user::builder_ids(conn).await?, - }]) -} - -fn ensure_or(allowed: bool, error: CommonError) -> Result<(), Error> { - if allowed { - return Ok(()); - } - - Err(error.into()) + }) } -fn address(connection: Option<&quinn::Connection>) -> String { - connection - .map(|connection| connection.remote_address().ip().to_string()) - .unwrap_or_default() +fn ip_of(connection: Option<&quinn::Connection>) -> Option { + connection.map(|connection| connection.remote_address().ip().to_string()) } async fn limit_logins( @@ -1777,7 +1643,7 @@ async fn limit_logins( ) -> Result<(), Error> { let limit = server_settings::read(conn).await?.logins_per_minute; - Ok(rate_limit.allow(&address(connection), limit)?) + Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?) } fn limit_messages( @@ -1785,33 +1651,20 @@ fn limit_messages( rate_limit: &RateLimit, settings: &ServerSettings, ) -> Result<(), Error> { - if permission::bypasses_limits(me.role) { + if permission::is_builder(me.role) { return Ok(()); } Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?) } -fn ensure_untaken(taken: bool) -> Result<(), Error> { - if taken { - return Err(CommonError::Taken.into()); - } - - Ok(()) -} - async fn record_address( user: &User, connection: Option<&quinn::Connection>, conn: &Connection, ) -> Result<(), Error> { - if let Some(connection) = connection { - user::set_last_ip( - &user.id, - &connection.remote_address().ip().to_string(), - conn, - ) - .await?; + if let Some(ip) = ip_of(connection) { + user::set_last_ip(&user.id, &ip, conn).await?; } Ok(()) @@ -1821,7 +1674,7 @@ struct Removal { community_id: String, user_id: String, reason: Option, - banned: bool, + sanction: Sanction, } async fn remove_member( @@ -1834,10 +1687,10 @@ async fn remove_member( community_id, user_id, reason, - banned, + sanction, } = removal; validate_reason(reason.as_deref())?; - ensure(!community::is_fixed(&community_id, conn).await?)?; + ensure_editable(&community_id, conn).await?; let target = user::read(&user_id, conn).await?; ensure(permission::can_moderate( actor_rank(me, &community_id, conn).await?, @@ -1847,24 +1700,25 @@ async fn remove_member( let tx = conn.transaction().await?; let members = user_community::members(&community_id, &tx).await?; user_community::leave(&user_id, &community_id, &tx).await?; - let action = if banned { - user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?; - LogAction::Banned { - reason: reason.clone(), + let action = match sanction { + Sanction::Ban => { + user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?; + LogAction::Banned { + reason: reason.clone(), + } } - } else { - LogAction::Kicked { + Sanction::Kick => LogAction::Kicked { reason: reason.clone(), - } + }, }; log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; tx.commit().await?; - let mut broadcasts = voice_leave(voice, &community_id, &user_id, conn).await?; + let mut broadcasts = leave_room_voice(voice, &community_id, &user_id, conn).await?; broadcasts.push(Broadcast { event: Event::Removed { community_id: community_id.clone(), community_name: community.name, - banned, + sanction, reason, }, user_ids: vec![user_id.clone()], @@ -1873,7 +1727,7 @@ async fn remove_member( community_id, user_id, }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); Ok((Response::Done, broadcasts)) } @@ -1946,7 +1800,7 @@ async fn invitations_updated(user_id: &str, conn: &Connection) -> Result Result, Error> { - let direct = match call { - Some(_) => community::is_direct(community_id, conn).await?, - None => false, + let Some(call) = call else { + return Ok(Vec::new()); }; - let Some(call) = call.filter(|_| direct).and_then(call_log_of) else { + if !community::is_direct(community_id, conn).await? { + return Ok(Vec::new()); + } + let Some(call) = call_log_of(call) else { return Ok(Vec::new()); }; let created = message::create_call_log(community_id, user_id, call, conn).await?; - Ok(broadcast(Event::MessageCreated(created), members)) + Ok(vec![broadcast(Event::MessageCreated(created), members)]) } async fn voice_left(left: Left, conn: &Connection) -> Result, Error> { @@ -2074,19 +1930,11 @@ async fn voice_left(left: Left, conn: &Connection) -> Result, Err community_id: left.community_id, user_id: left.user_id, }; - broadcasts.extend(broadcast(event, &members)); + broadcasts.push(broadcast(event, &members)); return Ok(broadcasts); }; - let community = community::label(&left.community_id, conn).await?; - admin_log::record( - Some(&left.user_id), - None, - Some(&community), - &AdminAction::GhostVoice { seconds }, - conn, - ) - .await?; + record_ghost_voice(&left.user_id, &left.community_id, seconds, conn).await?; Ok(Vec::new()) } @@ -2107,21 +1955,36 @@ fn set_state(state: &Mutex, new_state: State) { *state.lock().unwrap() = new_state; } -async fn authenticated(state: &Mutex, conn: &Connection) -> Result<(User, String), Error> { - let (cached, token) = match state.lock().unwrap().clone() { - State::Anonymous => return Err(CommonError::Unauthenticated.into()), - State::Authenticated { user, token } => (user, token), - }; +fn session(state: &Mutex) -> Result<(User, String), Error> { + match state.lock().unwrap().clone() { + State::Anonymous => Err(CommonError::Unauthenticated.into()), + State::Authenticated { user, token } => Ok((user, token)), + } +} + +fn session_token(state: &Mutex) -> Result { + Ok(session(state)?.1) +} + +fn cache_user(state: &Mutex, user: User) { + if let State::Authenticated { user: cached, .. } = &mut *state.lock().unwrap() { + *cached = user; + } +} + +async fn authenticated(state: &Mutex, conn: &Connection) -> Result { + let (cached, _) = session(state)?; let user = user::read(&cached.id, conn).await?; - set_state( - state, - State::Authenticated { - user: user.clone(), - token: token.clone(), - }, - ); + cache_user(state, user.clone()); + + Ok(user) +} - Ok((user, token)) +async fn builder(state: &Mutex, conn: &Connection) -> Result { + let user = authenticated(state, conn).await?; + ensure(permission::is_builder(user.role))?; + + Ok(user) } pub async fn actor_rank( @@ -2146,31 +2009,109 @@ async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result Result<(), Error> { + ensure_with(allowed, CommonError::Forbidden) +} + +pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), Error> { if !allowed { - return Err(CommonError::Forbidden.into()); + return Err(error.into()); } Ok(()) } -fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Vec { - let mut broadcasts = broadcast(event, members); - for broadcast in &mut broadcasts { - if !broadcast.user_ids.iter().any(|id| id == user_id) { - broadcast.user_ids.push(user_id.to_string()); - } +async fn allowed( + me: &User, + community_id: &str, + conn: &Connection, + check: fn(Option) -> bool, +) -> Result<(), Error> { + ensure(check(actor_rank(me, community_id, conn).await?)) +} + +async fn is_outsider(user_id: &str, community_id: &str, conn: &Connection) -> Result { + Ok(user_community::rank(user_id, community_id, conn) + .await? + .is_none()) +} + +async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), Error> { + ensure(!community::is_fixed(community_id, conn).await?) +} + +fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Broadcast { + let mut sent = broadcast(event, members); + if !sent.user_ids.iter().any(|id| id == user_id) { + sent.user_ids.push(user_id.to_string()); + } + + sent +} + +async fn message_broadcast( + message: &Message, + event: fn(Message) -> Event, + actor_id: &str, + conn: &Connection, +) -> Result { + let members = user_community::members(&message.community_id, conn).await?; + + Ok(broadcast_with(event(message.clone()), &members, actor_id)) +} + +fn joined_broadcasts( + community_id: &str, + user_id: &str, + muted: bool, + members: &[Member], +) -> Vec { + let mut broadcasts = vec![broadcast( + Event::VoiceJoined { + community_id: community_id.to_string(), + user_id: user_id.to_string(), + }, + members, + )]; + if muted { + broadcasts.push(broadcast( + Event::VoiceMuted { + user_id: user_id.to_string(), + muted, + }, + members, + )); } + broadcasts } -fn broadcast(event: Event, members: &[Member]) -> Vec { - vec![Broadcast { +async fn record_ghost_voice( + user_id: &str, + community_id: &str, + seconds: u64, + conn: &Connection, +) -> Result<(), Error> { + let community = community::label(community_id, conn).await?; + admin_log::record( + Some(user_id), + None, + Some(&community), + &AdminAction::GhostVoice { seconds }, + conn, + ) + .await?; + + Ok(()) +} + +fn broadcast(event: Event, members: &[Member]) -> Broadcast { + Broadcast { event, user_ids: members .iter() .map(|member| member.user.id.clone()) .collect(), - }] + } } #[cfg(test)] diff --git a/crates/server/src/server_ban.rs b/crates/server/src/server_ban.rs index 4a75e78..96a2e5a 100644 --- a/crates/server/src/server_ban.rs +++ b/crates/server/src/server_ban.rs @@ -4,7 +4,11 @@ use common::{ }; use turso::Connection; -use crate::{database::new_id, error::Error, user}; +use crate::{ + database::{self, new_id}, + error::Error, + user, +}; pub async fn insert( kind: ServerBanKind, @@ -47,17 +51,12 @@ pub async fn list(conn: &Connection) -> Result, Error> { } async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", - (kind.as_str(), value), - ) - .await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let found: i64 = row.get(0)?; + let found = database::scalar_i64( + conn, + "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", + (kind.as_str(), value), + ) + .await?; Ok(found != 0) } diff --git a/crates/server/src/server_settings.rs b/crates/server/src/server_settings.rs index a28d863..594a232 100644 --- a/crates/server/src/server_settings.rs +++ b/crates/server/src/server_settings.rs @@ -3,10 +3,21 @@ use turso::Connection; use crate::error::Error; +const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute"; + +fn assignments() -> String { + COLUMNS + .split(", ") + .enumerate() + .map(|(index, column)| format!("{column} = ?{}", index + 1)) + .collect::>() + .join(", ") +} + pub async fn read(conn: &Connection) -> Result { let mut rows = conn .query( - "SELECT 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 FROM server_settings WHERE id = 1", + &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"), (), ) .await?; @@ -21,6 +32,7 @@ pub async fn read(conn: &Connection) -> Result { let community_quota_bytes: i64 = row.get(5)?; let message_retention_days: i64 = row.get(6)?; let attachment_retention_days: i64 = row.get(7)?; + let announcement: String = row.get(8)?; let max_communities_per_user: i64 = row.get(9)?; let max_message_length: i64 = row.get(10)?; let max_avatar_bytes: i64 = row.get(11)?; @@ -36,7 +48,7 @@ pub async fn read(conn: &Connection) -> Result { community_quota_bytes: community_quota_bytes as u64, message_retention_days: message_retention_days as u32, attachment_retention_days: attachment_retention_days as u32, - announcement: row.get(8)?, + announcement, max_communities_per_user: max_communities_per_user as u32, max_message_length: max_message_length as u32, max_avatar_bytes: max_avatar_bytes as u64, @@ -47,7 +59,7 @@ pub async fn read(conn: &Connection) -> Result { pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), Error> { conn.execute( - "UPDATE server_settings SET name = ?1, registration_open = ?2, max_attachment_bytes = ?3, maintenance = ?4, user_quota_bytes = ?5, community_quota_bytes = ?6, message_retention_days = ?7, attachment_retention_days = ?8, announcement = ?9, max_communities_per_user = ?10, max_message_length = ?11, max_avatar_bytes = ?12, messages_per_minute = ?13, logins_per_minute = ?14 WHERE id = 1", + &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()), ( settings.name.as_str(), i64::from(settings.registration_open), diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs index 012a9d7..08bfdf4 100644 --- a/crates/server/src/stats.rs +++ b/crates/server/src/stats.rs @@ -4,7 +4,7 @@ use common::{ }; use turso::Connection; -use crate::{error::Error, user}; +use crate::{database, error::Error, user}; const MAXIMUM_DAYS: u32 = 90; @@ -53,12 +53,5 @@ pub async fn daily(days: u32, conn: &Connection) -> Result, Error> } async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result { - let mut rows = conn.query(sql, params).await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let value: i64 = row.get(0)?; - - Ok(value as u64) + Ok(database::scalar_i64(conn, sql, params).await? as u64) } diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index 8fa7fbe..b78cae3 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -2,7 +2,7 @@ use common::{ constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, error::{Error as CommonError, InvalidInput}, model::{Account, Presence, Role, User}, - time, + permission, time, validate::{validate_avatar_size, validate_status, validate_username}, }; use image::ImageFormat; @@ -33,45 +33,48 @@ pub fn from_row(row: &Row) -> Result { Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?) } -pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")), - ( - new_id(), - username, - password_hash, - Role::User.as_str(), - Role::Builder.as_str(), - ), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; +pub fn bool_at(row: &Row, index: usize) -> Result { + let flag: i64 = row.get(index)?; - from_row(&row) + Ok(flag != 0) } -pub async fn read(user_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), - (user_id,), - ) - .await?; +async fn one(sql: &str, params: impl turso::IntoParams, conn: &Connection) -> Result { + let mut rows = conn.query(sql, params).await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; from_row(&row) } +pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { + one( + &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")), + ( + new_id(), + username, + password_hash, + Role::User.as_str(), + Role::Builder.as_str(), + ), + conn, + ) + .await +} + +pub async fn read(user_id: &str, conn: &Connection) -> Result { + one( + &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), + (user_id,), + conn, + ) + .await +} + pub async fn any(conn: &Connection) -> Result { let mut rows = conn.query("SELECT EXISTS (SELECT 1 FROM user)", ()).await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let exists: i64 = row.get(0)?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; - Ok(exists != 0) + bool_at(&row, 0) } pub async fn by_username(username: &str, conn: &Connection) -> Result, Error> { @@ -88,6 +91,28 @@ pub async fn by_username(username: &str, conn: &Connection) -> Result, + conn: &Connection, +) -> Result { + Ok(by_username(username, conn) + .await? + .is_some_and(|existing| Some(existing.id.as_str()) != except_id)) +} + +pub async fn by_session_token(token: &str, conn: &Connection) -> Result { + let mut rows = conn + .query( + &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user_columns("user")), + (token,), + ) + .await?; + let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?; + + from_row(&row) +} + pub async fn credentials( username: &str, conn: &Connection, @@ -111,42 +136,33 @@ pub async fn credentials( pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result { validate_username(username)?; - if by_username(username, conn) - .await? - .is_some_and(|existing| existing.id != user_id) - { + if is_taken(username, Some(user_id), conn).await? { return Err(CommonError::Taken.into()); } - let mut rows = conn - .query( - &format!( - "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, username), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) + one( + &format!( + "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), + (user_id, username), + conn, + ) + .await } pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result { validate_status(status)?; - let mut rows = conn - .query( - &format!( - "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, status), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) + one( + &format!( + "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), + (user_id, status), + conn, + ) + .await } pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { @@ -163,29 +179,27 @@ pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { Ok(()) } -pub async fn set_avatar(user_id: &str, bytes: &[u8], conn: &mut Connection) -> Result { - check_avatar(bytes)?; +pub async fn set_avatar( + user_id: &str, + avatar: Option<&[u8]>, + conn: &mut Connection, +) -> Result { + if let Some(bytes) = avatar { + check_avatar(bytes)?; + } - let avatar_id = new_id(); + let avatar_id = avatar.map(|_| new_id()); let tx = conn.transaction().await?; tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,)) .await?; - tx.execute( - "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)", - (avatar_id.as_str(), user_id, bytes), - ) - .await?; - let user = set_avatar_id(user_id, Some(&avatar_id), &tx).await?; - tx.commit().await?; - - Ok(user) -} - -pub async fn remove_avatar(user_id: &str, conn: &mut Connection) -> Result { - let tx = conn.transaction().await?; - tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,)) + if let (Some(avatar_id), Some(bytes)) = (&avatar_id, avatar) { + tx.execute( + "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)", + (avatar_id.as_str(), user_id, bytes), + ) .await?; - let user = set_avatar_id(user_id, None, &tx).await?; + } + let user = set_avatar_id(user_id, avatar_id.as_deref(), &tx).await?; tx.commit().await?; Ok(user) @@ -196,18 +210,15 @@ async fn set_avatar_id( avatar_id: Option<&str>, conn: &Connection, ) -> Result { - let mut rows = conn - .query( - &format!( - "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, avatar_id), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) + one( + &format!( + "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), + (user_id, avatar_id), + conn, + ) + .await } pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error> { @@ -222,34 +233,16 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error Ok(row.get(0)?) } -pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!( - "UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}", - user_columns("user") - ), - (username, role.as_str()), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) -} - pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!( - "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, role.as_str()), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) + one( + &format!( + "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), + (user_id, role.as_str()), + conn, + ) + .await } pub async fn suspended(user_id: &str, conn: &Connection) -> Result { @@ -260,10 +253,9 @@ pub async fn suspended(user_id: &str, conn: &Connection) -> Result ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let flag: i64 = row.get(0)?; let until: Option = row.get(1)?; - Ok(flag != 0 || until.is_some_and(|until| until as u64 > time::now_ms())) + Ok(bool_at(&row, 0)? || until.is_some_and(|until| until as u64 > time::now_ms())) } pub async fn set_timeout( @@ -348,9 +340,8 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { let Some(row) = rows.next().await? else { return Ok(false); }; - let flag: i64 = row.get(0)?; - Ok(flag != 0) + bool_at(&row, 0) } pub async fn presence(user_id: &str, conn: &Connection) -> Result { @@ -380,14 +371,15 @@ pub async fn update_presence( pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "SELECT voice_muted AND role != ?2 FROM user WHERE id = ?1", - (user_id, Role::Builder.as_str()), + "SELECT voice_muted, role FROM user WHERE id = ?1", + (user_id,), ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let muted: i64 = row.get(0)?; + let role: String = row.get(1)?; + let builder = Role::parse(&role).is_some_and(permission::is_builder); - Ok(muted != 0) + Ok(bool_at(&row, 0)? && !builder) } pub async fn set_password_hash( @@ -413,16 +405,14 @@ pub async fn all(conn: &Connection) -> Result, Error> { .await?; let mut accounts = Vec::new(); while let Some(row) = rows.next().await? { - let flag: i64 = row.get(5)?; let last_seen: Option = row.get(6)?; let suspended_until: Option = row.get(7)?; - let ghost: i64 = row.get(8)?; accounts.push(Account { user: from_row(&row)?, - suspended: flag != 0, + suspended: bool_at(&row, 5)?, last_seen: last_seen.map(|millis| millis as u64), suspended_until: suspended_until.map(|millis| millis as u64), - ghost: ghost != 0, + ghost: bool_at(&row, 8)?, }); } @@ -430,18 +420,15 @@ pub async fn all(conn: &Connection) -> Result, Error> { } pub async fn delete(user_id: &str, conn: &Connection) -> Result { - let mut rows = conn - .query( - &format!( - "DELETE FROM user WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id,), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - - from_row(&row) + one( + &format!( + "DELETE FROM user WHERE id = ?1 RETURNING {}", + user_columns("user") + ), + (user_id,), + conn, + ) + .await } #[cfg(test)] @@ -468,9 +455,9 @@ mod tests { let mut conn = database::connect(&db).await.unwrap(); let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); - let small = user::set_avatar(&created_user.id, &jpeg(AVATAR_SIZE / 2), &mut conn).await; - let not_jpeg = user::set_avatar(&created_user.id, b"not a jpeg", &mut conn).await; - let valid = user::set_avatar(&created_user.id, &jpeg(AVATAR_SIZE), &mut conn) + let small = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await; + let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await; + let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn) .await .unwrap(); diff --git a/crates/server/src/voice.rs b/crates/server/src/voice.rs index 2e9cce8..063cd3a 100644 --- a/crates/server/src/voice.rs +++ b/crates/server/src/voice.rs @@ -25,12 +25,6 @@ pub enum CallEnd { Declined, } -pub struct GhostChange { - pub community_id: String, - pub ghost_seconds: Option, - pub call: Option, -} - pub struct Left { pub community_id: String, pub user_id: String, @@ -38,11 +32,16 @@ pub struct Left { pub call: Option, } +enum Outcome { + Ringing, + Declined, + Answered, +} + struct Room { participants: Vec, started_ms: u64, - answered: bool, - declined: bool, + outcome: Outcome, } impl Room { @@ -50,8 +49,7 @@ impl Room { Self { participants: Vec::new(), started_ms: time::now_ms(), - answered: false, - declined: false, + outcome: Outcome::Ringing, } } @@ -63,23 +61,20 @@ impl Room { fn admit(&mut self) { if self.occupied() { - self.answered = true; + self.outcome = Outcome::Answered; } else { self.started_ms = time::now_ms(); - self.answered = false; - self.declined = false; + self.outcome = Outcome::Ringing; } } fn end(&self) -> CallEnd { - if self.answered { - CallEnd::Answered { + match self.outcome { + Outcome::Answered => CallEnd::Answered { seconds: time::now_ms().saturating_sub(self.started_ms) / 1000, - } - } else if self.declined { - CallEnd::Declined - } else { - CallEnd::Unanswered + }, + Outcome::Declined => CallEnd::Declined, + Outcome::Ringing => CallEnd::Unanswered, } } } @@ -118,60 +113,45 @@ impl Voice { } pub fn decline(&self, community_id: &str) { - if let Some(room) = self.0.lock().unwrap().get_mut(community_id) { - room.declined = true; + if let Some(room) = self.0.lock().unwrap().get_mut(community_id) + && matches!(room.outcome, Outcome::Ringing) + { + room.outcome = Outcome::Declined; } } pub fn set_muted(&self, user_id: &str, muted: bool) -> Option { let mut rooms = self.0.lock().unwrap(); - for (community_id, room) in rooms.iter_mut() { - if let Some(participant) = room - .participants - .iter_mut() - .find(|participant| participant.user_id == user_id) - { - participant.muted = muted; - - return Some(community_id.clone()); - } - } + let (community_id, index) = locate(&rooms, user_id)?; + rooms.get_mut(&community_id)?.participants[index].muted = muted; - None + Some(community_id) } - pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { + pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { let mut rooms = self.0.lock().unwrap(); - for (community_id, room) in rooms.iter_mut() { - let Some(index) = room - .participants - .iter() - .position(|participant| participant.user_id == user_id) - else { - continue; - }; - if room.participants[index].ghost == ghost { - return None; - } - if !ghost { - room.admit(); - } - let participant = &mut room.participants[index]; - let seconds = participant - .ghost - .then(|| participant.joined_at.elapsed().as_secs()); - participant.ghost = ghost; - participant.joined_at = Instant::now(); - let call = (ghost && !room.occupied()).then(|| room.end()); - - return Some(GhostChange { - community_id: community_id.clone(), - ghost_seconds: seconds, - call, - }); + let (community_id, index) = locate(&rooms, user_id)?; + let room = rooms.get_mut(&community_id)?; + if room.participants[index].ghost == ghost { + return None; } + if !ghost { + room.admit(); + } + let participant = &mut room.participants[index]; + let seconds = participant + .ghost + .then(|| participant.joined_at.elapsed().as_secs()); + participant.ghost = ghost; + participant.joined_at = Instant::now(); + let call = (ghost && !room.occupied()).then(|| room.end()); - None + Some(Left { + community_id, + user_id: user_id.to_string(), + ghost_seconds: seconds, + call, + }) } pub fn room_users(&self, community_id: &str) -> Vec { @@ -189,16 +169,7 @@ impl Voice { } pub fn room_of(&self, user_id: &str) -> Option { - self.0 - .lock() - .unwrap() - .iter() - .find(|(_, room)| { - room.participants - .iter() - .any(|participant| participant.user_id == user_id) - }) - .map(|(community_id, _)| community_id.clone()) + locate(&self.0.lock().unwrap(), user_id).map(|(community_id, _)| community_id) } pub fn leave(&self, user_id: &str) -> Option { @@ -342,15 +313,17 @@ fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option Some(left(community_id, participant, call)) } +fn locate(rooms: &Rooms, user_id: &str) -> Option<(String, usize)> { + rooms.iter().find_map(|(community_id, room)| { + room.participants + .iter() + .position(|participant| participant.user_id == user_id) + .map(|index| (community_id.clone(), index)) + }) +} + fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option { - let community_id = rooms - .iter() - .find(|(_, room)| { - room.participants - .iter() - .any(|participant| participant.user_id == user_id) - }) - .map(|(community_id, _)| community_id.clone())?; + let (community_id, _) = locate(rooms, user_id)?; remove(rooms, &community_id, user_id) }