From d58bc1979903a6140f9cfbc1232fc118714e2cf0 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 20:01:27 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20simplify=20the?= =?UTF-8?q?=20whole=20workspace=20and=20fix=20the=20bugs=20found=20on=20th?= =?UTF-8?q?e=20way?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collapse duplicated helpers across client, server and common: one gui widget module, one capture worker type, shared db query helpers, one name validator. Gate the capture modules behind a stub so macOS compiles again, close the portal screencast session on stop, stop camera read spins, stop double WatchShare requests, fix frame pacing jitter drops, mention prefix matching, validation holes and a set of server cleanup and auth gaps. --- crates/client/Cargo.toml | 10 +- crates/client/src/accounts.rs | 26 +- crates/client/src/gui.rs | 2 + crates/client/src/gui/auth.rs | 49 +- crates/client/src/gui/builder.rs | 39 +- crates/client/src/gui/builder/access.rs | 32 +- crates/client/src/gui/builder/backups.rs | 21 +- crates/client/src/gui/builder/communities.rs | 13 +- crates/client/src/gui/builder/log.rs | 62 +- crates/client/src/gui/builder/messages.rs | 34 +- crates/client/src/gui/builder/reports.rs | 55 +- crates/client/src/gui/builder/server.rs | 45 +- crates/client/src/gui/builder/storage.rs | 41 +- crates/client/src/gui/builder/ui.rs | 43 +- crates/client/src/gui/builder/users.rs | 18 +- crates/client/src/gui/camera_view.rs | 54 +- crates/client/src/gui/chat.rs | 293 +++--- crates/client/src/gui/community_settings.rs | 121 +-- crates/client/src/gui/composer.rs | 219 +++-- crates/client/src/gui/forward.rs | 19 +- crates/client/src/gui/media_view.rs | 2 +- crates/client/src/gui/message_actions.rs | 224 ++--- crates/client/src/gui/poll.rs | 57 +- crates/client/src/gui/profile.rs | 40 +- crates/client/src/gui/settings_page.rs | 92 +- crates/client/src/gui/share_view.rs | 89 +- crates/client/src/gui/sidebar.rs | 208 ++--- crates/client/src/gui/snippet.rs | 15 +- crates/client/src/gui/social.rs | 49 +- crates/client/src/gui/voice_note.rs | 34 +- crates/client/src/gui/widget.rs | 116 +++ crates/client/src/lib.rs | 29 +- crates/client/src/main.rs | 6 +- crates/client/src/media/decode.rs | 112 +-- crates/client/src/media/meter.rs | 17 +- crates/client/src/media/mod.rs | 12 +- crates/client/src/media/resample.rs | 11 +- crates/client/src/media/voice_note.rs | 10 +- crates/client/src/mutes.rs | 24 +- crates/client/src/network.rs | 882 ++++++++---------- crates/client/src/settings.rs | 66 +- crates/client/src/share/audio_capture.rs | 65 +- .../client/src/share/audio_capture_windows.rs | 52 +- crates/client/src/share/camera.rs | 24 +- crates/client/src/share/capture.rs | 76 +- crates/client/src/share/capture_windows.rs | 10 +- crates/client/src/share/convert.rs | 13 - crates/client/src/share/encode.rs | 21 +- crates/client/src/share/frame.rs | 12 + crates/client/src/share/mod.rs | 5 +- crates/client/src/share/reassembly.rs | 8 +- crates/client/src/share/session.rs | 117 +-- crates/client/src/share/unsupported.rs | 52 ++ crates/client/src/tray.rs | 308 +++--- crates/client/src/voice/audio.rs | 21 +- crates/client/src/voice/audio/coreaudio.rs | 84 +- crates/client/src/voice/audio/pipewire.rs | 125 ++- crates/client/src/voice/audio/wasapi.rs | 77 +- crates/client/src/voice/engine.rs | 4 +- crates/client/src/voice/mod.rs | 43 +- crates/common/src/error.rs | 30 +- crates/common/src/model.rs | 10 +- crates/common/src/network.rs | 41 +- crates/common/src/share.rs | 20 - crates/common/src/time.rs | 2 +- crates/common/src/validate.rs | 69 +- crates/pixel/src/lib.rs | 24 +- crates/server/src/attachment.rs | 75 +- crates/server/src/authentication.rs | 6 +- crates/server/src/backup.rs | 24 +- crates/server/src/certificate.rs | 10 +- crates/server/src/community.rs | 39 +- crates/server/src/database.rs | 41 +- crates/server/src/direct.rs | 2 +- crates/server/src/error.rs | 2 - crates/server/src/friend.rs | 4 +- crates/server/src/invitation.rs | 8 +- crates/server/src/invite.rs | 12 +- crates/server/src/lib.rs | 8 +- crates/server/src/message.rs | 45 +- crates/server/src/network.rs | 111 ++- crates/server/src/notes.rs | 2 +- crates/server/src/overview.rs | 4 +- crates/server/src/report.rs | 6 +- crates/server/src/request.rs | 44 +- crates/server/src/server_ban.rs | 10 +- crates/server/src/server_settings.rs | 42 +- crates/server/src/share.rs | 45 +- crates/server/src/user.rs | 148 +-- crates/server/src/user_community.rs | 88 +- crates/server/src/voice.rs | 68 +- crates/spectrum/src/lib.rs | 10 +- 92 files changed, 2554 insertions(+), 2904 deletions(-) create mode 100644 crates/client/src/gui/widget.rs delete mode 100644 crates/client/src/share/convert.rs create mode 100644 crates/client/src/share/unsupported.rs diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index a76de1b..ddc6b03 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -15,14 +15,9 @@ gpui-kit = { version = "0.11.0", features = ["syntect"] } ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } -ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } -ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } -ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } -ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } -ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } @@ -32,13 +27,14 @@ ureq = "3.5.2" bytes = "1.12.2" tracing = "0.1.44" tracing-subscriber = "0.3.23" -uuid = "1.29.3" jiff = "1.0.2" dirs = "7.0.0" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } -nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } rtrb = "0.4.1" +[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] +nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } + [target.'cfg(target_os = "linux")'.dependencies] pipewire = { version = "0.10.1", features = ["v0_3_49"] } ksni = "0.3.7" diff --git a/crates/client/src/accounts.rs b/crates/client/src/accounts.rs index 2f6e66b..a113fee 100644 --- a/crates/client/src/accounts.rs +++ b/crates/client/src/accounts.rs @@ -1,9 +1,6 @@ -use std::{fs, path::PathBuf}; - use common::model::User; -use tracing::warn; -use crate::config_file; +use crate::{read_config, write_config}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Account { @@ -70,8 +67,7 @@ impl Accounts { } pub fn load() -> Accounts { - let Some(content) = config_file("accounts").and_then(|path| fs::read_to_string(path).ok()) - else { + let Some(content) = read_config("accounts") else { return Accounts::default(); }; let mut accounts = Accounts::default(); @@ -92,9 +88,6 @@ pub fn load() -> Accounts { } fn save(accounts: &Accounts) { - let Some(path) = config_file("accounts") else { - return; - }; let mut content: String = accounts .list .iter() @@ -109,18 +102,5 @@ fn save(accounts: &Accounts) { content.push_str(&format!("active\t{active}\n")); } - if let Err(error) = write_private(&path, &content) { - warn!("save accounts failed: {error}"); - } -} - -fn write_private(path: &PathBuf, content: &str) -> std::io::Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - let mut options = fs::OpenOptions::new(); - options.write(true).create(true).truncate(true); - #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); - std::io::Write::write_all(&mut options.open(path)?, content.as_bytes()) + write_config("accounts", &content); } diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 854ea0e..c8f78b0 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -61,6 +61,7 @@ mod voice_note; mod voice_settings; mod voice_stats; mod wave; +mod widget; use auth::Auth; use chat::{Chat, View}; @@ -1076,6 +1077,7 @@ impl Yumush { fn end_session(&mut self, window: &mut Window, cx: &mut Context) { self.end_voice(cx); self.leave_settings(); + self.stop_playing(cx); self.user = None; self.chat.reset(); self.change_page(Route::Login, window, cx); diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index 061929f..84f8b4f 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -1,19 +1,20 @@ -use super::{ - Tooltip as _, - settings_page::{segment, segment_track}, - text, -}; use gpui_kit::{ - Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, - component::input::{Input, InputEvent, InputState}, + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, + StatefulInteractiveElement, Styled, Window, + assets::IconName, + component::{ + Icon, + input::{Input, InputEvent, InputState}, + }, div, px, }; -use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon}; - -use crate::gui::{ - Palette, Route, Yumush, badge, clickable, connection_notice, hoverable, new_input, - notify_error, palette, primary_button, +use super::{ + Palette, Route, Tooltip as _, Yumush, badge, clickable, connection_notice, hoverable, + new_input, notify_error, palette, primary_button, + settings_page::{segment, segment_track}, + text, + widget::{field, frame}, }; pub struct Auth { @@ -87,32 +88,10 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { .detach(); } -pub(super) fn field(palette: Palette, input: &Entity) -> Div { - frame(palette, Input::new(input)) -} - fn password_field(palette: Palette, input: &Entity) -> Div { frame(palette, Input::new(input).mask_toggle()) } -fn frame(palette: Palette, input: Input) -> Div { - div() - .h(px(32.)) - .flex() - .items_center() - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.field) - .child( - input - .appearance(false) - .text_color(palette.text) - .flex_1() - .min_w_0(), - ) -} - impl Yumush { pub(super) fn auth_page(&self, route: Route, cx: &mut Context) -> impl IntoElement { let palette = palette(cx); @@ -183,9 +162,7 @@ impl Yumush { .children(connection_notice(&self.connection, palette)), ) } -} -impl Yumush { fn saved_accounts(&self, entity: &Entity, palette: Palette) -> Option
{ if self.accounts.list.is_empty() { return None; diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index d3b66da..8e0d36b 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -11,7 +11,7 @@ mod ui; mod users; mod voice; -use std::{fmt::Display, future::Future}; +use std::{fmt::Display, future::Future, path::PathBuf}; use common::{ model::{CommunityKind, Member, Role}, @@ -21,7 +21,7 @@ use gpui_kit::{ AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Window, assets::IconName, - component::{Icon, switch::Switch}, + component::{Icon, input::InputState, switch::Switch}, div, prelude::FluentBuilder as _, px, @@ -30,10 +30,14 @@ use gpui_kit::{ use self::ui::{accent_button, icon_button, page_heading, plain_button}; use super::{ Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, - text, + text, widget::search_text, }; use crate::network::NetworkHandle; +pub(super) fn save_directory() -> PathBuf { + dirs::download_dir().unwrap_or_else(std::env::temp_dir) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum BuilderTab { Overview, @@ -304,7 +308,10 @@ impl Yumush { BuilderTab::Overview => self.load_overview(window, cx), BuilderTab::Users => self.load_users(window, cx), BuilderTab::Communities => self.load_builder_communities(window, cx), - BuilderTab::Messages => {} + BuilderTab::Messages => { + self.load_users(window, cx); + self.load_builder_communities(window, cx); + } BuilderTab::Storage => { self.load_users(window, cx); self.load_builder_communities(window, cx); @@ -416,6 +423,30 @@ impl Yumush { .map(|summary| summary.community.id.clone()) } + pub(super) fn filter_user( + &self, + input: &Entity, + cx: &App, + ) -> Option> { + let name = search_text(input, cx); + if name.is_empty() { + return Some(None); + } + self.resolve_user(&name).map(Some) + } + + pub(super) fn filter_community( + &self, + input: &Entity, + cx: &App, + ) -> Option> { + let name = search_text(input, cx); + if name.is_empty() { + return Some(None); + } + self.resolve_community(&name).map(Some) + } + fn set_ghost_state(&mut self, ghost: bool) { self.chat.ghost = ghost; let Some(me) = self.user.as_ref() else { diff --git a/crates/client/src/gui/builder/access.rs b/crates/client/src/gui/builder/access.rs index b138909..7dae9ec 100644 --- a/crates/client/src/gui/builder/access.rs +++ b/crates/client/src/gui/builder/access.rs @@ -4,9 +4,12 @@ use gpui_kit::{ Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px, }; -use super::ui::{accent_button, card, card_header, icon_button, pill, toolbar}; +use super::ui::{ + accent_button, card, card_header, confirmed, delete_icon_button, fixed, icon_button, pill, + toolbar, +}; use crate::gui::STAMP; -use crate::gui::{Palette, Yumush, auth::field, entity_action, millis_time, notify_error, text}; +use crate::gui::{Palette, Yumush, entity_action, millis_time, notify_error, text, widget::field}; fn list_card(header: Div, rows: Vec
, empty: &str, palette: Palette) -> Div { let body = if rows.is_empty() { @@ -43,11 +46,6 @@ fn invite_row( || "never".to_string(), |at| format!("expires {}", millis_time(at, STAMP)), ); - let (delete_icon, delete_tip, delete_color) = if pending { - (IconName::Check, "Confirm", palette.on_accent) - } else { - (IconName::Trash, "Delete", palette.danger) - }; div() .min_h(px(44.)) @@ -90,11 +88,9 @@ fn invite_row( yumush.copy_invite(©_code, cx) }), )) - .child(icon_button( + .child(delete_icon_button( format!("delete_invite_{}", invite.code), - delete_icon, - delete_tip, - delete_color, + pending, palette, entity_action(entity, move |yumush, window, cx| { yumush.delete_invite(&delete_code, window, cx) @@ -212,12 +208,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_invite_delete.as_deref() != Some(code) { - self.chat.pending_invite_delete = Some(code.to_string()); + if !confirmed(&mut self.chat.pending_invite_delete, code) { cx.notify(); return; } - self.chat.pending_invite_delete = None; let network = self.network.clone(); let code = code.to_string(); @@ -255,14 +249,8 @@ impl Yumush { pub(super) fn access_body(&self, entity: &Entity, palette: Palette) -> Vec { let controls = toolbar(vec![ - div() - .w(px(80.)) - .child(field(palette, &self.chat.invite_uses)) - .into_any_element(), - div() - .w(px(90.)) - .child(field(palette, &self.chat.invite_hours)) - .into_any_element(), + fixed(80., field(palette, &self.chat.invite_uses)), + fixed(90., field(palette, &self.chat.invite_hours)), accent_button( "create_invite", "Create", diff --git a/crates/client/src/gui/builder/backups.rs b/crates/client/src/gui/builder/backups.rs index d454abb..d1550d9 100644 --- a/crates/client/src/gui/builder/backups.rs +++ b/crates/client/src/gui/builder/backups.rs @@ -4,7 +4,10 @@ use gpui_kit::{ component::Icon, div, prelude::FluentBuilder as _, px, }; -use super::ui::{accent_button, card, card_header, delete_icon_button, icon_button, list_row}; +use super::{ + save_directory, + ui::{accent_button, card, card_header, confirmed, 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 { @@ -139,12 +142,10 @@ impl Yumush { } fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context) { - if self.pending_backup_delete.as_deref() != Some(name) { - self.pending_backup_delete = Some(name.to_string()); + if !confirmed(&mut self.pending_backup_delete, name) { cx.notify(); return; } - self.pending_backup_delete = None; let network = self.network.clone(); let name = name.to_string(); @@ -161,14 +162,18 @@ impl Yumush { } fn export_backup(&self, name: &str, window: &mut Window, cx: &mut Context) { - let directory = dirs::download_dir().unwrap_or_else(std::env::temp_dir); - let target = cx.prompt_for_new_path(&directory, Some(name)); + let target = cx.prompt_for_new_path(&save_directory(), Some(name)); let network = self.network.clone(); let name = name.to_string(); cx.spawn_in(window, async move |this, cx| { - let Ok(Ok(Some(target))) = target.await else { - return; + let target = match target.await { + Ok(Ok(Some(target))) => target, + Ok(Err(error)) => { + notify_error(&this, cx, error); + return; + } + _ => return, }; if let Err(error) = network.download_backup(&name, target).await { notify_error(&this, cx, error); diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs index 35ac6b8..7f3cd4d 100644 --- a/crates/client/src/gui/builder/communities.rs +++ b/crates/client/src/gui/builder/communities.rs @@ -6,11 +6,11 @@ use gpui_kit::{ use super::{ Transfer, - ui::{card, icon_button, pill, plain_button, rows_body}, + ui::{card, confirmed, 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, + Palette, Yumush, avatar, chat::View, community_icon, entity_action, notify_error, + profile::user_link, text, widget::search_text, }; impl Yumush { @@ -63,12 +63,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_community_delete.as_deref() != Some(community_id) { - self.chat.pending_community_delete = Some(community_id.to_string()); + if !confirmed(&mut self.chat.pending_community_delete, community_id) { cx.notify(); return; } - self.chat.pending_community_delete = None; let network = self.network.clone(); let community_id = community_id.to_string(); @@ -171,8 +169,7 @@ impl Yumush { let Some(transfer) = self.chat.transfer.as_mut() else { return; }; - if transfer.pending.as_deref() != Some(user_id) { - transfer.pending = Some(user_id.to_string()); + if !confirmed(&mut transfer.pending, user_id) { window.refresh(); cx.notify(); return; diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index 6ee1ea7..426ed09 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -3,22 +3,25 @@ use common::{ time::{created_at_ms, now_ms}, }; use gpui_kit::{ - AnyElement, App, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, + AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, - component::{Icon, WindowExt, input::InputState, notification::Notification, select::Select}, + component::{Icon, WindowExt, notification::Notification, select::Select}, div, prelude::FluentBuilder as _, px, }; use jiff::Timestamp; -use super::ui::{accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar}; +use super::{ + save_directory, + ui::{accent_button, card, end_of_day_ms, fixed, list_row, pill, start_of_day_ms, toolbar}, +}; use crate::gui::STAMP; use crate::gui::{ Palette, Yumush, - auth::field, - community_settings::{search_text, user_name}, - entity_action, id_time, millis_time, text, + community_settings::user_name, + entity_action, id_time, millis_time, notify_error, text, + widget::{field, search_text}, }; fn builder_log_text(entry: &AdminLogEntry) -> String { @@ -155,14 +158,6 @@ fn action_icon(action: &AdminAction) -> IconName { } } -fn fixed(width: f32, control: impl IntoElement) -> AnyElement { - div() - .w(px(width)) - .flex_shrink_0() - .child(control) - .into_any_element() -} - fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { list_row() .child( @@ -206,8 +201,8 @@ impl Yumush { return; } let (Some(actor_id), Some(target_id)) = ( - self.log_user(&self.chat.builder_log_actor, cx), - self.log_user(&self.chat.builder_log_target, cx), + self.filter_user(&self.chat.builder_log_actor, cx), + self.filter_user(&self.chat.builder_log_target, cx), ) else { window.push_notification(Notification::error("Unknown user"), cx); return; @@ -237,31 +232,28 @@ impl Yumush { ); } - pub(super) fn log_user(&self, input: &Entity, cx: &App) -> Option> { - let name = search_text(input, cx); - if name.is_empty() { - return Some(None); - } - - self.resolve_user(&name).map(Some) - } - pub(super) fn export_builder_log(&self, window: &mut Window, cx: &mut Context) { - let Some(directory) = dirs::download_dir() else { - window.push_notification(Notification::error("No download folder"), cx); - return; - }; let name = format!( "yumush-admin-log-{}.csv", millis_time(now_ms(), "%Y%m%d-%H%M%S") ); - let path = directory.join(name); - match std::fs::write(&path, builder_log_csv(&self.chat.builder_logs)) { - Ok(()) => { - window.push_notification(Notification::success(path.display().to_string()), cx) + let target = cx.prompt_for_new_path(&save_directory(), Some(&name)); + let csv = builder_log_csv(&self.chat.builder_logs); + + cx.spawn_in(window, async move |this, cx| { + let target = match target.await { + Ok(Ok(Some(target))) => target, + Ok(Err(error)) => { + notify_error(&this, cx, error); + return; + } + _ => return, + }; + if let Err(error) = std::fs::write(target, csv) { + notify_error(&this, cx, error); } - Err(error) => window.push_notification(Notification::error(error.to_string()), cx), - } + }) + .detach(); } pub(super) fn log_body(&self, entity: &Entity, palette: Palette) -> Vec { diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs index 040c227..4a3ae8f 100644 --- a/crates/client/src/gui/builder/messages.rs +++ b/crates/client/src/gui/builder/messages.rs @@ -1,22 +1,25 @@ use common::model::MessageHit; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, - assets::IconName, div, prelude::FluentBuilder as _, px, + assets::IconName, + component::{WindowExt, notification::Notification}, + div, + prelude::FluentBuilder as _, + px, }; use super::ui::{ - accent_button, card, delete_icon_button, end_of_day_ms, icon_button, list_card, list_row, - start_of_day_ms, + accent_button, card, confirmed, 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, - auth::field, - avatar, - community_settings::{search_text, user_name}, + Palette, Yumush, avatar, + community_settings::user_name, entity_action, id_time, notify_error, profile::user_link, text, + widget::{field, search_text}, }; fn message_hit_row( @@ -205,10 +208,15 @@ impl Yumush { pub(super) fn search_messages(&mut self, window: &mut Window, cx: &mut Context) { let text = search_text(&self.chat.builder_message_text, cx); - let username = search_text(&self.chat.builder_message_user, cx); - 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 Some(user_id) = self.filter_user(&self.chat.builder_message_user, cx) else { + window.push_notification(Notification::error("Unknown user"), cx); + return; + }; + let Some(community_id) = self.filter_community(&self.chat.builder_message_community, cx) + else { + window.push_notification(Notification::error("Unknown community"), cx); + return; + }; 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); @@ -240,12 +248,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_message_delete.as_deref() != Some(message_id) { - self.chat.pending_message_delete = Some(message_id.to_string()); + if !confirmed(&mut self.chat.pending_message_delete, message_id) { cx.notify(); return; } - self.chat.pending_message_delete = None; let network = self.network.clone(); let message_id = message_id.to_string(); diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index be11390..3df4a00 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -23,21 +23,13 @@ use crate::{ network::NetworkHandle, }; -const REPORT_FILTERS: [(Option, &str); 4] = [ - (Some(ReportStatus::Open), "Open"), - (Some(ReportStatus::Resolved), "Resolved"), - (Some(ReportStatus::Dismissed), "Dismissed"), - (None, "All"), +const REPORT_FILTERS: [Option; 4] = [ + Some(ReportStatus::Open), + Some(ReportStatus::Resolved), + Some(ReportStatus::Dismissed), + None, ]; -fn status_label(status: ReportStatus) -> &'static str { - match status { - ReportStatus::Open => "Open", - ReportStatus::Resolved => "Resolved", - ReportStatus::Dismissed => "Dismissed", - } -} - fn status_color(status: ReportStatus, palette: Palette) -> Hsla { match status { ReportStatus::Open => palette.accent, @@ -166,25 +158,24 @@ impl Yumush { } pub(super) fn report_filters(&self, entity: &Entity, palette: Palette) -> Div { - div() - .flex() - .child( - segment_track(palette).children(REPORT_FILTERS.map(|(status, label)| { - segment( - clickable( - label, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.select_report_filter(status, window, cx) - }), - ), - self.chat.report_filter == status, + div().flex().child( + segment_track(palette).children(REPORT_FILTERS.map(|status| { + let label = status.map_or("All", ReportStatus::label); + segment( + clickable( + label, palette, - ) - .px(px(10.)) - .child(label) - })), - ) + entity_action(entity, move |yumush, window, cx| { + yumush.select_report_filter(status, window, cx) + }), + ), + self.chat.report_filter == status, + palette, + ) + .px(px(10.)) + .child(label) + })), + ) } pub(super) fn reports_body(&self, entity: &Entity, palette: Palette) -> Vec { @@ -236,7 +227,7 @@ impl Yumush { ), )) .child(pill( - status_label(report.status), + report.status.label(), status_color(report.status, palette), palette, )) diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs index cb420a5..be5bb8d 100644 --- a/crates/client/src/gui/builder/server.rs +++ b/crates/client/src/gui/builder/server.rs @@ -1,19 +1,24 @@ use common::model::ServerSettings; use gpui_kit::{ - AnyElement, App, Context, Entity, IntoElement, Window, component::input::InputState, + AnyElement, App, Context, Entity, IntoElement, Window, + component::{WindowExt, input::InputState, notification::Notification}, }; 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::{KB, MB, Palette, Yumush, notify_error, settings_page::segmented, widget::field}; fn input_text(input: &Entity, cx: &App) -> String { input.read(cx).text().to_string() } -fn input_number(input: &Entity, cx: &App) -> u32 { +fn input_number(input: &Entity, cx: &App) -> Option { number(&input_text(input, cx)) } +fn input_bytes(input: &Entity, unit: u64, cx: &App) -> Option { + to_bytes(&input_text(input, cx), unit) +} + fn set_input(input: &Entity, text: &str, window: &mut Window, cx: &mut App) { input.update(cx, |input, cx| input.set_value(text, window, cx)); } @@ -95,26 +100,30 @@ impl Yumush { ); } - pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context) { + fn server_form(&self, cx: &App) -> Option { let chat = &self.chat; - let settings = ServerSettings { + Some(ServerSettings { 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), + max_attachment_bytes: input_bytes(&chat.server_limit, MB as u64, cx)?, 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), + user_quota_bytes: input_bytes(&chat.server_user_quota, MB as u64, cx)?, + community_quota_bytes: input_bytes(&chat.server_community_quota, MB as u64, cx)?, + 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), + 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: input_bytes(&chat.server_max_avatar, KB as u64, cx)?, + messages_per_minute: input_number(&chat.server_messages_per_minute, cx)?, + logins_per_minute: input_number(&chat.server_logins_per_minute, cx)?, + }) + } + + pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context) { + let Some(settings) = self.server_form(cx) else { + window.push_notification(Notification::error("Invalid number"), cx); + return; }; let network = self.network.clone(); diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index 74885b4..274bdb1 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -1,23 +1,22 @@ use common::model::AttachmentInfo; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, - assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, + assets::IconName, + component::{Icon, WindowExt, notification::Notification}, + div, + prelude::FluentBuilder as _, + px, relative, }; use super::ui::{ - accent_button, card, card_header, delete_icon_button, list_card, list_row, toolbar, + accent_button, card, card_header, confirmed, delete_icon_button, fixed, list_card, list_row, + toolbar, }; use crate::gui::{ - DATE, Palette, Yumush, - auth::field, - community_settings::{search_text, user_name}, - entity_action, id_time, notify_error, storage, text, + DATE, Palette, Yumush, community_settings::user_name, entity_action, id_time, notify_error, + storage, text, widget::field, }; -fn fixed(width: f32, control: impl IntoElement) -> Div { - div().w(px(width)).flex_shrink_0().child(control) -} - fn share(bytes: u64, max: u64) -> f32 { if max == 0 { 0. @@ -197,12 +196,11 @@ impl Yumush { )); let controls = toolbar(vec![ - fixed(160., field(palette, &self.chat.builder_attachment_user)).into_any_element(), + fixed(160., field(palette, &self.chat.builder_attachment_user)), fixed( 160., field(palette, &self.chat.builder_attachment_community), - ) - .into_any_element(), + ), accent_button( "search_attachments", "Search", @@ -272,10 +270,15 @@ impl Yumush { } pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context) { - let username = search_text(&self.chat.builder_attachment_user, cx); - let community = search_text(&self.chat.builder_attachment_community, cx); - let user_id = self.resolve_user(&username); - let community_id = self.resolve_community(&community); + let Some(user_id) = self.filter_user(&self.chat.builder_attachment_user, cx) else { + window.push_notification(Notification::error("Unknown user"), cx); + return; + }; + let Some(community_id) = self.filter_community(&self.chat.builder_attachment_community, cx) + else { + window.push_notification(Notification::error("Unknown community"), cx); + return; + }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { @@ -301,12 +304,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_attachment_delete.as_deref() != Some(attachment_id) { - self.chat.pending_attachment_delete = Some(attachment_id.to_string()); + if !confirmed(&mut self.chat.pending_attachment_delete, attachment_id) { cx.notify(); return; } - self.chat.pending_attachment_delete = None; let network = self.network.clone(); let attachment_id = attachment_id.to_string(); diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs index 49b3806..89140c7 100644 --- a/crates/client/src/gui/builder/ui.rs +++ b/crates/client/src/gui/builder/ui.rs @@ -1,24 +1,38 @@ -use crate::gui::{Palette, Tooltip as _, clickable, primary_button, text}; +use crate::gui::{Palette, Tooltip as _, clickable, primary_button, text, widget}; 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 to_bytes(text: &str, unit: u64) -> u64 { - text.trim() - .parse::() - .ok() - .and_then(|units| units.checked_mul(unit)) - .unwrap_or(0) +pub(super) fn to_bytes(text: &str, unit: u64) -> Option { + text.trim().parse::().ok()?.checked_mul(unit) } pub(super) fn to_units(bytes: u64, unit: u64) -> String { (bytes / unit).to_string() } -pub(super) fn number(text: &str) -> u32 { - text.trim().parse().unwrap_or(0) +pub(super) fn confirmed(pending: &mut Option, id: &str) -> bool { + if pending.as_deref() == Some(id) { + *pending = None; + true + } else { + *pending = Some(id.to_string()); + false + } +} + +pub(super) fn fixed(width: f32, control: impl IntoElement) -> AnyElement { + div() + .w(px(width)) + .flex_shrink_0() + .child(control) + .into_any_element() +} + +pub(super) fn number(text: &str) -> Option { + text.trim().parse().ok() } pub(super) fn icon_button( @@ -29,16 +43,7 @@ pub(super) fn icon_button( palette: Palette, action: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - clickable(id, palette, action) - .tip(tip) - .size(px(26.)) - .flex_shrink_0() - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(color) - .child(Icon::new(icon).w(px(14.)).h(px(14.))) + widget::icon_button(id, palette, icon, tip, action).text_color(color) } pub(super) fn delete_icon_button( diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index eeb5657..286ac01 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -16,13 +16,15 @@ use gpui_kit::{ }; use super::ui::{ - accent_button, action_button, action_group, card, confirm_button, pill, plain_button, + accent_button, action_button, action_group, card, confirm_button, confirmed, pill, plain_button, }; use crate::{ gui::{ - DATE, DAY, Palette, Tooltip as _, Yumush, auth::field, avatar, clickable, - community_settings::search_text, entity_action, id_time, millis_time, notify_error, - profile::user_link, text, + DATE, DAY, Palette, Tooltip as _, Yumush, avatar, clickable, entity_action, id_time, + millis_time, notify_error, + profile::user_link, + text, + widget::{field, search_text}, }, network::NetworkHandle, }; @@ -111,12 +113,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_builder_delete.as_deref() != Some(user_id) { - self.chat.pending_builder_delete = Some(user_id.to_string()); + if !confirmed(&mut self.chat.pending_builder_delete, user_id) { cx.notify(); return; } - self.chat.pending_builder_delete = None; let network = self.network.clone(); let user_id = user_id.to_string(); @@ -367,12 +367,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_builder_purge.as_deref() != Some(user_id) { - self.chat.pending_builder_purge = Some(user_id.to_string()); + if !confirmed(&mut self.chat.pending_builder_purge, user_id) { cx.notify(); return; } - self.chat.pending_builder_purge = None; let network = self.network.clone(); let user_id = user_id.to_string(); diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index 9481e2c..8cdcab8 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -3,13 +3,16 @@ use std::sync::Arc; use common::share::{Fps, Kind, Quality, Resolution}; use gpui_kit::{ Context, Entity, InteractiveElement, IntoElement, ObjectFit, ParentElement, RenderImage, - StatefulInteractiveElement, Styled, StyledImage, Task, Window, assets::IconName, - component::Icon, div, img, px, + StatefulInteractiveElement, Styled, StyledImage, Task, Window, assets::IconName, div, img, px, }; use super::{ - Palette, Tooltip as _, Yumush, clickable, media_view::to_render_image, notify_error, - share_view::FRAME_TICK, text, + Palette, Tooltip as _, Yumush, clickable, + media_view::to_render_image, + notify_error, + share_view::FRAME_TICK, + text, + widget::{icon_button, spawn_warn}, }; use crate::share::session::WatchQuality; @@ -56,15 +59,11 @@ impl Yumush { ); let network = self.network.clone(); let user_id = user_id.clone(); - cx.spawn(async move |_, _| { - if let Err(error) = network + spawn_warn(cx, "camera watch", async move { + network .watch_share(&user_id, Kind::Camera, CAMERA_TILE) .await - { - tracing::warn!("camera watch failed: {error}"); - } - }) - .detach(); + }); changed = true; } @@ -184,29 +183,24 @@ pub(super) fn camera_toggle( ) -> impl IntoElement { let entity = entity.clone(); - clickable("camera_toggle", palette, move |window, cx| { - entity.update(cx, |yumush, cx| yumush.toggle_camera(window, cx)); - }) - .tip(if on { - "Turn off camera" - } else { - "Turn on camera" - }) - .size(px(26.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(if on { palette.ok } else { palette.muted }) - .child( - Icon::new(if on { + icon_button( + "camera_toggle", + palette, + if on { IconName::VideoOff } else { IconName::Video - }) - .w(px(14.)) - .h(px(14.)), + }, + if on { + "Turn off camera" + } else { + "Turn on camera" + }, + move |window, cx| { + entity.update(cx, |yumush, cx| yumush.toggle_camera(window, cx)); + }, ) + .text_color(if on { palette.ok } else { palette.muted }) } fn camera_tile( diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 56f092b..0813bd0 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -14,7 +14,7 @@ use crate::gui::{ FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, builder::{BuilderTab, Transfer}, clickable, community_name, - community_settings::{BanSort, LogSort, search_text}, + community_settings::{BanSort, LogSort}, composer::{self, Composer}, entity_action, hoverable, id_time, media_view::{self, Media}, @@ -23,13 +23,15 @@ use crate::gui::{ profile::profile_popover, rank_tag, share_view::{self, Viewer}, - sidebar::SidebarTab, + sidebar::{SidebarTab, unread_badge}, snippet, voice_note::{self, VoiceNote}, + widget::{icon_button, ok_or_notify, search_text, spawn_done}, }; use crate::network::Levels; use crate::settings::VOLUME; use crate::share::session::ShareSample; +use crate::voice::VoiceSample; use common::{ constant::MESSAGE_PAGE_LIMIT, event::Event, @@ -45,7 +47,7 @@ use common::{ use gpui_kit::{ Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, InteractiveElement, IntoElement, ParentElement, RenderOnce, ScrollHandle, - StatefulInteractiveElement, Styled, Task, Window, + StatefulInteractiveElement, Styled, Subscription, Task, Window, assets::IconName, base::Selectable, component::{ @@ -54,15 +56,13 @@ use gpui_kit::{ popover::Popover, searchable_list::SearchableVec, select::SelectState, + slider::{SliderEvent, SliderState}, + text::TextView, }, div, prelude::FluentBuilder as _, px, relative, }; -use gpui_kit::{ - Subscription, - component::slider::{SliderEvent, SliderState}, -}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum View { @@ -241,7 +241,7 @@ pub struct Chat { pub(super) builder_voice_rooms: Vec, pub(super) voice_task: Option>, pub(super) user_volume: Option, - pub(super) voice_samples: VecDeque, + pub(super) voice_samples: VecDeque, pub(super) share_sample: ShareSample, pub(super) share_loss: HashMap>, pub(super) stats_tab: StatsTab, @@ -538,7 +538,13 @@ impl Chat { Event::MessageUpdated(message) => { if self.is_selected(&message.community_id) { self.update_pin(&message); - self.insert_messages([message], me); + if let Some(existing) = self + .messages + .iter_mut() + .find(|existing| existing.id == message.id) + { + *existing = message; + } } } Event::MessageDeleted(message) => { @@ -715,16 +721,15 @@ impl Chat { fn forget_message(&mut self, message_id: &str) { self.messages.retain(|existing| existing.id != message_id); - let stale = match &self.composer { - Composer::Compose { reply } => reply.as_deref() == Some(message_id), - Composer::Edit { message_id: edited } => edited == message_id, - Composer::Select { .. } => false, - }; - if stale { - self.composer = Composer::Compose { reply: None }; - } - if let Composer::Select { ids } = &mut self.composer { - ids.retain(|id| id != message_id); + match &mut self.composer { + Composer::Select { ids } => ids.retain(|id| id != message_id), + Composer::Compose { reply } if reply.as_deref() == Some(message_id) => { + self.composer = Composer::Compose { reply: None }; + } + Composer::Edit { message_id: edited } if edited.as_str() == message_id => { + self.composer = Composer::Compose { reply: None }; + } + _ => {} } } @@ -866,18 +871,23 @@ impl Chat { } } - pub fn selected_community(&self) -> Option<&Community> { + fn community(&self, community_id: &str) -> Option<&Community> { self.communities .iter() .chain(self.opened.as_ref()) - .find(|community| self.is_selected(&community.id)) + .find(|community| community.id == community_id) + } + + pub fn selected_community(&self) -> Option<&Community> { + self.community(self.selected_community_id.as_deref()?) + } + + fn member_entry(&self, user_id: &str) -> Option<&Member> { + self.members.iter().find(|member| member.user.id == user_id) } pub fn member(&self, user_id: &str) -> Option<&User> { - self.members - .iter() - .map(|member| &member.user) - .find(|user| user.id == user_id) + self.member_entry(user_id).map(|member| &member.user) } pub fn author(&self, user_id: &str) -> Option<&User> { @@ -904,11 +914,7 @@ impl Chat { } pub fn rank_of(&self, user: &User) -> Option { - let rank = self - .members - .iter() - .find(|member| member.user.id == user.id) - .map(|member| member.rank); + let rank = self.member_entry(&user.id).map(|member| member.rank); permission::effective_rank(user.role, rank) } @@ -941,14 +947,6 @@ impl Chat { } pub fn update_member(&mut self, user: &User) { - if let Some(member) = self - .members - .iter_mut() - .find(|member| member.user.id == user.id) - { - member.user = user.clone(); - } - let peers = self .communities .iter_mut() @@ -967,6 +965,8 @@ impl Chat { .iter_mut() .map(|invitation| &mut invitation.inviter), ) + .chain(self.members.iter_mut().map(|member| &mut member.user)) + .chain(self.users.values_mut()) .chain(peers); for existing in known.filter(|existing| existing.id == user.id) { *existing = user.clone(); @@ -1056,6 +1056,15 @@ impl Chat { self.builder_voice_rooms.clear(); self.ringing.clear(); self.ring_task = None; + self.ghost = false; + self.drafts.clear(); + self.shares.clear(); + self.typing.clear(); + self.typing_sent.clear(); + self.users.clear(); + self.user_requests.clear(); + self.user_volume = None; + self.card_menu = CardMenu::Main; self.set_voice_off(); } @@ -1067,11 +1076,7 @@ impl Chat { } pub fn voice_room(&self) -> Option<&Community> { - let community_id = self.voice_community()?; - self.communities - .iter() - .chain(self.opened.as_ref()) - .find(|community| community.id == community_id) + self.community(self.voice_community()?) } pub fn in_voice(&self, community_id: &str) -> bool { @@ -1088,10 +1093,8 @@ impl Chat { } pub fn voice_enabled(&self, community_id: &str) -> bool { - self.communities - .iter() - .chain(self.opened.as_ref()) - .any(|community| community.id == community_id && community.voice_enabled) + self.community(community_id) + .is_some_and(|community| community.voice_enabled) } pub fn share_of(&self, community_id: &str, user_id: &str, kind: Kind) -> Option<&Share> { @@ -1164,12 +1167,8 @@ pub(super) fn create_community( let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { - let community = match network.create_community(&name).await { - Ok(community) => community, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(community) = ok_or_notify(network.create_community(&name).await, &this, cx) else { + return; }; let _ = this.update_in(cx, |yumush, window, cx| { @@ -1239,7 +1238,7 @@ impl Yumush { .flex() .flex_row() .size_full() - .child(self.sidebar(&entity, &self.search_query(cx), palette)) + .child(self.sidebar(&entity, &search_text(&self.chat.search_input, cx), palette)) .child(self.main_panel(&entity, palette, cx)) .children(self.fullscreen_viewer(&entity, palette)) } @@ -1424,7 +1423,7 @@ impl Yumush { .absolute() .top(px(-6.)) .right(px(-6.)) - .children(super::sidebar::unread_badge( + .children(unread_badge( palette, false, Some(&Unread { @@ -1468,12 +1467,10 @@ impl Yumush { .messages .iter() .enumerate() - .flat_map(|(index, message)| { + .map(|(index, message)| { let first = index == 0 || self.chat.messages[index - 1].user_id != message.user_id; - let divider = (divider == Some(index)) - .then(|| new_divider(palette).into_any_element()); - divider.into_iter().chain([render_message( + let row = render_message( message, first, index > 0, @@ -1481,12 +1478,22 @@ impl Yumush { self.user.as_ref(), entity, palette, - )]) + ); + if divider == Some(index) { + div() + .flex() + .flex_col() + .child(new_divider(palette)) + .child(row) + .into_any_element() + } else { + row + } }), ) } - fn composer(&self, entity: &Entity, palette: Palette) -> gpui_kit::AnyElement { + fn composer(&self, entity: &Entity, palette: Palette) -> AnyElement { if let Composer::Select { ids } = &self.chat.composer { return div() .p(px(16.)) @@ -1616,6 +1623,7 @@ impl Yumush { if let Some(community_id) = self.chat.selected_community_id.clone() { self.load_members(window, cx); + self.chat.messages.clear(); self.load_messages(None, window, cx); self.load_voice(window, cx); self.load_shares(community_id, cx); @@ -1626,12 +1634,8 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let communities = match network.communities().await { - Ok(communities) => communities, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(communities) = ok_or_notify(network.communities().await, &this, cx) else { + return; }; let unreads = network.unreads().await.unwrap_or_default(); @@ -1670,12 +1674,12 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let hits = match network.search_community(community_id.clone(), text).await { - Ok(hits) => hits, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(hits) = ok_or_notify( + network.search_community(community_id.clone(), text).await, + &this, + cx, + ) else { + return; }; let _ = this.update(cx, |yumush, cx| { @@ -1695,12 +1699,8 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let pins = match network.pins(&community_id).await { - Ok(pins) => pins, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(pins) = ok_or_notify(network.pins(&community_id).await, &this, cx) else { + return; }; let _ = this.update(cx, |yumush, cx| { @@ -1720,12 +1720,9 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let members = match network.members(&community_id).await { - Ok(members) => members, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(members) = ok_or_notify(network.members(&community_id).await, &this, cx) + else { + return; }; let _ = this.update_in(cx, |yumush, window, cx| { @@ -1776,12 +1773,8 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let bans = match network.bans(&community_id).await { - Ok(bans) => bans, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(bans) = ok_or_notify(network.bans(&community_id).await, &this, cx) else { + return; }; let _ = this.update(cx, |yumush, cx| { @@ -1842,15 +1835,14 @@ impl Yumush { let latest = before.is_none() && window.is_window_active(); cx.spawn_in(window, async move |this, cx| { - let page = match network - .read_messages(&community_id, before.as_deref()) - .await - { - Ok(page) => page, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(page) = ok_or_notify( + network + .read_messages(&community_id, before.as_deref()) + .await, + &this, + cx, + ) else { + return; }; let _ = this.update_in(cx, |yumush, window, cx| { @@ -1909,12 +1901,9 @@ impl Yumush { let network = self.network.clone(); let message_id = message_id.to_string(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.delete_message(&message_id).await { - notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.delete_message(&message_id).await + }); } pub(super) fn leave_community( @@ -1947,12 +1936,10 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let participants = match network.voice_participants(&community_id).await { - Ok(participants) => participants, - Err(error) => { - notify_error(&this, cx, error); - return; - } + let Some(participants) = + ok_or_notify(network.voice_participants(&community_id).await, &this, cx) + else { + return; }; let _ = this.update(cx, |yumush, cx| { @@ -2274,22 +2261,18 @@ impl Yumush { yumush.toggle_voice(community_id.clone(), window, cx) }) }; - let button = if in_voice { - primary_button("voice_button", palette, on_click) - } else { - clickable("voice_button", palette, on_click) - }; - let button = if direct && in_voice { - button.bg(palette.danger) - } else { - button - }; let (icon, tip) = match (direct, in_voice) { (true, false) => (IconName::Phone, "Call"), (true, true) => (IconName::PhoneOff, "Hang up"), (false, false) => (IconName::Headphones, "Join voice"), (false, true) => (IconName::Headphones, "Leave voice"), }; + let button = if in_voice { + primary_button("voice_button", palette, on_click) + .when(direct, |button| button.bg(palette.danger)) + } else { + clickable("voice_button", palette, on_click).text_color(palette.accent) + }; Some( button @@ -2299,11 +2282,6 @@ impl Yumush { .items_center() .justify_center() .rounded(px(6.)) - .text_color(if in_voice { - palette.on_accent - } else { - palette.accent - }) .child(Icon::new(icon).w(px(14.)).h(px(14.))), ) } @@ -2441,12 +2419,9 @@ impl Yumush { cx.notify(); let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.decline_call(&community_id).await { - notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.decline_call(&community_id).await + }); } fn voice_stack(&self, entity: &Entity, palette: Palette) -> Option { @@ -2525,42 +2500,40 @@ impl Yumush { .flex() .items_center() .child( - clickable("mic_button", palette, move |window, cx| { - mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx)) - }) - .tip(match (muted, self.hidden_in_voice()) { - (true, true) => "Speak as ghost", - (true, false) => "Unmute", - (false, _) => "Mute", - }) - .size(px(26.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) + icon_button( + "mic_button", + palette, + mic_icon, + match (muted, self.hidden_in_voice()) { + (true, true) => "Speak as ghost", + (true, false) => "Unmute", + (false, _) => "Mute", + }, + move |window, cx| { + mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx)) + }, + ) .text_color(if muted || deafened { palette.danger } else { palette.muted - }) - .child(Icon::new(mic_icon).w(px(14.)).h(px(14.))), + }), ) .child( - clickable("deafen_button", palette, move |_, cx| { - deafen_entity.update(cx, |yumush, cx| yumush.toggle_deafen(cx)) - }) - .tip(if deafened { "Undeafen" } else { "Deafen" }) - .size(px(26.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) + icon_button( + "deafen_button", + palette, + deafen_icon, + if deafened { "Undeafen" } else { "Deafen" }, + move |_, cx| { + deafen_entity.update(cx, |yumush, cx| yumush.toggle_deafen(cx)) + }, + ) .text_color(if deafened { palette.danger } else { palette.muted - }) - .child(Icon::new(deafen_icon).w(px(14.)).h(px(14.))), + }), ) .children(self.chat.ghost.then(|| { div() @@ -2898,7 +2871,7 @@ fn render_message( .text_color(palette.body) .child( div().min_w_0().child( - gpui_kit::component::text::TextView::markdown( + TextView::markdown( format!("message-body-{}", message.id), hard_breaks(&message.body), ) diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index 98c4843..cf5c887 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -1,5 +1,3 @@ -use super::text; -use crate::gui::STAMP; use std::{collections::HashMap, sync::Arc}; use common::{ @@ -22,14 +20,16 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, avatar, - chat::{DeleteStep, View}, + Palette, STAMP, Yumush, avatar, + chat::View, clickable, community_icon, entity_action, id_time, notify_error, profile::user_link, settings_page::{ Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, - section, text_row, + section, small_button, text_row, }, + text, + widget::search_text, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -225,7 +225,7 @@ impl Yumush { let Some(community_id) = self.chat.selected_community_id.clone() else { return; }; - let name = self.chat.community_name_input.read(cx).text().to_string(); + let name = self.chat.community_name_input.read(cx).text().to_string().trim().to_string(); if let Err(error) = validate_community_name(&name) { window.push_notification(Notification::error(error.to_string()), cx); @@ -235,15 +235,8 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - match network.update_community(&community_id, &name).await { - Ok(community) => { - let _ = this.update(cx, |yumush, cx| { - yumush.chat.insert_community(community); - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } + let result = network.update_community(&community_id, &name).await; + apply_community(&this, cx, result); }) .detach(); } @@ -286,31 +279,26 @@ impl Yumush { } pub(super) fn delete_community(&mut self, window: &mut Window, cx: &mut Context) { - match self.chat.delete_step { - DeleteStep::Idle => { - self.chat.delete_step = DeleteStep::Confirm; - cx.notify(); - } - DeleteStep::Confirm => { - let Some(community_id) = self.chat.selected_community_id.clone() else { - return; - }; - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_community(&community_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.remove_community(&community_id); - yumush.show_view(View::Chat, window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } + if !self.confirm_delete(cx) { + return; } + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_community(&community_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.remove_community(&community_id); + yumush.show_view(View::Chat, window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); } pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context) { @@ -454,19 +442,18 @@ fn voice_control( ) -> impl IntoElement { let entity = entity.clone(); - clickable("community_voice_button", palette, move |window, cx| { - entity.update(cx, |yumush, cx| { - yumush.set_community_voice(community_id.clone(), !enabled, window, cx) - }); - }) - .h(px(28.)) - .px(px(10.)) - .flex() - .items_center() - .rounded(px(6.)) + small_button( + "community_voice_button", + palette, + palette.text, + move |window, cx| { + entity.update(cx, |yumush, cx| { + yumush.set_community_voice(community_id.clone(), !enabled, window, cx) + }); + }, + ) .border_1() .border_color(palette.border) - .text_size(text(13.)) .child(if enabled { "On" } else { "Off" }) } @@ -476,15 +463,9 @@ fn view_control( palette: Palette, open: fn(&mut Yumush, &mut Window, &mut Context), ) -> impl IntoElement { - clickable(id, palette, entity_action(entity, open)) - .h(px(28.)) - .px(px(10.)) - .flex() - .items_center() - .rounded(px(6.)) + small_button(id, palette, palette.text, entity_action(entity, open)) .border_1() .border_color(palette.border) - .text_size(text(13.)) .child("View") } @@ -552,10 +533,6 @@ fn moderation_body( .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list)) } -pub(super) fn search_text(input: &Entity, cx: &App) -> String { - input.read(cx).text().to_string().trim().to_lowercase() -} - fn ban_list<'a>(bans: &'a [Ban], query: &str, sort: BanSort) -> Vec<&'a Ban> { let mut list: Vec<&Ban> = bans .iter() @@ -645,20 +622,18 @@ fn leave_control( ) -> impl IntoElement { let entity = entity.clone(); - clickable("leave_community_button", palette, move |window, cx| { - entity.update(cx, |yumush, cx| { - yumush.leave_community(community_id.clone(), window, cx) - }); - }) - .h(px(28.)) - .px(px(10.)) - .flex() - .items_center() - .rounded(px(6.)) + small_button( + "leave_community_button", + palette, + palette.danger, + move |window, cx| { + entity.update(cx, |yumush, cx| { + yumush.leave_community(community_id.clone(), window, cx) + }); + }, + ) .border_1() .border_color(palette.danger.opacity(0.5)) - .text_size(text(13.)) - .text_color(palette.danger) .child("Leave") } diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index d8a9ed6..da9ecb8 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -1,4 +1,5 @@ use super::text; +use super::widget::{compact_field, icon_button, panel, spawn_done}; use std::time::{Duration, Instant}; use common::{ @@ -6,42 +7,52 @@ use common::{ error::Error, model::Attachment, time::now_ms, - validate::{validate_message_body, validate_new_message, validate_poll}, + validate::{validate_new_message, validate_poll}, }; use gpui_kit::{ Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, IntoElement, KeyBinding, ParentElement, Styled, Window, actions, assets::IconName, component::{ - Icon, WindowExt, - checkbox::Checkbox, - input::{Input, InputState}, - notification::Notification, - popover::Popover, - text::TextView, + Icon, WindowExt, checkbox::Checkbox, input::InputState, notification::Notification, + popover::Popover, text::TextView, }, div, px, }; use super::{ - Palette, Tooltip as _, Trigger, Yumush, + Palette, Trigger, Yumush, chat::{Chat, TYPING_SEND_INTERVAL}, - clickable, hoverable, new_input, notify_error, pop_in, primary_button, + hoverable, new_input, notify_error, pop_in, primary_button, }; actions!(composer, [Bold, Italic, Code, Strike]); const CONTEXT: &str = "MessageComposer"; +const MOD: &str = if cfg!(target_os = "macos") { + "Cmd" +} else { + "Ctrl" +}; + const FORMAT_ROWS: [(&str, &str); 6] = [ - ("**bold**", "Ctrl+B"), - ("*italic*", "Ctrl+I"), - ("`code`", "Ctrl+E"), - ("~~strike~~", "Ctrl+Shift+X"), + ("**bold**", "B"), + ("*italic*", "I"), + ("`code`", "E"), + ("~~strike~~", "Shift+X"), ("> quote", ""), ("- list", ""), ]; +fn shortcut_label(keys: &str) -> String { + if keys.is_empty() { + String::new() + } else { + format!("{MOD}+{keys}") + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Composer { Compose { reply: Option }, @@ -164,17 +175,15 @@ fn edit_bar(entity: &Entity, palette: Palette) -> impl IntoElement { fn cancel_button(entity: &Entity, palette: Palette) -> impl IntoElement { let entity = entity.clone(); - clickable("cancel_composer", palette, move |window, cx| { - entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); - }) - .tip("Cancel") - .size(px(20.)) - .flex_shrink_0() - .flex() - .items_center() - .justify_center() - .rounded(px(4.)) - .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))) + icon_button( + "cancel_composer", + palette, + IconName::Close, + "Cancel", + move |window, cx| { + entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); + }, + ) } impl Yumush { @@ -270,10 +279,23 @@ impl Yumush { retry_after_seconds, }) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.slow_down(retry_after_seconds, &restore, body, pending, window, cx) + yumush.slow_down( + retry_after_seconds, + &restore, + &community_id, + body, + pending, + window, + cx, + ) + }); + } + Err(error) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.restore_message(&restore, &community_id, body, pending, window, cx) }); + notify_error(&this, cx, error); } - Err(error) => notify_error(&this, cx, error), } }) .detach(); @@ -283,23 +305,40 @@ impl Yumush { self.chat.composer = Composer::Compose { reply: None }; } - fn slow_down( + fn restore_message( &mut self, - seconds: u64, input: &Entity, + community_id: &str, body: String, pending: Vec, window: &mut Window, cx: &mut Context, ) { + if self.chat.selected_community_id.as_deref() != Some(community_id) { + self.chat.drafts.insert(community_id.to_string(), body); + return; + } if input.read(cx).text().len() == 0 { input.update(cx, |state, cx| state.set_value(body, window, cx)); } if self.chat.media.pending.is_empty() { self.chat.media.pending = pending; } - self.chat.slowed_until = Some(now_ms() + seconds * 1000); cx.notify(); + } + + fn slow_down( + &mut self, + seconds: u64, + input: &Entity, + community_id: &str, + body: String, + pending: Vec, + window: &mut Window, + cx: &mut Context, + ) { + self.restore_message(input, community_id, body, pending, window, cx); + self.chat.slowed_until = Some(now_ms() + seconds * 1000); cx.spawn_in(window, async move |this, cx| { loop { @@ -324,14 +363,22 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if let Err(error) = validate_message_body(&body, self.max_message_length()) { + if let Err(error) = validate_new_message(&body, 0, self.max_message_length()) { window.push_notification(Notification::error(error.to_string()), cx); return; } let network = self.network.clone(); + let restore = input.clone(); cx.spawn_in(window, async move |this, cx| { if let Err(error) = network.update_message(&message_id, &body).await { + let _ = this.update_in(cx, |yumush, window, cx| { + if restore.read(cx).text().len() == 0 { + restore.update(cx, |state, cx| state.set_value(body, window, cx)); + yumush.chat.composer = Composer::Edit { message_id }; + cx.notify(); + } + }); notify_error(&this, cx, error); } }) @@ -446,10 +493,10 @@ impl Yumush { pub fn bind_keys(cx: &mut App) { let scope = format!("{CONTEXT} > Input"); cx.bind_keys([ - KeyBinding::new("ctrl-b", Bold, Some(scope.as_str())), - KeyBinding::new("ctrl-i", Italic, Some(scope.as_str())), - KeyBinding::new("ctrl-e", Code, Some(scope.as_str())), - KeyBinding::new("ctrl-shift-x", Strike, Some(scope.as_str())), + KeyBinding::new("secondary-b", Bold, Some(scope.as_str())), + KeyBinding::new("secondary-i", Italic, Some(scope.as_str())), + KeyBinding::new("secondary-e", Code, Some(scope.as_str())), + KeyBinding::new("secondary-shift-x", Strike, Some(scope.as_str())), ]); } @@ -499,16 +546,12 @@ pub fn format_popover(palette: Palette) -> impl IntoElement { .content(move |_, _, _| { pop_in( "format_list", - div() + panel(palette) .w(px(340.)) .p(px(8.)) .flex() .flex_col() .gap(px(6.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .text_size(text(12.)) .children(FORMAT_ROWS.map(|(syntax, shortcut)| { div() @@ -517,32 +560,17 @@ pub fn format_popover(palette: Palette) -> impl IntoElement { .gap(px(12.)) .child(div().w(px(100.)).text_color(palette.muted).child(syntax)) .child(div().flex_1().child(TextView::markdown(syntax, syntax))) - .child(div().text_color(palette.muted).child(shortcut)) + .child( + div() + .text_color(palette.muted) + .child(shortcut_label(shortcut)), + ) })), Anchor::BottomLeft, ) }) } -pub(super) fn poll_field(input: &Entity, palette: Palette) -> impl IntoElement { - 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(input) - .appearance(false) - .text_color(palette.text) - .flex_1() - .min_w_0(), - ) -} - pub fn poll_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { let question = chat.poll_question.clone(); let options = chat.poll_options.clone(); @@ -565,38 +593,38 @@ pub fn poll_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i let submit = entity.clone(); pop_in( "poll_form", - div() + panel(palette) .w(px(300.)) .p(px(8.)) .flex() .flex_col() .gap(px(6.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .text_size(text(12.)) - .child(poll_field(&question, palette)) + .child(compact_field(palette, &question)) .children(options.iter().enumerate().map(|(index, option)| { let remove = entity.clone(); div() .flex() .items_center() .gap(px(6.)) - .child(div().flex_1().min_w_0().child(poll_field(option, palette))) + .child( + div() + .flex_1() + .min_w_0() + .child(compact_field(palette, option)), + ) .children((options.len() > MINIMUM_POLL_OPTIONS).then(|| { - clickable(format!("poll_remove_{index}"), palette, move |_, cx| { - remove.update(cx, |yumush, cx| { - yumush.remove_poll_option(index, cx) - }); - }) - .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))) + icon_button( + format!("poll_remove_{index}"), + palette, + IconName::Close, + "Remove option", + move |_, cx| { + remove.update(cx, |yumush, cx| { + yumush.remove_poll_option(index, cx) + }); + }, + ) })) })) .child( @@ -616,16 +644,17 @@ pub fn poll_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i }), ) .children((options.len() < MAXIMUM_POLL_OPTIONS).then(|| { - clickable("poll_add", palette, move |window, cx| { - add.update(cx, |yumush, cx| yumush.add_poll_option(window, cx)); - }) - .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::Plus).w(px(14.)).h(px(14.))) + icon_button( + "poll_add", + palette, + IconName::Plus, + "Add option", + move |window, cx| { + add.update(cx, |yumush, cx| { + yumush.add_poll_option(window, cx) + }); + }, + ) })), ) .child( @@ -656,7 +685,9 @@ impl Yumush { } pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context) { - if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS { + if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS + && index < self.chat.poll_options.len() + { self.chat.poll_options.remove(index); cx.notify(); } @@ -680,15 +711,11 @@ impl Yumush { let multiple = self.chat.poll_multiple; let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network + spawn_done(window, cx, async move { + network .create_poll(&community_id, &question, options, multiple) .await - { - notify_error(&this, cx, error); - } - }) - .detach(); + }); self.chat .poll_question diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index 80ff71f..41e7e7b 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -12,8 +12,9 @@ use gpui_kit::{ use super::{ Yumush, clickable, community_name, - composer::{Composer, poll_field}, - notify_error, palette, + composer::Composer, + palette, + widget::{compact_field, search_text, spawn_done}, }; pub struct Forward { @@ -55,7 +56,7 @@ impl Forward { impl Render for Forward { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let palette = palette(cx); - let query = self.filter.read(cx).text().to_string().to_lowercase(); + let query = search_text(&self.filter, cx); let entity = cx.entity(); let keep_authors = self.keep_authors; let rows: Vec<_> = { @@ -100,7 +101,7 @@ impl Render for Forward { .flex() .flex_col() .gap(px(10.)) - .child(poll_field(&self.filter, palette)) + .child(compact_field(palette, &self.filter)) .child( Checkbox::new("keep_authors") .label("Keep authors") @@ -165,15 +166,11 @@ impl Yumush { .collect(); let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network + spawn_done(window, cx, async move { + network .forward_messages(ids, &community_id, keep_authors) .await - { - notify_error(&this, cx, error); - } - }) - .detach(); + }); cx.notify(); } } diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index a0013c0..f9c12bf 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -523,7 +523,7 @@ impl Yumush { .. }) = self.chat.media.playing.take() { - cx.drop_image(frame, None); + cx.defer(move |cx| cx.drop_image(frame, None)); } } } diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index acbd672..3b2e3b4 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -7,20 +7,23 @@ use gpui_kit::{ Anchor, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Stateful, Styled, Window, assets::IconName, - component::{Icon, input::InputState, popover::Popover}, + component::{ + Icon, + input::InputState, + popover::{Popover, PopoverState}, + }, div, prelude::FluentBuilder as _, px, }; use super::{ - CLOCK, Palette, Tooltip as _, Yumush, - auth::field, - avatar, + CLOCK, Palette, Yumush, avatar, chat::{Chat, ReportTarget}, clickable, composer::trigger_icon, entity_action, id_time, notify_error, pop_in, primary_button, sidebar, + widget::{field, icon_button, panel, spawn_done}, }; pub fn reactions( @@ -96,14 +99,10 @@ pub fn react_popover( let popover = cx.entity(); pop_in( "react_list", - div() + panel(palette) .flex() .gap(px(2.)) .p(px(4.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .children(REACTIONS.map(|emoji| { let entity = entity.clone(); let message_id = message_id.clone(); @@ -211,24 +210,63 @@ pub fn pin_mark(palette: Palette) -> impl IntoElement { .child(Icon::new(IconName::Pin).w(px(12.)).h(px(12.))) } +struct Hit { + message_id: String, + name: String, + time: Option, + body: String, +} + +fn jump_row( + prefix: &str, + hit: &Hit, + entity: &Entity, + popover: &Entity, + palette: Palette, +) -> Stateful
{ + let entity = entity.clone(); + let popover = popover.clone(); + let message_id = hit.message_id.clone(); + + clickable( + format!("{prefix}_{message_id}"), + palette, + move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + entity.update(cx, |yumush, cx| { + yumush.go_to_message(message_id.clone(), window, cx) + }); + }, + ) + .flex() + .gap(px(6.)) + .px(px(8.)) + .py(px(4.)) + .rounded(px(6.)) + .text_size(text(12.)) + .child( + div() + .flex_shrink_0() + .font_weight(FontWeight::SEMIBOLD) + .child(hit.name.clone()), + ) +} + pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { let entity = entity.clone(); let input = chat.community_search.clone(); - let hits: Vec<(String, String, String, String)> = chat + let hits: Vec = chat .community_hits .iter() - .map(|hit| { - let name = hit + .map(|hit| Hit { + message_id: hit.message.id.clone(), + name: hit .author .as_ref() .map(|user| user.username.clone()) - .unwrap_or_default(); - ( - hit.message.id.clone(), - name, - id_time(&hit.message.id, CLOCK), - quote_text(&hit.message.body, hit.message.attachments.len()), - ) + .unwrap_or_default(), + time: Some(id_time(&hit.message.id, CLOCK)), + body: quote_text(&hit.message.body, hit.message.attachments.len()), }) .collect(); @@ -245,51 +283,22 @@ pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> let popover = cx.entity(); pop_in( "search_list", - div() + panel(palette) .w(px(320.)) .p(px(4.)) .flex() .flex_col() .gap(px(4.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .child(sidebar::input_box(&input, palette)) - .children(hits.iter().map(|(message_id, name, time, body)| { - let entity = entity.clone(); - let popover = popover.clone(); - let message_id = message_id.clone(); - clickable( - format!("search_hit_{message_id}"), - palette, - move |window, cx| { - popover.update(cx, |state, cx| state.dismiss(window, cx)); - let message_id = message_id.clone(); - entity.update(cx, |yumush, cx| { - yumush.go_to_message(message_id, window, cx) - }); - }, - ) - .flex() - .gap(px(6.)) - .px(px(8.)) - .py(px(4.)) - .rounded(px(6.)) - .text_size(text(12.)) - .child( - div() - .flex_shrink_0() - .font_weight(FontWeight::SEMIBOLD) - .child(name.clone()), - ) - .child( - div() - .flex_shrink_0() - .text_color(palette.muted) - .child(time.clone()), - ) - .child(div().flex_1().min_w_0().truncate().child(body.clone())) + .children(hits.iter().map(|hit| { + jump_row("search_hit", hit, &entity, &popover, palette) + .children(hit.time.as_ref().map(|time| { + div() + .flex_shrink_0() + .text_color(palette.muted) + .child(time.clone()) + })) + .child(div().flex_1().min_w_0().truncate().child(hit.body.clone())) })), Anchor::TopRight, ) @@ -298,19 +307,17 @@ pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { let entity = entity.clone(); - let pins: Vec<(String, String, String)> = chat + let pins: Vec = chat .pins .iter() - .map(|pin| { - let name = chat + .map(|pin| Hit { + message_id: pin.id.clone(), + name: chat .author(&pin.user_id) .map(|user| user.username.clone()) - .unwrap_or_default(); - ( - pin.id.clone(), - name, - quote_text(&pin.body, pin.attachments.len()), - ) + .unwrap_or_default(), + time: None, + body: quote_text(&pin.body, pin.attachments.len()), }) .collect(); @@ -322,50 +329,20 @@ pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i let popover = cx.entity(); pop_in( "pins_list", - div() + panel(palette) .w(px(260.)) .p(px(4.)) .flex() .flex_col() .gap(px(2.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) - .children(pins.iter().map(|(message_id, name, body)| { - let entity = entity.clone(); - let popover = popover.clone(); - let message_id = message_id.clone(); - clickable( - format!("pin_hit_{message_id}"), - palette, - move |window, cx| { - popover.update(cx, |state, cx| state.dismiss(window, cx)); - let message_id = message_id.clone(); - entity.update(cx, |yumush, cx| { - yumush.go_to_message(message_id, window, cx) - }); - }, - ) - .flex() - .gap(px(6.)) - .px(px(8.)) - .py(px(4.)) - .rounded(px(6.)) - .text_size(text(12.)) - .child( - div() - .flex_shrink_0() - .font_weight(FontWeight::SEMIBOLD) - .child(name.clone()), - ) - .child( + .children(pins.iter().map(|hit| { + jump_row("pin_hit", hit, &entity, &popover, palette).child( div() .flex_1() .min_w_0() .truncate() .text_color(palette.muted) - .child(body.clone()), + .child(hit.body.clone()), ) })), Anchor::TopRight, @@ -389,15 +366,11 @@ pub fn actions( let id = message.id.as_str(); let armed = chat.pending_message_delete.as_deref() == Some(id); - div() + panel(palette) .flex() .items_center() .gap(px(2.)) .p(px(2.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .when(!armed, |this| this.invisible()) .group_hover(group, |style| style.visible()) .child(action( @@ -514,12 +487,9 @@ impl Yumush { .any(|message| message.id == message_id && message.pinned); let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.pin(&message_id, !pinned).await { - notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.pin(&message_id, !pinned).await + }); } pub(super) fn toggle_reaction( @@ -531,12 +501,9 @@ impl Yumush { ) { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.react(&message_id, &emoji).await { - notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.react(&message_id, &emoji).await + }); } pub(super) fn start_report( @@ -600,16 +567,15 @@ fn action( let entity = entity.clone(); let message_id = message_id.to_string(); - clickable(format!("{tip}_{message_id}"), palette, move |window, cx| { - let message_id = message_id.clone(); - entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); - }) - .tip(tip) + icon_button( + format!("{tip}_{message_id}"), + palette, + icon, + tip, + move |window, cx| { + let message_id = message_id.clone(); + entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); + }, + ) .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(icon).w(px(14.)).h(px(14.))) } diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index 085c48e..75bb582 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -6,7 +6,12 @@ use gpui_kit::{ Window, assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, }; -use super::{Palette, Tooltip as _, Yumush, chat::Chat, clickable, notify_error, text}; +use super::{ + Palette, Yumush, + chat::Chat, + clickable, text, + widget::{icon_button, spawn_done}, +}; pub fn voter_count(poll: &Poll) -> usize { poll.options @@ -160,21 +165,16 @@ pub fn poll_card( .children(poll.closed.then_some("Closed")) .children(close_id.map(|close_id| { let close_entity = entity.clone(); - clickable( + icon_button( format!("poll_close_{close_id}"), palette, + IconName::CircleStop, + "End poll", move |window, cx| { let close_id = close_id.clone(); close_entity.update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); }, ) - .tip("End poll") - .size(px(22.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .child(Icon::new(IconName::CircleStop).w(px(13.)).h(px(13.))) })); div() @@ -282,21 +282,18 @@ impl Yumush { ), ), ) - .child( - clickable("poll_banner_jump", palette, move |window, cx| { + .child(icon_button( + "poll_banner_jump", + palette, + IconName::ArrowUpRight, + "Jump to message", + move |window, cx| { let message_id = message_id.clone(); jump.update(cx, |yumush, cx| { yumush.go_to_message(message_id, window, cx) }); - }) - .size(px(24.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::ArrowUpRight).w(px(14.)).h(px(14.))), - ), + }, + )), ) .children(expanded.then(|| { poll_card( @@ -320,12 +317,9 @@ impl Yumush { ) { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.vote(&message_id, positions).await { - notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.vote(&message_id, positions).await + }); } pub(super) fn close_poll( @@ -336,11 +330,10 @@ impl Yumush { ) { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.close_poll(&message_id).await { - notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done( + window, + cx, + async move { network.close_poll(&message_id).await }, + ); } } diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index 45e5d31..7bc70a2 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -1,5 +1,3 @@ -use super::text; -use crate::gui::DAY_YEAR; use std::{collections::HashMap, sync::Arc}; use common::{ @@ -23,9 +21,10 @@ use gpui_kit::{ use super::chat::{CardMenu, ReportTarget, View}; use super::message_actions::report_bar; use super::social::Relation; +use super::widget::{panel, spawn_done}; use super::{ - Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, palette, - pop_in, presence_color, rank_tag, swap_in, + DAY_YEAR, Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, + notify_error, palette, pop_in, presence_color, rank_tag, swap_in, text, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -81,6 +80,7 @@ pub(super) fn profile_popover( .on_open_change(move |_, _, cx| { notify_entity.update(cx, |yumush, cx| { yumush.chat.card_menu = CardMenu::Main; + yumush.chat.pending_user_delete = None; yumush.open_user_volume(&volume_user_id, cx); cx.notify() }) @@ -220,16 +220,12 @@ impl Card { }; let divider = (!rows.is_empty()).then(|| div().h(px(1.)).my(px(4.)).bg(palette.border)); - div() + panel(palette) .w(px(260.)) .p(px(16.)) .flex() .flex_col() .gap(px(10.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .child(avatar(palette, &self.user, px(48.), text(18.), avatars)) .child( div() @@ -655,10 +651,12 @@ impl Yumush { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { window.close_dialog(cx); - yumush.load_bans(window, cx); + if removal == Removal::Ban { + yumush.load_bans(window, cx); + } }); } - Err(error) => super::notify_error(&this, cx, error), + Err(error) => notify_error(&this, cx, error), } }) .detach(); @@ -677,12 +675,9 @@ impl Yumush { let network = self.network.clone(); let user_id = user_id.to_string(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.set_rank(&community_id, &user_id, rank).await { - super::notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.set_rank(&community_id, &user_id, rank).await + }); } pub(super) fn set_presence( @@ -699,12 +694,9 @@ impl Yumush { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.update_presence(presence).await { - super::notify_error(&this, cx, error); - } - }) - .detach(); + spawn_done(window, cx, async move { + network.update_presence(presence).await + }); } pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context) { @@ -730,7 +722,7 @@ impl Yumush { cx.notify(); }); } - Err(error) => super::notify_error(&this, cx, error), + Err(error) => notify_error(&this, cx, error), } }) .detach(); diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index d01921d..83df871 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -1,5 +1,4 @@ -use super::text; -use std::{future::Future, path::Path}; +use std::future::Future; use common::{error::Error, model::User}; use gpui_kit::{ @@ -7,15 +6,18 @@ use gpui_kit::{ InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, WeakEntity, Window, assets::IconName, - component::{Icon, input::InputState, switch::Switch}, + component::{input::InputState, switch::Switch}, div, prelude::FluentBuilder as _, px, transparent_black, }; use super::{ - Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable, - notify_error, primary_button, + Palette, Tooltip as _, Yumush, avatar, + chat::DeleteStep, + chat::View, + clickable, notify_error, primary_button, text, + widget::{field, icon_button}, }; use crate::settings::{self, FontSize, ThemeChoice}; @@ -203,31 +205,35 @@ impl Yumush { .detach(); } + pub(super) fn confirm_delete(&mut self, cx: &mut Context) -> bool { + if self.chat.delete_step == DeleteStep::Idle { + self.chat.delete_step = DeleteStep::Confirm; + cx.notify(); + return false; + } + true + } + pub(super) fn delete_account(&mut self, window: &mut Window, cx: &mut Context) { - match self.chat.delete_step { - DeleteStep::Idle => { - self.chat.delete_step = DeleteStep::Confirm; - cx.notify(); - } - DeleteStep::Confirm => { - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { - return; - }; - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_user(&user_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.end_session(window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } + if !self.confirm_delete(cx) { + return; } + let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_user(&user_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.end_session(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); } pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context) { @@ -277,7 +283,7 @@ pub(super) fn picked_avatar( let path = paths.into_iter().next()?; Some( executor - .spawn(async move { read_avatar_file(&path, maximum) }) + .spawn(async move { crate::avatar::prepare(&std::fs::read(&path)?, maximum) }) .await, ) } @@ -298,19 +304,15 @@ pub(super) fn header( .gap(px(8.)) .border_b_1() .border_color(palette.border) - .child( - clickable("settings_back_button", palette, move |window, cx| { + .child(icon_button( + "settings_back_button", + palette, + IconName::ArrowLeft, + "Back", + move |window, cx| { entity.update(cx, |yumush, cx| yumush.show_view(View::Chat, window, cx)); - }) - .tip("Back") - .size(px(26.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(IconName::ArrowLeft).w(px(14.)).h(px(14.))), - ) + }, + )) .child(div().font_weight(FontWeight::SEMIBOLD).child(title)) } @@ -530,7 +532,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: P })) } -fn small_button( +pub(super) fn small_button( id: &'static str, palette: Palette, color: Hsla, @@ -567,12 +569,6 @@ pub(super) fn delete_control( .child(if confirming { "Confirm" } else { "Delete" }) } -fn read_avatar_file(path: &Path, maximum: u64) -> Result, Error> { - let bytes = std::fs::read(path)?; - - crate::avatar::prepare(&bytes, maximum) -} - pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div { div() .min_h(px(48.)) diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index 0c53e64..0cb72f4 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -16,9 +16,15 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Trigger, Yumush, camera_view, chat::View, clickable, entity_action, - media_view::to_render_image, notify_error, pop_in, settings_page::segmented, - sidebar::icon_button, text, wave::wave, + Palette, Tooltip as _, Trigger, Yumush, camera_view, + chat::View, + clickable, entity_action, + media_view::to_render_image, + notify_error, pop_in, + settings_page::segmented, + text, + wave::wave, + widget::{icon_button, spawn_warn}, }; use crate::{ settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings}, @@ -68,14 +74,6 @@ impl AudioMode { ShareAudio::Source(_) => Self::App, } } - - fn audio(self, first: String) -> ShareAudio { - match self { - Self::Off => ShareAudio::Off, - Self::Everything => ShareAudio::Everything, - Self::App => ShareAudio::Source(first), - } - } } pub(super) struct Viewer { @@ -125,12 +123,11 @@ impl Yumush { settings::save(&self.settings); if self.network.set_share_settings(self.settings.share.clone()) { let network = self.network.clone(); - cx.spawn(async move |_, _| { - if let Err(error) = network.update_share().await { - tracing::warn!("share update failed: {error}"); - } - }) - .detach(); + spawn_warn( + cx, + "share update", + async move { network.update_share().await }, + ); } cx.notify(); } @@ -164,13 +161,14 @@ impl Yumush { } pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context) { - let first = self - .share_apps - .first() - .map(|app| app.node.clone()) - .unwrap_or_default(); - self.update_share(cx, |settings| settings.audio = mode.audio(first)); self.refresh_share_apps(cx); + let audio = match (mode, self.share_apps.first()) { + (AudioMode::Off, _) => ShareAudio::Off, + (AudioMode::Everything, _) => ShareAudio::Everything, + (AudioMode::App, Some(app)) => ShareAudio::Source(app.node.clone()), + (AudioMode::App, None) => return, + }; + self.update_share(cx, |settings| settings.audio = audio); } pub(super) fn set_share_source(&mut self, node: String, cx: &mut Context) { @@ -266,6 +264,11 @@ impl Yumush { } else { cx.spawn_in(window, async move |this, cx| { if let Err(error) = network.watch_share(&user_id, kind, watch).await { + let _ = this.update(cx, |yumush, cx| { + if yumush.is_watching(&user_id, kind) { + yumush.close_viewer(cx); + } + }); notify_error(&this, cx, error); } }) @@ -279,7 +282,7 @@ impl Yumush { return; }; if let Some(frame) = viewer.frame { - cx.drop_image(frame, None); + cx.defer(move |cx| cx.drop_image(frame, None)); } let network = self.network.clone(); if viewer.kind == Kind::Camera && self.chat.cameras.contains_key(&viewer.user_id) { @@ -340,29 +343,24 @@ impl Yumush { palette, )) .child( - clickable("share_toggle", palette, move |window, cx| { - toggle.update(cx, |yumush, cx| yumush.toggle_share(window, cx)); - }) - .tip(if sharing { - "Stop sharing" - } else { - "Share screen" - }) - .size(px(26.)) - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(if sharing { palette.ok } else { palette.muted }) - .child( - Icon::new(if sharing { + icon_button( + "share_toggle", + palette, + if sharing { IconName::ScreenShareOff } else { IconName::ScreenShare - }) - .w(px(14.)) - .h(px(14.)), - ), + }, + if sharing { + "Stop sharing" + } else { + "Share screen" + }, + move |window, cx| { + toggle.update(cx, |yumush, cx| yumush.toggle_share(window, cx)); + }, + ) + .text_color(if sharing { palette.ok } else { palette.muted }), ) .child( Popover::new("share_settings") @@ -418,8 +416,7 @@ impl Yumush { fn share_top(&self, user_id: &str, kind: Kind) -> Quality { self.chat - .selected_community_id - .as_ref() + .voice_community() .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) .map_or(SHARE_QUALITY, |share| share.source.top) } diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index aa1d2f6..dcb469e 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -29,6 +29,7 @@ use super::{ social::Relation, voice_stats, wave::wave, + widget::{bare_input, compact_frame, icon_button}, }; const SIDEBAR_WIDTH: f32 = 232.; @@ -341,7 +342,7 @@ impl Yumush { }; icon_button( - "sidebar_collapse".to_string(), + "sidebar_collapse", palette, icon, tip, @@ -350,6 +351,7 @@ impl Yumush { cx.notify(); }), ) + .into_any_element() } fn tab_bar(&self, entity: &Entity, palette: Palette) -> impl IntoElement { @@ -602,15 +604,12 @@ impl Yumush { }) }) .context_menu(move |menu, _, _| { - let remove = remove.clone(); - let remove_id = remove_id.clone(); - - menu.item( - PopupMenuItem::new("Remove friend").on_click(move |_, window, cx| { - remove.update(cx, |yumush, cx| { - yumush.remove_friend(remove_id.clone(), window, cx) - }) - }), + menu_action( + menu, + "Remove friend", + &remove, + remove_id.clone(), + |yumush, id, window, cx| yumush.remove_friend(id, window, cx), ) }) .into_any_element() @@ -623,15 +622,14 @@ impl Yumush { let mut trailing = Vec::new(); if relation != Relation::Myself { - let user_id = user.id.clone(); - trailing.push(icon_button( - format!("message_{}", user.id), + trailing.push(row_button( + entity, + "message", + &user.id, palette, IconName::MessageSquare, "Message", - entity_action(entity, move |yumush, window, cx| { - yumush.open_direct(user_id.clone(), window, cx) - }), + |yumush, id, window, cx| yumush.open_direct(id, window, cx), )); } let action = match relation { @@ -639,15 +637,14 @@ impl Yumush { _ => None, }; if let Some((label, icon)) = action { - let user_id = user.id.clone(); - trailing.push(icon_button( - format!("friend_action_{}", user.id), + trailing.push(row_button( + entity, + "friend_action", + &user.id, palette, icon, label, - entity_action(entity, move |yumush, window, cx| { - yumush.friend_action(relation, user_id.clone(), window, cx) - }), + move |yumush, id, window, cx| yumush.friend_action(relation, id, window, cx), )); } @@ -675,30 +672,27 @@ impl Yumush { } fn incoming_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { - let accept_id = user.id.clone(); - let decline_id = user.id.clone(); - self.user_row( palette, user, [ - icon_button( - format!("accept_friend_{}", user.id), + row_button( + entity, + "accept_friend", + &user.id, palette, IconName::Check, "Accept", - entity_action(entity, move |yumush, window, cx| { - yumush.accept_friend(accept_id.clone(), window, cx) - }), + |yumush, id, window, cx| yumush.accept_friend(id, window, cx), ), - icon_button( - format!("decline_friend_{}", user.id), + row_button( + entity, + "decline_friend", + &user.id, palette, IconName::X, "Decline", - entity_action(entity, move |yumush, window, cx| { - yumush.remove_friend(decline_id.clone(), window, cx) - }), + |yumush, id, window, cx| yumush.remove_friend(id, window, cx), ), ], ) @@ -706,19 +700,17 @@ impl Yumush { } fn outgoing_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { - let cancel_id = user.id.clone(); - self.user_row( palette, user, - [icon_button( - format!("cancel_friend_{}", user.id), + [row_button( + entity, + "cancel_friend", + &user.id, palette, IconName::X, "Cancel", - entity_action(entity, move |yumush, window, cx| { - yumush.remove_friend(cancel_id.clone(), window, cx) - }), + |yumush, id, window, cx| yumush.remove_friend(id, window, cx), )], ) .into_any_element() @@ -731,8 +723,6 @@ impl Yumush { palette: Palette, ) -> AnyElement { let community = &invitation.community; - let accept_id = community.id.clone(); - let decline_id = community.id.clone(); let label = div().flex().flex_col().child(community.name.clone()).child( div() .text_size(text(11.)) @@ -746,23 +736,23 @@ impl Yumush { community_icon(palette, community, px(16.), text(10.), &self.chat.avatars), label, [ - icon_button( - format!("accept_invitation_{}", community.id), + row_button( + entity, + "accept_invitation", + &community.id, palette, IconName::Check, "Accept", - entity_action(entity, move |yumush, window, cx| { - yumush.accept_invitation(accept_id.clone(), window, cx) - }), + |yumush, id, window, cx| yumush.accept_invitation(id, window, cx), ), - icon_button( - format!("decline_invitation_{}", community.id), + row_button( + entity, + "decline_invitation", + &community.id, palette, IconName::X, "Decline", - entity_action(entity, move |yumush, window, cx| { - yumush.decline_invitation(decline_id.clone(), window, cx) - }), + |yumush, id, window, cx| yumush.decline_invitation(id, window, cx), ), ], ) @@ -940,37 +930,33 @@ fn community_menu( let entity = entity.clone(); move |menu, _, _| { - let invite = entity.clone(); - let invite_id = community_id.clone(); - let settings = entity.clone(); - let settings_id = community_id.clone(); - let leave = entity.clone(); - let leave_id = community_id.clone(); - - let menu = menu - .item(PopupMenuItem::new("Invite").on_click(move |_, window, cx| { - invite.update(cx, |yumush, cx| { - yumush.open_invite(invite_id.clone(), window, cx) - }) - })) - .item( - PopupMenuItem::new("Settings").on_click(move |_, window, cx| { - settings.update(cx, |yumush, cx| { - yumush.open_community_settings(settings_id.clone(), window, cx) - }) - }), - ); + let menu = menu_action( + menu, + "Invite", + &entity, + community_id.clone(), + |yumush, id, window, cx| yumush.open_invite(id, window, cx), + ); + let menu = menu_action( + menu, + "Settings", + &entity, + community_id.clone(), + |yumush, id, window, cx| yumush.open_community_settings(id, window, cx), + ); let menu = mute_item(menu, &entity, community_id.clone(), muted); if !can_leave { return menu; } - menu.item(PopupMenuItem::new("Leave").on_click(move |_, window, cx| { - leave.update(cx, |yumush, cx| { - yumush.leave_community(leave_id.clone(), window, cx) - }) - })) + menu_action( + menu, + "Leave", + &entity, + community_id.clone(), + |yumush, id, window, cx| yumush.leave_community(id, window, cx), + ) } } @@ -996,6 +982,7 @@ fn new_community_menu( window, cx, |this, name, window, cx| { + let name = name.trim().to_string(); if validate_community_name(&name).is_ok() { create_community(this, name, window, cx); } @@ -1008,25 +995,11 @@ fn new_community_menu( } pub(super) fn input_box(input: &Entity, palette: Palette) -> Div { - div() - .h(px(30.)) - .px(px(10.)) - .flex() - .items_center() + compact_frame(palette) .gap(px(8.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.field) .text_color(palette.muted) .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))) - .child( - Input::new(input) - .appearance(false) - .text_color(palette.text) - .flex_1() - .min_w_0(), - ) + .child(bare_input(palette, Input::new(input))) } fn group(title: &'static str, palette: Palette, rows: Vec) -> Option
{ @@ -1067,22 +1040,39 @@ fn entry( .children(trailing) } -pub(super) fn icon_button( - id: String, +fn row_button( + entity: &Entity, + key: &str, + id: &str, palette: Palette, icon: IconName, tip: &'static str, - on_click: impl Fn(&mut Window, &mut App) + 'static, + run: impl Fn(&mut Yumush, String, &mut Window, &mut Context) + 'static, ) -> AnyElement { - clickable(id, palette, on_click) - .tip(tip) - .size(px(26.)) - .flex_shrink_0() - .flex() - .items_center() - .justify_center() - .rounded(px(6.)) - .text_color(palette.muted) - .child(Icon::new(icon).w(px(14.)).h(px(14.))) - .into_any_element() + let id = id.to_string(); + + icon_button( + format!("{key}_{id}"), + palette, + icon, + tip, + entity_action(entity, move |yumush, window, cx| { + run(yumush, id.clone(), window, cx) + }), + ) + .into_any_element() +} + +fn menu_action( + menu: PopupMenu, + label: &'static str, + entity: &Entity, + id: String, + run: impl Fn(&mut Yumush, String, &mut Window, &mut Context) + 'static, +) -> PopupMenu { + let entity = entity.clone(); + + menu.item(PopupMenuItem::new(label).on_click(move |_, window, cx| { + entity.update(cx, |yumush, cx| run(yumush, id.clone(), window, cx)) + })) } diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs index e7df1a1..318e28a 100644 --- a/crates/client/src/gui/snippet.rs +++ b/crates/client/src/gui/snippet.rs @@ -6,7 +6,10 @@ use gpui_kit::{ relative, }; -use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link}; +use super::{ + Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link, + widget::panel, +}; pub fn snippet_card( message: &Message, @@ -21,15 +24,11 @@ pub fn snippet_card( }; Some( - div() + panel(palette) .flex() .flex_col() .gap(px(10.)) .p(px(10.)) - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) .child( div() .text_size(text(12.)) @@ -51,13 +50,13 @@ fn snippet_row( entity: &Entity, palette: Palette, ) -> impl IntoElement { - let user = User { + let user = chat.author(&item.user_id).cloned().unwrap_or_else(|| User { id: item.user_id.clone(), username: item.username.clone(), role: Role::User, status: String::new(), avatar_id: item.avatar_id.clone(), - }; + }); div() .flex() diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index 5cc1649..22119fd 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -1,12 +1,11 @@ -use super::text; use std::{fmt::Display, future::Future}; use common::{ - model::{Community, CommunityKind, Rank}, + model::{Community, CommunityKind, Rank, User}, validate::validate_username, }; use gpui_kit::{ - Context, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, component::{ WindowExt, @@ -15,14 +14,17 @@ use gpui_kit::{ div, px, }; -use super::{Palette, Yumush, avatar, new_input, notify_error, primary_button}; +use super::{ + Palette, Yumush, avatar, new_input, notify_error, primary_button, text, + widget::{search_text, spawn_done}, +}; #[derive(Debug, Clone, Default)] pub enum InviteLookup { #[default] Idle, - Found(common::model::User), - Member(common::model::User), + Found(User), + Member(User), Missing, } @@ -47,19 +49,6 @@ impl Relation { } } -fn spawn_done( - window: &mut Window, - cx: &mut Context, - call: impl Future> + 'static, -) { - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = call.await { - notify_error(&this, cx, error); - } - }) - .detach(); -} - fn spawn_community( window: &mut Window, cx: &mut Context, @@ -155,20 +144,10 @@ impl Yumush { .detach(); } - pub(super) fn search_query(&self, cx: &Context) -> String { - self.chat - .search_input - .read(cx) - .text() - .to_string() - .trim() - .to_lowercase() - } - pub(super) fn search_user(&mut self, window: &mut Window, cx: &mut Context) { self.chat.found = None; cx.notify(); - let username = self.search_query(cx); + let username = search_text(&self.chat.search_input, cx); if validate_username(&username).is_err() { return; } @@ -177,7 +156,7 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { let found = network.find_user(&username).await.ok(); let _ = this.update(cx, |yumush, cx| { - if yumush.search_query(cx) != username { + if search_text(&yumush.chat.search_input, cx) != username { return; } if let Some(user) = &found { @@ -349,7 +328,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let username = input.read(cx).text().to_string().trim().to_string(); + let username = search_text(input, cx); self.chat.invite = InviteLookup::Idle; window.refresh(); if validate_username(&username).is_err() { @@ -371,7 +350,7 @@ impl Yumush { Err(_) => InviteLookup::Missing, }; let _ = this.update_in(cx, |yumush, window, cx| { - if input.read(cx).text().to_string().trim() != username { + if search_text(&input, cx) != username { return; } if let InviteLookup::Found(user) | InviteLookup::Member(user) = &lookup { @@ -409,7 +388,7 @@ fn invite_result( entity: &Entity, yumush: &Yumush, palette: Palette, -) -> Option { +) -> Option { match lookup { InviteLookup::Idle => None, InviteLookup::Missing => Some( @@ -454,7 +433,7 @@ fn invite_result( } } -fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gpui_kit::Div { +fn user_row(user: &User, yumush: &Yumush, palette: Palette) -> Div { div() .flex() .items_center() diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index 34afec1..55f951f 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -20,6 +20,7 @@ use super::{ clickable, media_view::{time_text, upload_file}, notify_error, primary_button, text, + widget::ok_or_notify, }; use crate::{ media::voice_note::{self, BARS}, @@ -31,6 +32,8 @@ use crate::{ const TICK: Duration = Duration::from_millis(100); const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize; +const MAX_SECONDS: usize = 300; +const MAX_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * MAX_SECONDS; const SLOT_WIDTH: f32 = 5.; const BAR_WIDTH: f32 = 3.; const BAR_MIN: f32 = 2.; @@ -51,7 +54,9 @@ pub enum VoiceNote { } fn drain(consumer: &mut Consumer, samples: &mut Vec) { - while let Ok(sample) = consumer.pop() { + while samples.len() < MAX_SAMPLES + && let Ok(sample) = consumer.pop() + { samples.push(sample); } } @@ -148,7 +153,7 @@ pub fn recording_row( .text_size(text(13.)) .text_color(palette.text) .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.))) - .child(time_text(started.elapsed())) + .child(time_text(started.elapsed().min(Duration::from_secs(MAX_SECONDS as u64)))) .child(bars(levels, 1., palette, |_, _, _| {})), ) .child( @@ -265,17 +270,20 @@ impl Yumush { else { return; }; - let attachment = - match upload_file(&this, &network, &community_id, path, maximum, cx).await { - Ok(attachment) => attachment, - Err(error) => return notify_error(&this, cx, error), - }; - if let Err(error) = network - .create_message(&community_id, "", vec![attachment.id], None) - .await - { - notify_error(&this, cx, error); - } + let uploaded = + upload_file(&this, &network, &community_id, path.clone(), maximum, cx).await; + let _ = std::fs::remove_file(&path); + let attachment = match uploaded { + Ok(attachment) => attachment, + Err(error) => return notify_error(&this, cx, error), + }; + ok_or_notify( + network + .create_message(&community_id, "", vec![attachment.id], None) + .await, + &this, + cx, + ); }) .detach(); } diff --git a/crates/client/src/gui/widget.rs b/crates/client/src/gui/widget.rs new file mode 100644 index 0000000..3884645 --- /dev/null +++ b/crates/client/src/gui/widget.rs @@ -0,0 +1,116 @@ +use std::{fmt::Display, future::Future}; + +use gpui_kit::{ + App, AsyncWindowContext, Context, Div, ElementId, Entity, ParentElement, Stateful, Styled, + WeakEntity, Window, + assets::IconName, + component::{Icon, input::Input, input::InputState}, + div, px, +}; + +use super::{Palette, Tooltip as _, Yumush, clickable, notify_error}; + +pub(super) fn icon_button( + id: impl Into, + palette: Palette, + icon: IconName, + tip: &'static str, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + clickable(id, palette, on_click) + .tip(tip) + .size(px(26.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(icon).w(px(14.)).h(px(14.))) +} + +pub(super) fn panel(palette: Palette) -> Div { + div() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) +} + +pub(super) fn field(palette: Palette, input: &Entity) -> Div { + frame(palette, Input::new(input)) +} + +pub(super) fn compact_frame(palette: Palette) -> Div { + div() + .h(px(30.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) +} + +pub(super) fn compact_field(palette: Palette, input: &Entity) -> Div { + compact_frame(palette).child(bare_input(palette, Input::new(input))) +} + +pub(super) fn frame(palette: Palette, input: Input) -> Div { + div() + .h(px(32.)) + .flex() + .items_center() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .child(bare_input(palette, input)) +} + +pub(super) fn bare_input(palette: Palette, input: Input) -> Input { + input + .appearance(false) + .text_color(palette.text) + .flex_1() + .min_w_0() +} + +pub(super) fn search_text(input: &Entity, cx: &App) -> String { + input.read(cx).text().to_string().trim().to_lowercase() +} + +pub(super) fn ok_or_notify( + result: Result, + this: &WeakEntity, + cx: &mut AsyncWindowContext, +) -> Option { + result.map_err(|error| notify_error(this, cx, error)).ok() +} + +pub(super) fn spawn_done( + window: &mut Window, + cx: &mut Context, + call: impl Future> + 'static, +) { + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = call.await { + notify_error(&this, cx, error); + } + }) + .detach(); +} + +pub(super) fn spawn_warn( + cx: &mut Context, + label: &'static str, + call: impl Future> + 'static, +) { + cx.spawn(async move |_, _| { + if let Err(error) = call.await { + tracing::warn!("{label} failed: {error}"); + } + }) + .detach(); +} diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 1e4467b..288a2e0 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -1,6 +1,7 @@ -use std::path::PathBuf; +use std::{fs, io::Write, path::PathBuf}; use common::config::Config; +use tracing::warn; pub mod accounts; pub mod avatar; @@ -16,13 +17,37 @@ pub mod voice; pub const NAME: &str = "Yumush"; -pub fn config_file(name: &str) -> Option { +fn config_file(name: &str) -> Option { std::env::var_os("YUMUSH_CONFIG_DIR") .map(PathBuf::from) .or_else(|| dirs::config_dir().map(|dir| dir.join("yumush"))) .map(|dir| dir.join(name)) } +pub fn read_config(name: &str) -> Option { + fs::read_to_string(config_file(name)?).ok() +} + +pub fn write_config(name: &str, content: &str) { + let Some(path) = config_file(name) else { + return; + }; + let result = path + .parent() + .map_or(Ok(()), fs::create_dir_all) + .and_then(|()| { + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(&path)?.write_all(content.as_bytes()) + }); + + if let Err(error) = result { + warn!("save {name} failed: {error}"); + } +} + const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/../../configs/client_config.toml" diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 6a4898e..28a0748 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -1,3 +1,5 @@ +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] + use client::{ ClientConfig, NAME, gui::{self, Yumush}, @@ -101,7 +103,9 @@ fn open_window( view.update(cx, |yumush, cx| yumush.attach_window(window, cx)); let closing = view.clone(); window.on_window_should_close(cx, move |_, cx| { - if !closing.update(cx, |yumush, _| yumush.detach_window()) { + let detached = + tray::AVAILABLE && closing.update(cx, |yumush, _| yumush.detach_window()); + if !detached { cx.quit(); } true diff --git a/crates/client/src/media/decode.rs b/crates/client/src/media/decode.rs index 8b78467..539e53c 100644 --- a/crates/client/src/media/decode.rs +++ b/crates/client/src/media/decode.rs @@ -248,25 +248,8 @@ impl VideoDecoder { else { return Vec::new(); }; - match decoder.decode(&packet.data) { - Ok(Some(picture)) => vec![( - pts, - Picture::Planes(Planes { - y: picture.y, - y_stride: picture.stride, - u: picture.u, - v: picture.v, - uv_stride: picture.uv_stride, - width: u32::from(picture.width), - height: u32::from(picture.height), - }), - )], - Ok(None) => Vec::new(), - Err(error) => { - warn!("video packet skipped: {error}"); - Vec::new() - } - } + skipped(decoder.decode(&packet.data)) + .map_or_else(Vec::new, |picture| vec![(pts, vp8_picture(picture))]) } VideoDecoder::H265(decoder) => { if let Err(error) = decoder.decode_annex_b(&packet.data) { @@ -276,14 +259,8 @@ impl VideoDecoder { decoder.end_picture(); drain_h265(decoder, seconds) } - VideoDecoder::Vp9(decoder) => match decoder.decode(&packet.data) { - Ok(Some(picture)) => vec![(seconds, vp9_picture(picture))], - Ok(None) => Vec::new(), - Err(error) => { - warn!("video packet skipped: {error}"); - Vec::new() - } - }, + VideoDecoder::Vp9(decoder) => skipped(decoder.decode(&packet.data)) + .map_or_else(Vec::new, |picture| vec![(seconds, vp9_picture(picture))]), VideoDecoder::Av1(decoder) => match decoder.decode_temporal_unit(&packet.data) { Ok(pictures) => pictures .into_iter() @@ -426,6 +403,25 @@ fn h265_picture(picture: &ec_h265::decode::DecodedPicture) -> Picture { }) } +fn skipped(result: Result) -> T { + result.unwrap_or_else(|error| { + warn!("video packet skipped: {error}"); + T::default() + }) +} + +fn vp8_picture(picture: ec_vp8::decode::Picture) -> Picture { + Picture::Planes(Planes { + y: picture.y, + y_stride: picture.stride, + u: picture.u, + v: picture.v, + uv_stride: picture.uv_stride, + width: u32::from(picture.width), + height: u32::from(picture.height), + }) +} + fn vp9_picture(picture: ec_vp9::decode::Picture) -> Picture { let shift = u32::from(picture.bit_depth.saturating_sub(8)); Picture::Planes(Planes { @@ -467,11 +463,9 @@ pub struct Worker { reader: Reader, playback: Playback, producer: Option>, - video_index: Option, - video: Option, + video: Option<(u32, VideoDecoder)>, backlog: VecDeque, - audio_index: Option, - audio: Option, + audio: Option<(u32, AudioDecoder)>, pending: VecDeque, resampler: Resampler, align: Option, @@ -495,11 +489,9 @@ impl Worker { reader, playback, producer, - video_index: tracks.video.as_ref().map(|(index, _, _)| *index), - video: tracks.video.map(|(_, _, decoder)| decoder), + video: tracks.video.map(|(index, _, decoder)| (index, decoder)), backlog: VecDeque::new(), - audio_index: tracks.audio.as_ref().map(|(index, _)| *index), - audio: tracks.audio.map(|(_, decoder)| decoder), + audio: tracks.audio, pending: VecDeque::new(), resampler: Resampler::default(), align: Some(0.0), @@ -534,14 +526,13 @@ impl Worker { fn play_step(&mut self) { self.feed(); - self.decode_backlog(); + let decoded = self.decode_backlog(); if self.eof { self.finish(); } - if self.eof || self.buffered() { + let read = !self.eof && !self.buffered() && self.fill(); + if !decoded && !read { wait(); - } else { - self.fill(); } } @@ -549,14 +540,17 @@ impl Worker { self.pending.len() >= RING_FRAMES } - fn fill(&mut self) { + fn fill(&mut self) -> bool { + let mut read = false; while !self.eof && !self.buffered() && self.backlog.len() < BACKLOG_LIMIT && (self.producer.is_some() || self.backlog.is_empty()) { self.step(); + read = true; } + read } fn primed(&self) -> bool { @@ -628,24 +622,32 @@ impl Worker { } fn packet(&mut self, packet: Packet) { - if Some(packet.stream) == self.video_index && self.video.is_some() { + if self + .video + .as_ref() + .is_some_and(|(index, _)| *index == packet.stream) + { self.backlog.push_back(Queued::Packet(packet)); - } else if Some(packet.stream) == self.audio_index { + } else if self + .audio + .as_ref() + .is_some_and(|(index, _)| *index == packet.stream) + { self.audio_packet(&packet); } } - fn decode_backlog(&mut self) { - let Some(video) = self.video.as_mut() else { - return; + fn decode_backlog(&mut self) -> bool { + let Some((_, video)) = self.video.as_mut() else { + return false; }; if lock(&self.shared.video).queue.len() >= QUEUE_LIMIT { - return; + return false; } let pictures = match self.backlog.pop_front() { Some(Queued::Packet(packet)) => video.send(&packet), Some(Queued::Flush) => video.flush(), - None => return, + None => return false, }; let position = position(&self.shared, &self.playback); for (pts, picture) in pictures { @@ -653,13 +655,14 @@ impl Worker { show(&self.shared, pts, picture); } } + true } fn audio_packet(&mut self, packet: &Packet) { if self.producer.is_none() { return; } - let Some(audio) = self.audio.as_mut() else { + let Some((_, audio)) = self.audio.as_mut() else { return; }; let mut samples = std::mem::take(&mut self.scratch); @@ -708,7 +711,7 @@ impl Worker { } if self.producer.is_some() { let mut samples = std::mem::take(&mut self.scratch); - let params = self.audio.as_mut().and_then(|audio| { + let params = self.audio.as_mut().and_then(|(_, audio)| { audio .flush(&mut samples) .ok() @@ -729,10 +732,10 @@ impl Worker { self.skip = 0; self.eof = false; self.backlog.clear(); - if let Some(video) = self.video.as_mut() { + if let Some((_, video)) = self.video.as_mut() { video.reset(); } - if let Some(audio) = self.audio.as_mut() { + if let Some((_, audio)) = self.audio.as_mut() { audio.reset(); } lock(&self.shared.video).queue.clear(); @@ -744,7 +747,12 @@ impl Worker { lock(&self.shared.stash).clear(); clock.rebase(to); } - if let Some(stream) = self.video_index.or(self.audio_index) { + let stream = self + .video + .as_ref() + .map(|(index, _)| *index) + .or(self.audio.as_ref().map(|(index, _)| *index)); + if let Some(stream) = stream { let at = Timestamp::new((to * 1_000_000.0) as i64, TimeBase::MICROS); if self.reader.seek(stream, at, SeekMode::SyncBefore).is_err() { self.restart(); diff --git a/crates/client/src/media/meter.rs b/crates/client/src/media/meter.rs index 799ff05..ea02f8a 100644 --- a/crates/client/src/media/meter.rs +++ b/crates/client/src/media/meter.rs @@ -1,9 +1,12 @@ use std::collections::VecDeque; -use std::sync::{Arc, Mutex, OnceLock, PoisonError}; +use std::sync::{Arc, Mutex, OnceLock}; use common::constant::VOICE_SAMPLE_RATE; use spectrum::{Analyzer, WINDOW}; +use super::decode::lock; +use super::resample::mean; + pub fn rms(samples: &[f32]) -> f32 { if samples.is_empty() { return 0.0; @@ -24,12 +27,11 @@ pub struct Spectrum { impl Spectrum { pub fn record(&mut self, samples: &[f32], channels: usize) { - for frame in samples.chunks(channels) { + for frame in samples.chunks(channels.max(1)) { if self.samples.len() >= WINDOW { self.samples.pop_front(); } - self.samples - .push_back(frame.iter().sum::() / frame.len() as f32); + self.samples.push_back(mean(frame)); } self.fresh = true; } @@ -55,13 +57,10 @@ pub struct Meter(Arc>); impl Meter { pub fn record(&self, samples: &[f32], channels: usize) { - self.0 - .lock() - .unwrap_or_else(PoisonError::into_inner) - .record(samples, channels); + lock(&self.0).record(samples, channels); } pub fn take(&self) -> Vec { - self.0.lock().unwrap_or_else(PoisonError::into_inner).take() + lock(&self.0).take() } } diff --git a/crates/client/src/media/mod.rs b/crates/client/src/media/mod.rs index 36023ea..6ba6fb7 100644 --- a/crates/client/src/media/mod.rs +++ b/crates/client/src/media/mod.rs @@ -15,6 +15,7 @@ use std::{ use ec_core::registry::MediaType; use ec_probe::{Reader, decoder::AudioDecoder}; use rtrb::RingBuffer; +use tracing::warn; use crate::voice::{ Playback, @@ -190,6 +191,7 @@ impl Player { .name("media-decode".to_string()) .spawn(move || { let Ok((reader, tracks, _)) = open_tracks(&worker_path) else { + warn!("media reopen failed: {}", worker_path.display()); return; }; Worker::new( @@ -212,7 +214,7 @@ impl Player { } pub fn play(&self) { - if self.finished() { + if lock(&self.shared.clock).state == State::Finished { *lock(&self.shared.seek) = Some(0.0); } let mut clock = lock(&self.shared.clock); @@ -247,16 +249,16 @@ impl Player { pub fn seek(&self, to: Duration) { *lock(&self.shared.seek) = Some(to.as_secs_f64()); + let mut clock = lock(&self.shared.clock); + if clock.state == State::Finished { + clock.set(State::Paused); + } } pub fn playing(&self) -> bool { lock(&self.shared.clock).state == State::Playing } - pub fn finished(&self) -> bool { - lock(&self.shared.clock).state == State::Finished - } - pub fn position(&self) -> Duration { Duration::from_secs_f64(decode::position(&self.shared, &self.playback)) } diff --git a/crates/client/src/media/resample.rs b/crates/client/src/media/resample.rs index f4058e6..89380f3 100644 --- a/crates/client/src/media/resample.rs +++ b/crates/client/src/media/resample.rs @@ -2,22 +2,23 @@ use common::constant::VOICE_SAMPLE_RATE; pub type Stereo = [f32; 2]; +pub fn mean(frame: &[f32]) -> f32 { + frame.iter().sum::() / frame.len() as f32 +} + pub fn stereo(interleaved: &[f32], channels: usize) -> Vec { interleaved .chunks(channels.max(1)) .map(|frame| match frame { [mono] => [*mono; 2], [left, right] => [*left, *right], - _ => [frame.iter().sum::() / frame.len() as f32; 2], + _ => [mean(frame); 2], }) .collect() } pub fn downmix(interleaved: &[f32], channels: usize) -> Vec { - interleaved - .chunks(channels.max(1)) - .map(|frame| frame.iter().sum::() / frame.len() as f32) - .collect() + interleaved.chunks(channels.max(1)).map(mean).collect() } #[derive(Debug, Default)] diff --git a/crates/client/src/media/voice_note.rs b/crates/client/src/media/voice_note.rs index c5e238e..3253034 100644 --- a/crates/client/src/media/voice_note.rs +++ b/crates/client/src/media/voice_note.rs @@ -13,7 +13,7 @@ use ec_ogg::OggMuxer; use ec_opus::{Application, Encoder, ogg::opus_head}; use ec_probe::{Reader, decoder::AudioDecoder}; -use super::resample; +use super::{meter::rms, resample}; pub const BARS: usize = 40; const BITRATE: u32 = 32_000; @@ -26,11 +26,7 @@ pub struct Waveform { } pub fn level(samples: &[f32]) -> f32 { - if samples.is_empty() { - return 0.; - } - let mean = samples.iter().map(|sample| sample * sample).sum::() / samples.len() as f32; - let db = 10. * mean.max(f32::MIN_POSITIVE).log10(); + let db = 20. * rms(samples).max(f32::MIN_POSITIVE).log10(); ((db + RANGE_DB) / RANGE_DB).clamp(0., 1.) } @@ -62,7 +58,7 @@ pub fn waveform(path: &Path) -> Option { } let mono = resample::downmix(&interleaved, decoder.channels()); Some(Waveform { - duration: Duration::from_secs_f32(mono.len() as f32 / VOICE_SAMPLE_RATE as f32), + duration: Duration::from_secs_f32(mono.len() as f32 / decoder.sample_rate() as f32), peaks: peaks(&mono), }) } diff --git a/crates/client/src/mutes.rs b/crates/client/src/mutes.rs index 79f77c4..83b8454 100644 --- a/crates/client/src/mutes.rs +++ b/crates/client/src/mutes.rs @@ -1,15 +1,13 @@ -use std::{collections::HashSet, fs, path::Path}; +use std::collections::HashSet; -use tracing::warn; - -use crate::config_file; +use crate::{read_config, write_config}; fn prefix(account_user_id: &str) -> String { format!("{account_user_id}\t") } pub fn load(account_user_id: &str) -> HashSet { - let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) else { + let Some(content) = read_config("mutes") else { return HashSet::new(); }; let prefix = prefix(account_user_id); @@ -22,11 +20,8 @@ pub fn load(account_user_id: &str) -> HashSet { } pub fn save(account_user_id: &str, muted: &HashSet) { - let Some(path) = config_file("mutes") else { - return; - }; let prefix = prefix(account_user_id); - let mut content: String = fs::read_to_string(&path) + let mut content: String = read_config("mutes") .unwrap_or_default() .lines() .filter(|line| !line.starts_with(&prefix)) @@ -38,14 +33,5 @@ pub fn save(account_user_id: &str, muted: &HashSet) { .map(|community_id| format!("{prefix}{community_id}\n")), ); - if let Err(error) = write(&path, &content) { - warn!("save mutes failed: {error}"); - } -} - -fn write(path: &Path, content: &str) -> std::io::Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - fs::write(path, content) + write_config("mutes", &content); } diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index a88c908..6e5c090 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -1,5 +1,6 @@ use std::{ collections::HashMap, + future::Future, path::{Path, PathBuf}, sync::{Arc, Mutex}, time::Duration, @@ -28,9 +29,9 @@ use common::{ share::{Fps, Kind, Quality, Resolution, Source}, validate::{ validate_attachment_name, validate_attachment_size, validate_avatar_size, - validate_community_name, validate_forward, validate_message_body, validate_new_message, - validate_password, validate_poll, validate_reason, validate_server_settings, - validate_status, validate_username, + validate_community_name, validate_forward, validate_new_message, validate_password, + validate_poll, validate_reason, validate_server_settings, validate_status, + validate_username, }, }; use quinn::Endpoint; @@ -48,7 +49,7 @@ use tracing::{info, warn}; use crate::{ ClientConfig, - settings::{SHARE_QUALITY, ShareSettings, VoiceSettings}, + settings::{ShareSettings, VoiceSettings}, share::{ audio::AudioApp, audio_capture, @@ -83,6 +84,20 @@ type SharedSettings = Arc>; type SharedShare = Arc>; type SharedShareSettings = Arc>; +#[derive(Clone, Default)] +struct Shared { + voice: SharedVoice, + mic_test: SharedVoice, + voice_settings: SharedSettings, + share: SharedShare, + share_settings: SharedShareSettings, +} + +fn hang_up(shared: &Shared) { + shared.voice.lock().unwrap().take(); + *shared.share.lock().unwrap() = Share::default(); +} + #[derive(Default)] pub struct Levels { pub voice: Vec<(String, Vec)>, @@ -98,10 +113,6 @@ struct Share { } impl Share { - fn clear(shared: &SharedShare) { - *shared.lock().unwrap() = Share::default(); - } - fn event(&mut self, event: &Event) { match event { Event::ShareLayers { kind, layers } => { @@ -196,11 +207,16 @@ enum Command { #[derive(Clone)] pub struct NetworkHandle { command_sender: mpsc::Sender, - voice: SharedVoice, - mic_test: SharedVoice, - voice_settings: SharedSettings, - share: SharedShare, - share_settings: SharedShareSettings, + shared: Shared, +} + +macro_rules! expect { + ($response:expr, $variant:path) => { + match $response { + $variant(value) => Ok(value), + _ => Err(Error::Server), + } + }; } impl NetworkHandle { @@ -219,7 +235,7 @@ impl NetworkHandle { } fn with_voice(&self, f: impl FnOnce(&Voice) -> T) -> Option { - self.voice.lock().unwrap().as_ref().map(f) + self.shared.voice.lock().unwrap().as_ref().map(f) } async fn request(&self, request: Request) -> Result { @@ -247,15 +263,13 @@ impl NetworkHandle { } pub async fn sessions(&self, user_id: &str) -> Result, Error> { - match self - .request(Request::Sessions { + expect!( + self.request(Request::Sessions { user_id: user_id.to_string(), }) - .await? - { - Response::Sessions(sessions) => Ok(sessions), - _ => Err(Error::Server), - } + .await?, + Response::Sessions + ) } pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Error> { @@ -269,16 +283,14 @@ impl NetworkHandle { pub async fn rename_user(&self, user_id: &str, username: &str) -> Result { validate_username(username)?; - match self - .request(Request::RenameUser { + expect!( + self.request(Request::RenameUser { user_id: user_id.to_string(), username: username.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn resume(&self, token: &str) -> Result<(User, String), Error> { @@ -310,7 +322,6 @@ impl NetworkHandle { } pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Error> { - validate_username(username)?; validate_password(password)?; self.sign_in(Request::Login { @@ -327,34 +338,28 @@ impl NetworkHandle { pub async fn update_user(&self, username: &str) -> Result { validate_username(username)?; - match self - .request(Request::UpdateUser { + expect!( + self.request(Request::UpdateUser { username: username.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn delete_user(&self, user_id: &str) -> Result<(), Error> { - match self - .request(Request::DeleteUser { + expect!( + self.request(Request::DeleteUser { user_id: user_id.to_string(), }) - .await? - { - Response::User(_) => Ok(()), - _ => Err(Error::Server), - } + .await?, + Response::User + ) + .map(|_| ()) } pub async fn users(&self) -> Result, Error> { - match self.request(Request::Users).await? { - Response::Users(accounts) => Ok(accounts), - _ => Err(Error::Server), - } + expect!(self.request(Request::Users).await?, Response::Users) } pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Error> { @@ -390,10 +395,10 @@ impl NetworkHandle { } pub async fn server_bans(&self) -> Result, Error> { - match self.request(Request::ServerBans).await? { - Response::ServerBans(bans) => Ok(bans), - _ => Err(Error::Server), - } + expect!( + self.request(Request::ServerBans).await?, + Response::ServerBans + ) } pub async fn remove_server_ban(&self, id: &str) -> Result<(), Error> { @@ -406,20 +411,18 @@ impl NetworkHandle { uses: u32, hours: Option, ) -> Result { - match self - .request(Request::CreateInviteCode { uses, hours }) - .await? - { - Response::InviteCode(code) => Ok(code), - _ => Err(Error::Server), - } + expect!( + self.request(Request::CreateInviteCode { uses, hours }) + .await?, + Response::InviteCode + ) } pub async fn invite_codes(&self) -> Result, Error> { - match self.request(Request::InviteCodes).await? { - Response::InviteCodes(codes) => Ok(codes), - _ => Err(Error::Server), - } + expect!( + self.request(Request::InviteCodes).await?, + Response::InviteCodes + ) } pub async fn delete_invite_code(&self, code: &str) -> Result<(), Error> { @@ -447,28 +450,24 @@ impl NetworkHandle { } pub async fn clear_profile(&self, user_id: &str) -> Result { - match self - .request(Request::ClearProfile { + expect!( + self.request(Request::ClearProfile { user_id: user_id.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn set_role(&self, user_id: &str, role: Role) -> Result { - match self - .request(Request::SetRole { + expect!( + self.request(Request::SetRole { user_id: user_id.to_string(), role, }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn admin_logs( @@ -486,24 +485,21 @@ impl NetworkHandle { after_ms, before_ms, }; - match self.request(request).await? { - Response::AdminLogs(entries) => Ok(entries), - _ => Err(Error::Server), - } + expect!(self.request(request).await?, Response::AdminLogs) } pub async fn daily_stats(&self, days: u32) -> Result, Error> { - match self.request(Request::DailyStats { days }).await? { - Response::DailyStats(stats) => Ok(stats), - _ => Err(Error::Server), - } + expect!( + self.request(Request::DailyStats { days }).await?, + Response::DailyStats + ) } pub async fn server_settings(&self) -> Result { - match self.request(Request::ServerSettings).await? { - Response::ServerSettings(settings) => Ok(settings), - _ => Err(Error::Server), - } + expect!( + self.request(Request::ServerSettings).await?, + Response::ServerSettings + ) } pub async fn update_server_settings( @@ -512,43 +508,36 @@ impl NetworkHandle { ) -> Result { validate_server_settings(&settings)?; - match self - .request(Request::UpdateServerSettings { settings }) - .await? - { - Response::ServerSettings(settings) => Ok(settings), - _ => Err(Error::Server), - } + expect!( + self.request(Request::UpdateServerSettings { settings }) + .await?, + Response::ServerSettings + ) } pub async fn create_user(&self, username: &str, password: &str) -> Result { validate_username(username)?; validate_password(password)?; - match self - .request(Request::CreateUser { + expect!( + self.request(Request::CreateUser { username: username.to_string(), password: password.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn overview(&self) -> Result { - match self.request(Request::Overview).await? { - Response::Overview(overview) => Ok(overview), - _ => Err(Error::Server), - } + expect!(self.request(Request::Overview).await?, Response::Overview) } pub async fn all_communities(&self) -> Result, Error> { - match self.request(Request::AllCommunities).await? { - Response::AllCommunities(summaries) => Ok(summaries), - _ => Err(Error::Server), - } + expect!( + self.request(Request::AllCommunities).await?, + Response::AllCommunities + ) } pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Error> { @@ -560,29 +549,25 @@ impl NetworkHandle { } pub async fn read_user(&self, user_id: &str) -> Result { - match self - .request(Request::ReadUser { + expect!( + self.request(Request::ReadUser { user_id: user_id.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn create_community(&self, name: &str) -> Result { validate_community_name(name)?; - match self - .request(Request::CreateCommunity { + expect!( + self.request(Request::CreateCommunity { name: name.to_string(), }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub async fn update_community( @@ -592,28 +577,25 @@ impl NetworkHandle { ) -> Result { validate_community_name(name)?; - match self - .request(Request::UpdateCommunity { + expect!( + self.request(Request::UpdateCommunity { community_id: community_id.to_string(), name: name.to_string(), }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub async fn delete_community(&self, community_id: &str) -> Result<(), Error> { - match self - .request(Request::DeleteCommunity { + expect!( + self.request(Request::DeleteCommunity { community_id: community_id.to_string(), }) - .await? - { - Response::Community(_) => Ok(()), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) + .map(|_| ()) } pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { @@ -624,22 +606,20 @@ impl NetworkHandle { } pub async fn communities(&self) -> Result, Error> { - match self.request(Request::Communities).await? { - Response::Communities(communities) => Ok(communities), - _ => Err(Error::Server), - } + expect!( + self.request(Request::Communities).await?, + Response::Communities + ) } pub async fn members(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::Members { + expect!( + self.request(Request::Members { community_id: community_id.to_string(), }) - .await? - { - Response::Members(members) => Ok(members), - _ => Err(Error::Server), - } + .await?, + Response::Members + ) } pub async fn kick( @@ -681,27 +661,23 @@ impl NetworkHandle { } pub async fn bans(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::Bans { + expect!( + self.request(Request::Bans { community_id: community_id.to_string(), }) - .await? - { - Response::Bans(users) => Ok(users), - _ => Err(Error::Server), - } + .await?, + Response::Bans + ) } pub async fn logs(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::Logs { + expect!( + self.request(Request::Logs { community_id: community_id.to_string(), }) - .await? - { - Response::Logs(entries) => Ok(entries), - _ => Err(Error::Server), - } + .await?, + Response::Logs + ) } pub async fn set_rank( @@ -719,15 +695,14 @@ impl NetworkHandle { } pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> { - match self - .request(Request::DeleteMessage { + expect!( + self.request(Request::DeleteMessage { message_id: message_id.to_string(), }) - .await? - { - Response::Message(_) => Ok(()), - _ => Err(Error::Server), - } + .await?, + Response::Message + ) + .map(|_| ()) } pub async fn create_message( @@ -739,33 +714,29 @@ impl NetworkHandle { ) -> Result { validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; - match self - .request(Request::CreateMessage { + expect!( + self.request(Request::CreateMessage { community_id: community_id.to_string(), body: body.to_string(), attachments, reply_to, }) - .await? - { - Response::Message(message) => Ok(message), - _ => Err(Error::Server), - } + .await?, + Response::Message + ) } pub async fn update_message(&self, message_id: &str, body: &str) -> Result { - validate_message_body(body, MAXIMUM_MESSAGE_LENGTH)?; + validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; - match self - .request(Request::UpdateMessage { + expect!( + self.request(Request::UpdateMessage { message_id: message_id.to_string(), body: body.to_string(), }) - .await? - { - Response::Message(message) => Ok(message), - _ => Err(Error::Server), - } + .await?, + Response::Message + ) } pub async fn forward_messages( @@ -776,64 +747,50 @@ impl NetworkHandle { ) -> Result, Error> { validate_forward(message_ids.len())?; - match self - .request(Request::ForwardMessages { + expect!( + self.request(Request::ForwardMessages { message_ids, community_id: community_id.to_string(), snippet, }) - .await? - { - Response::Messages(messages) => Ok(messages), - _ => Err(Error::Server), - } + .await?, + Response::Messages + ) } pub async fn find_user(&self, username: &str) -> Result { - validate_username(username)?; - - match self - .request(Request::FindUser { + expect!( + self.request(Request::FindUser { username: username.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn open_notes(&self) -> Result { - match self.request(Request::OpenNotes).await? { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + expect!(self.request(Request::OpenNotes).await?, Response::Community) } pub async fn open_direct(&self, user_id: &str) -> Result { - match self - .request(Request::OpenDirect { + expect!( + self.request(Request::OpenDirect { user_id: user_id.to_string(), }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub async fn friends(&self) -> Result { - match self.request(Request::Friends).await? { - Response::Friends(friends) => Ok(friends), - _ => Err(Error::Server), - } + expect!(self.request(Request::Friends).await?, Response::Friends) } pub async fn read_presences(&self) -> Result, Error> { - match self.request(Request::ReadPresences).await? { - Response::Presences(presences) => Ok(presences), - _ => Err(Error::Server), - } + expect!( + self.request(Request::ReadPresences).await?, + Response::Presences + ) } pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> { @@ -870,22 +827,20 @@ impl NetworkHandle { } pub async fn invitations(&self) -> Result, Error> { - match self.request(Request::Invitations).await? { - Response::Invitations(invitations) => Ok(invitations), - _ => Err(Error::Server), - } + expect!( + self.request(Request::Invitations).await?, + Response::Invitations + ) } pub async fn accept_invitation(&self, community_id: &str) -> Result { - match self - .request(Request::AcceptInvitation { + expect!( + self.request(Request::AcceptInvitation { community_id: community_id.to_string(), }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Error> { @@ -919,15 +874,13 @@ impl NetworkHandle { } pub async fn pins(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::Pins { + expect!( + self.request(Request::Pins { community_id: community_id.to_string(), }) - .await? - { - Response::Messages(messages) => Ok(messages), - _ => Err(Error::Server), - } + .await?, + Response::Messages + ) } pub async fn create_poll( @@ -939,18 +892,16 @@ impl NetworkHandle { ) -> Result { validate_poll(question, &options)?; - match self - .request(Request::CreatePoll { + expect!( + self.request(Request::CreatePoll { community_id: community_id.to_string(), question: question.to_string(), options, multiple, }) - .await? - { - Response::Message(message) => Ok(message), - _ => Err(Error::Server), - } + .await?, + Response::Message + ) } pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Error> { @@ -989,10 +940,10 @@ impl NetworkHandle { } pub async fn reports(&self, status: Option) -> Result, Error> { - match self.request(Request::Reports { status }).await? { - Response::Reports(reports) => Ok(reports), - _ => Err(Error::Server), - } + expect!( + self.request(Request::Reports { status }).await?, + Response::Reports + ) } pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Error> { @@ -1011,19 +962,17 @@ impl NetworkHandle { after_ms: Option, before_ms: Option, ) -> Result, Error> { - match self - .request(Request::SearchMessages { + expect!( + self.request(Request::SearchMessages { text, user_id, community_id, after_ms, before_ms, }) - .await? - { - Response::MessageHits(hits) => Ok(hits), - _ => Err(Error::Server), - } + .await?, + Response::MessageHits + ) } pub async fn search_community( @@ -1031,13 +980,11 @@ impl NetworkHandle { community_id: String, text: String, ) -> Result, Error> { - match self - .request(Request::SearchCommunity { community_id, text }) - .await? - { - Response::MessageHits(hits) => Ok(hits), - _ => Err(Error::Server), - } + expect!( + self.request(Request::SearchCommunity { community_id, text }) + .await?, + Response::MessageHits + ) } pub async fn storage_usage(&self) -> Result<(Vec, Vec), Error> { @@ -1048,17 +995,11 @@ impl NetworkHandle { } pub async fn create_backup(&self) -> Result { - match self.request(Request::CreateBackup).await? { - Response::Backup(backup) => Ok(backup), - _ => Err(Error::Server), - } + expect!(self.request(Request::CreateBackup).await?, Response::Backup) } pub async fn backups(&self) -> Result, Error> { - match self.request(Request::Backups).await? { - Response::Backups(backups) => Ok(backups), - _ => Err(Error::Server), - } + expect!(self.request(Request::Backups).await?, Response::Backups) } pub async fn delete_backup(&self, name: &str) -> Result<(), Error> { @@ -1073,16 +1014,14 @@ impl NetworkHandle { user_id: Option, community_id: Option, ) -> Result, Error> { - match self - .request(Request::AllAttachments { + expect!( + self.request(Request::AllAttachments { user_id, community_id, }) - .await? - { - Response::AttachmentInfos(infos) => Ok(infos), - _ => Err(Error::Server), - } + .await?, + Response::AttachmentInfos + ) } pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Error> { @@ -1148,23 +1087,18 @@ impl NetworkHandle { community_id: &str, before: Option<&str>, ) -> Result, Error> { - match self - .request(Request::ReadMessages { + expect!( + self.request(Request::ReadMessages { community_id: community_id.to_string(), before: before.map(str::to_string), }) - .await? - { - Response::Messages(messages) => Ok(messages), - _ => Err(Error::Server), - } + .await?, + Response::Messages + ) } pub async fn unreads(&self) -> Result, Error> { - match self.request(Request::Unreads).await? { - Response::Unreads(unreads) => Ok(unreads), - _ => Err(Error::Server), - } + expect!(self.request(Request::Unreads).await?, Response::Unreads) } pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> { @@ -1178,24 +1112,22 @@ impl NetworkHandle { pub async fn update_status(&self, status: &str) -> Result { validate_status(status)?; - match self - .request(Request::UpdateStatus { + expect!( + self.request(Request::UpdateStatus { status: status.to_string(), }) - .await? - { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + .await?, + Response::User + ) } pub async fn update_avatar(&self, bytes: Vec) -> Result { validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; - match self.request(Request::UpdateAvatar { image: bytes }).await? { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + expect!( + self.request(Request::UpdateAvatar { image: bytes }).await?, + Response::User + ) } pub async fn update_community_avatar( @@ -1207,47 +1139,38 @@ impl NetworkHandle { validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; } - match self - .request(Request::UpdateCommunityAvatar { + expect!( + self.request(Request::UpdateCommunityAvatar { community_id: community_id.to_string(), image, }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub async fn remove_avatar(&self) -> Result { - match self.request(Request::RemoveAvatar).await? { - Response::User(user) => Ok(user), - _ => Err(Error::Server), - } + expect!(self.request(Request::RemoveAvatar).await?, Response::User) } pub async fn read_avatar(&self, avatar_id: &str) -> Result, Error> { - match self - .request(Request::ReadAvatar { + expect!( + self.request(Request::ReadAvatar { avatar_id: avatar_id.to_string(), }) - .await? - { - Response::Avatar(bytes) => Ok(bytes), - _ => Err(Error::Server), - } + .await?, + Response::Avatar + ) } pub async fn join_voice(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::JoinVoice { + expect!( + self.request(Request::JoinVoice { community_id: community_id.to_string(), }) - .await? - { - Response::Voice(participants) => Ok(participants), - _ => Err(Error::Server), - } + .await?, + Response::Voice + ) } pub async fn typing(&self, community_id: &str) -> Result<(), Error> { @@ -1262,34 +1185,30 @@ impl NetworkHandle { } pub async fn read_community(&self, community_id: &str) -> Result { - match self - .request(Request::ReadCommunity { + expect!( + self.request(Request::ReadCommunity { community_id: community_id.to_string(), }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub async fn voice_participants(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::VoiceParticipants { + expect!( + self.request(Request::VoiceParticipants { community_id: community_id.to_string(), }) - .await? - { - Response::Voice(participants) => Ok(participants), - _ => Err(Error::Server), - } + .await?, + Response::Voice + ) } pub async fn voice_rooms(&self) -> Result, Error> { - match self.request(Request::VoiceRooms).await? { - Response::VoiceRooms(rooms) => Ok(rooms), - _ => Err(Error::Server), - } + expect!( + self.request(Request::VoiceRooms).await?, + Response::VoiceRooms + ) } pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> { @@ -1316,56 +1235,60 @@ impl NetworkHandle { community_id: &str, enabled: bool, ) -> Result { - match self - .request(Request::SetCommunityVoice { + expect!( + self.request(Request::SetCommunityVoice { community_id: community_id.to_string(), enabled, }) - .await? - { - Response::Community(community) => Ok(community), - _ => Err(Error::Server), - } + .await?, + Response::Community + ) } pub fn set_voice_settings(&self, settings: VoiceSettings) { - *self.voice_settings.lock().unwrap() = settings.clone(); + *self.shared.voice_settings.lock().unwrap() = settings.clone(); - if let Some(voice) = self.voice.lock().unwrap().as_mut() { + if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() { voice.apply(&settings); } - if let Some(voice) = self.mic_test.lock().unwrap().as_mut() { + if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() { voice.apply(&settings); } } pub fn start_mic_test(&self) { - if self.voice.lock().unwrap().is_some() { + if self.shared.voice.lock().unwrap().is_some() { return; } - let settings = self.voice_settings.lock().unwrap().clone(); - *self.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); + let settings = self.shared.voice_settings.lock().unwrap().clone(); + *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); } pub fn play_chime(&self) { - voice::play_chime(&self.voice_settings.lock().unwrap()); + voice::play_chime(&self.shared.voice_settings.lock().unwrap()); } pub fn play_notification(&self) { - voice::play_yumush(&self.voice_settings.lock().unwrap()); + voice::play_yumush(&self.shared.voice_settings.lock().unwrap()); } pub fn play_ring(&self) { - voice::play_ring(&self.voice_settings.lock().unwrap()); + voice::play_ring(&self.shared.voice_settings.lock().unwrap()); } pub fn stop_mic_test(&self) { - self.mic_test.lock().unwrap().take(); + self.shared.mic_test.lock().unwrap().take(); } pub fn voice_level_db(&self) -> Option { - self.with_voice(Voice::level_db) - .or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db)) + self.with_voice(Voice::level_db).or_else(|| { + self.shared + .mic_test + .lock() + .unwrap() + .as_ref() + .map(Voice::level_db) + }) } pub fn voice_sample(&self) -> Option { @@ -1385,7 +1308,7 @@ impl NetworkHandle { } pub fn levels(&self) -> Levels { - let share = self.share.lock().unwrap(); + let share = self.shared.share.lock().unwrap(); Levels { voice: self.with_voice(Voice::levels).unwrap_or_default(), watching: share @@ -1407,7 +1330,7 @@ impl NetworkHandle { } async fn start(&self, kind: Kind) -> Result<(), Error> { - let settings = self.share_settings.lock().unwrap().clone(); + let settings = self.shared.share_settings.lock().unwrap().clone(); self.ask(|reply| Command::StartShare { kind, settings, @@ -1417,7 +1340,7 @@ impl NetworkHandle { } pub async fn update_share(&self) -> Result<(), Error> { - let settings = self.share_settings.lock().unwrap().clone(); + let settings = self.shared.share_settings.lock().unwrap().clone(); self.ask(|reply| Command::UpdateShare { settings, reply }) .await } @@ -1432,14 +1355,15 @@ impl NetworkHandle { async fn stop(&self, kind: Kind) -> Result<(), Error> { let result = self.done(Request::StopShare { kind }).await; - let mut share = self.share.lock().unwrap(); + let mut share = self.shared.share.lock().unwrap(); share.sharing.remove(&kind); share.sources.remove(&kind); result } pub fn sharing(&self) -> bool { - self.share + self.shared + .share .lock() .unwrap() .sharing @@ -1447,7 +1371,8 @@ impl NetworkHandle { } pub fn camera_on(&self) -> bool { - self.share + self.shared + .share .lock() .unwrap() .sharing @@ -1455,7 +1380,8 @@ impl NetworkHandle { } pub fn share_source(&self) -> Option { - self.share + self.shared + .share .lock() .unwrap() .sources @@ -1464,15 +1390,13 @@ impl NetworkHandle { } pub async fn shares(&self, community_id: &str) -> Result, Error> { - match self - .request(Request::Shares { + expect!( + self.request(Request::Shares { community_id: community_id.to_string(), }) - .await? - { - Response::Shares(shares) => Ok(shares), - _ => Err(Error::Server), - } + .await?, + Response::Shares + ) } pub async fn watch_share( @@ -1481,15 +1405,13 @@ impl NetworkHandle { kind: Kind, watch: WatchQuality, ) -> Result<(), Error> { - let quality = match watch { - WatchQuality::Fixed(quality) => quality, - WatchQuality::Auto => SHARE_QUALITY, - }; - let volume = self.share_settings.lock().unwrap().volume; - let choice = self.voice_settings.lock().unwrap().choice.clone(); + let volume = self.shared.share_settings.lock().unwrap().volume; + let choice = self.shared.voice_settings.lock().unwrap().choice.clone(); let key = (user_id.to_string(), kind); let watching = Watching::new(kind, watch, volume, choice); - self.share + let quality = watching.wanted(); + self.shared + .share .lock() .unwrap() .watching @@ -1504,13 +1426,14 @@ impl NetworkHandle { }) .await; if result.is_err() { - self.share.lock().unwrap().watching.remove(&key); + self.shared.share.lock().unwrap().watching.remove(&key); } result } pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Error> { - self.share + self.shared + .share .lock() .unwrap() .watching @@ -1524,6 +1447,7 @@ impl NetworkHandle { pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { if let Some(watching) = self + .shared .share .lock() .unwrap() @@ -1535,7 +1459,7 @@ impl NetworkHandle { } pub fn share_sample(&self) -> ShareSample { - let mut share = self.share.lock().unwrap(); + let mut share = self.shared.share.lock().unwrap(); ShareSample { sending: share .sharing @@ -1552,7 +1476,8 @@ impl NetworkHandle { } pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option { - self.share + self.shared + .share .lock() .unwrap() .watching @@ -1563,12 +1488,13 @@ impl NetworkHandle { pub fn set_share_settings(&self, settings: ShareSettings) -> bool { let changed = self.sharing() && self + .shared .share_settings .lock() .unwrap() .encoding_differs(&settings); - *self.share_settings.lock().unwrap() = settings.clone(); - for ((_, kind), watching) in self.share.lock().unwrap().watching.iter_mut() { + *self.shared.share_settings.lock().unwrap() = settings.clone(); + for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() { if *kind == Kind::Screen { watching.set_volume(settings.volume); watching.set_quality(settings.watch); @@ -1585,33 +1511,18 @@ impl NetworkHandle { pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver) { let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); - let voice: SharedVoice = Arc::new(Mutex::new(None)); - let mic_test: SharedVoice = Arc::new(Mutex::new(None)); - let voice_settings: SharedSettings = Arc::new(Mutex::new(VoiceSettings::default())); - let share: SharedShare = Arc::new(Mutex::new(Share::default())); - let share_settings: SharedShareSettings = Arc::new(Mutex::new(ShareSettings::default())); + let shared = Shared::default(); std::thread::Builder::new() .name("network".to_string()) .spawn({ - let voice = voice.clone(); - let mic_test = mic_test.clone(); - let voice_settings = voice_settings.clone(); - let share = share.clone(); + let shared = shared.clone(); move || { tokio::runtime::Builder::new_current_thread() .enable_all() .build() .expect("network runtime") - .block_on(actor( - client_config, - command_receiver, - event_sender, - voice, - mic_test, - voice_settings, - share, - )); + .block_on(actor(client_config, command_receiver, event_sender, shared)); } }) .expect("network thread"); @@ -1619,11 +1530,7 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver Result Result<(), Error> { + match send(connection, &request).await? { + Response::Done => Ok(()), + Response::Error(error) => Err(error), + _ => Err(Error::Server), + } +} + async fn send_body( send_stream: &mut quinn::SendStream, file: &mut tokio::fs::File, @@ -1843,26 +1758,22 @@ async fn download( Ok(bytes) } -async fn dispatch( - connection: quinn::Connection, - request: Request, - reply: oneshot::Sender>, +fn answer( + reply: oneshot::Sender>, + work: impl Future> + Send + 'static, ) { - let _ = reply.send(send(&connection, &request).await); + tokio::spawn(async move { + let _ = reply.send(work.await); + }); } async fn actor( client_config: ClientConfig, mut command_receiver: mpsc::Receiver, event_sender: mpsc::Sender, - voice: SharedVoice, - mic_test: SharedVoice, - voice_settings: SharedSettings, - share: SharedShare, + shared: Shared, ) { let mut token: Option = None; - let mut token_epoch = 0; - let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE); 'session: loop { let connection = loop { match connect(&client_config).await { @@ -1887,8 +1798,13 @@ async fn actor( let request = Request::Resume { token: stored }; match send(&connection, &request).await { Ok(Response::Session { token: resumed, .. }) => token = Some(resumed), - _ => { - warn!("session resume failed"); + Err(error) => { + warn!("session resume failed: {error}"); + tokio::time::sleep(RECONNECT_DELAY).await; + continue 'session; + } + Ok(_) => { + warn!("session resume rejected"); token = None; if event_sender.send(NetworkEvent::SessionLost).await.is_err() { @@ -1906,13 +1822,9 @@ async fn actor( tokio::spawn(event_receive_loop( connection.clone(), event_sender.clone(), - share.clone(), - )); - tokio::spawn(datagram_receive_loop( - connection.clone(), - voice.clone(), - share.clone(), + shared.share.clone(), )); + tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone())); let mut ticker = tokio::time::interval(SHARE_TICK); loop { @@ -1920,103 +1832,79 @@ async fn actor( command = command_receiver.recv() => match command { Some(Command::Request { request, reply }) => match &request { Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { - voice.lock().unwrap().take(); - Share::clear(&share); - let token_sender = token_sender.clone(); - let epoch = token_epoch; - let connection = connection.clone(); - - tokio::spawn(async move { - let response = send(&connection, &request).await; - if let Ok(Response::Session { token: session_token, .. }) = &response { - let _ = token_sender.send((epoch, session_token.clone())).await; - } + hang_up(&shared); - let _ = reply.send(response); - }); + let response = send(&connection, &request).await; + if let Ok(Response::Session { token: session_token, .. }) = &response { + token = Some(session_token.clone()); + } + let _ = reply.send(response); } Request::Logout | Request::Detach => { token = None; - token_epoch += 1; - voice.lock().unwrap().take(); - Share::clear(&share); + hang_up(&shared); - tokio::spawn(dispatch(connection.clone(), request, reply)); + let connection = connection.clone(); + answer(reply, async move { send(&connection, &request).await }); } Request::JoinVoice { .. } => { - let voice = voice.clone(); - let mic_test = mic_test.clone(); - let settings = voice_settings.lock().unwrap().clone(); + let shared = shared.clone(); + let settings = shared.voice_settings.lock().unwrap().clone(); let connection = connection.clone(); - tokio::spawn(async move { + answer(reply, async move { let response = send(&connection, &request).await; if let Ok(Response::Voice(_)) = &response { - mic_test.lock().unwrap().take(); - *voice.lock().unwrap() = + shared.mic_test.lock().unwrap().take(); + *shared.voice.lock().unwrap() = Some(voice::start(Some(connection), &settings)); } - - let _ = reply.send(response); + response }); } Request::LeaveVoice => { - voice.lock().unwrap().take(); - Share::clear(&share); + hang_up(&shared); - tokio::spawn(dispatch(connection.clone(), request, reply)); + let connection = connection.clone(); + answer(reply, async move { send(&connection, &request).await }); } _ => { - tokio::spawn(dispatch(connection.clone(), request, reply)); + let connection = connection.clone(); + answer(reply, async move { send(&connection, &request).await }); } }, Some(Command::StartShare { kind, settings, reply }) => { let connection = connection.clone(); - let share = share.clone(); + let share = shared.share.clone(); - tokio::spawn(async move { - let _ = reply.send(start_share(&connection, &share, kind, &settings).await); - }); + answer(reply, async move { start_share(&connection, &share, kind, &settings).await }); } Some(Command::UpdateShare { settings, reply }) => { let connection = connection.clone(); - let share = share.clone(); + let share = shared.share.clone(); - tokio::spawn(async move { - let _ = reply.send(update_share(&connection, &share, &settings).await); - }); + answer(reply, async move { update_share(&connection, &share, &settings).await }); } Some(Command::Upload { community_id, path, maximum, reply }) => { let connection = connection.clone(); - tokio::spawn(async move { - let _ = reply.send(upload(&connection, &community_id, &path, maximum).await); - }); + answer(reply, async move { upload(&connection, &community_id, &path, maximum).await }); } Some(Command::Download { attachment_id, thumbnail, reply }) => { let connection = connection.clone(); - tokio::spawn(async move { - let _ = reply.send(download(&connection, &attachment_id, thumbnail).await); - }); + answer(reply, async move { download(&connection, &attachment_id, thumbnail).await }); } Some(Command::BackupDownload { name, path, reply }) => { let connection = connection.clone(); - tokio::spawn(async move { - let _ = reply.send(backup_download(&connection, &name, &path).await); - }); + answer(reply, async move { backup_download(&connection, &name, &path).await }); } None => break 'session, }, - Some((epoch, session_token)) = token_receiver.recv() => { - if epoch == token_epoch { - token = Some(session_token); - } - } _ = ticker.tick() => { - let requests = share.lock().unwrap().ticks(); + let requests = shared.share.lock().unwrap().ticks(); for request in requests { let connection = connection.clone(); tokio::spawn(async move { @@ -2027,8 +1915,7 @@ async fn actor( error = connection.closed() => { warn!("disconnected: {error}"); - voice.lock().unwrap().take(); - Share::clear(&share); + hang_up(&shared); if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { return; @@ -2066,11 +1953,7 @@ async fn start_share( share.sources.insert(kind, source.clone()); } - let result = match send(connection, &Request::StartShare { kind, source }).await { - Ok(Response::Done) => Ok(()), - Ok(_) => Err(Error::Server), - Err(error) => Err(error), - }; + let result = done(connection, Request::StartShare { kind, source }).await; if result.is_err() { let mut share = share.lock().unwrap(); share.sharing.remove(&kind); @@ -2104,19 +1987,14 @@ async fn update_share( .sources .insert(Kind::Screen, source.clone()); - match send( + done( connection, - &Request::StartShare { + Request::StartShare { kind: Kind::Screen, source, }, ) .await - { - Ok(Response::Done) => Ok(()), - Ok(_) => Err(Error::Server), - Err(error) => Err(error), - } } async fn event_receive_loop( @@ -2140,18 +2018,14 @@ async fn event_receive_loop( } } -async fn datagram_receive_loop( - connection: quinn::Connection, - voice: SharedVoice, - share: SharedShare, -) { +async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) { let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") .ok() .and_then(|value| value.parse().ok()) .unwrap_or(0); let mut received: u64 = 0; while let Ok(datagram) = connection.read_datagram().await { - if let Some(voice) = voice.lock().unwrap().as_ref() { + if let Some(voice) = shared.voice.lock().unwrap().as_ref() { voice.receive(&datagram); } if let Some((user_id, packet)) = decode_relay(&datagram) { @@ -2165,7 +2039,7 @@ async fn datagram_receive_loop( Datagram::Video(fragment) => fragment.kind, _ => Kind::Screen, }; - if let Some(watching) = share.lock().unwrap().watching.get(&(user_id, kind)) { + if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) { watching.receive(packet); } } diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index d67a96e..bc9f456 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -1,4 +1,4 @@ -use std::{collections::BTreeMap, fmt::Display, fs, ops::RangeInclusive}; +use std::{collections::BTreeMap, fmt::Display, ops::RangeInclusive}; use common::{ config::Config, @@ -10,12 +10,12 @@ use gpui_kit::{ component::{Theme, ThemeMode}, px, }; -use tracing::warn; use crate::{ - config_file, + read_config, share::{audio::AudioMode, encode::capabilities, session::WatchQuality}, voice::audio::Choice, + write_config, }; pub const SHARE_QUALITY: Quality = Quality { @@ -197,6 +197,18 @@ pub struct Settings { pub close_to_tray: bool, } +impl Default for Settings { + fn default() -> Self { + Self { + theme: ThemeChoice::Dark, + font_size: FontSize::Medium, + voice: VoiceSettings::default(), + share: ShareSettings::default(), + close_to_tray: true, + } + } +} + fn quality_text(quality: Quality) -> String { format!("{}p{}", quality.resolution.height(), quality.fps.value()) } @@ -215,9 +227,7 @@ fn parse_quality(text: &str) -> Option { } pub fn load() -> Settings { - let config = config_file("settings") - .and_then(|path| fs::read_to_string(path).ok()) - .and_then(|content| Config::parse(&content).ok()); + let config = read_config("settings").and_then(|content| Config::parse(&content).ok()); let text = |key: &str| { config .as_ref() @@ -231,25 +241,25 @@ pub fn load() -> Settings { .unwrap_or(default) }; - let defaults = VoiceSettings::default(); + let defaults = Settings::default(); let voice = VoiceSettings { sensitivity_db: number( "voice.sensitivity", - defaults.sensitivity_db, + defaults.voice.sensitivity_db, &SENSITIVITY_DB, ), - input_volume: number("voice.input_volume", defaults.input_volume, &VOLUME), - output_volume: number("voice.output_volume", defaults.output_volume, &VOLUME), + input_volume: number("voice.input_volume", defaults.voice.input_volume, &VOLUME), + output_volume: number("voice.output_volume", defaults.voice.output_volume, &VOLUME), choice: Choice { input: text("voice.input"), output: text("voice.output"), }, activation: text("voice.activation") .and_then(|value| Activation::parse(&value)) - .unwrap_or(Activation::VoiceActivity), + .unwrap_or(defaults.voice.activation), profile: text("voice.profile") .and_then(|value| Profile::parse(&value)) - .unwrap_or(Profile::Voice), + .unwrap_or(defaults.voice.profile), push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), user_volumes: text("voice.user_volumes") .map(|value| { @@ -265,11 +275,10 @@ pub fn load() -> Settings { .unwrap_or_default(), }; - let share_defaults = ShareSettings::default(); let share = ShareSettings { top: text("share.top") .and_then(|value| parse_quality(&value)) - .unwrap_or(share_defaults.top), + .unwrap_or(defaults.share.top), codec: text("share.codec") .and_then(|value| Codec::parse(&value)) .map_or(ShareCodec::Auto, ShareCodec::Only), @@ -281,24 +290,25 @@ pub fn load() -> Settings { _ => ShareAudio::Everything, }, excluded: text("share.excluded") - .map(|value| value.split(',').map(str::to_string).collect()) + .map(|value| value.split('\t').map(str::to_string).collect()) .unwrap_or_default(), watch: text("share.watch") .and_then(|value| parse_quality(&value)) .map_or(WatchQuality::Auto, WatchQuality::Fixed), - volume: number("share.volume", share_defaults.volume, &VOLUME), + volume: number("share.volume", defaults.share.volume, &VOLUME), }; Settings { theme: text("theme") .and_then(|value| ThemeChoice::parse(&value)) - .unwrap_or(ThemeChoice::Dark), + .unwrap_or(defaults.theme), font_size: text("font_size") .and_then(|value| FontSize::parse(&value)) - .unwrap_or(FontSize::Medium), + .unwrap_or(defaults.font_size), voice, share, - close_to_tray: text("close_to_tray").is_none_or(|value| value != "false"), + close_to_tray: text("close_to_tray") + .map_or(defaults.close_to_tray, |value| value != "false"), } } @@ -307,12 +317,7 @@ fn line(key: &str, value: impl Display) -> String { } pub fn save(settings: &Settings) { - let Some(path) = config_file("settings") else { - return; - }; - let voice = &settings.voice; - let key = voice.push_to_talk_key.as_str(); let share = &settings.share; let (audio, source) = match &share.audio { ShareAudio::Off => ("off", ""), @@ -340,7 +345,7 @@ pub fn save(settings: &Settings) { ), line("voice.activation", voice.activation.as_str()), line("voice.profile", voice.profile.as_str()), - line("voice.push_to_talk", key), + line("voice.push_to_talk", &voice.push_to_talk_key), line( "voice.user_volumes", voice @@ -360,20 +365,13 @@ pub fn save(settings: &Settings) { ), line("share.audio", audio), line("share.audio_source", source), - line("share.excluded", share.excluded.join(",")), + line("share.excluded", share.excluded.join("\t")), line("share.watch", watch), line("share.volume", share.volume), ] .concat(); - let result = path - .parent() - .map_or(Ok(()), fs::create_dir_all) - .and_then(|()| fs::write(&path, content)); - - if let Err(error) = result { - warn!("save settings failed: {error}"); - } + write_config("settings", &content); } pub fn apply(choice: ThemeChoice, font_size: FontSize, cx: &mut App) { diff --git a/crates/client/src/share/audio_capture.rs b/crates/client/src/share/audio_capture.rs index 3893768..042ccec 100644 --- a/crates/client/src/share/audio_capture.rs +++ b/crates/client/src/share/audio_capture.rs @@ -4,11 +4,7 @@ use std::{ error::Error, process, rc::Rc, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, - thread::JoinHandle, + sync::atomic::{AtomicBool, Ordering}, time::Duration, }; @@ -28,9 +24,9 @@ use spa::{pod::Pod, utils::dict::DictRef}; use tracing::warn; use super::audio::{AudioApp, AudioKind, AudioMode}; +use crate::voice::audio::{Worker, supervise}; const STOP_CHECK: Duration = Duration::from_millis(100); -const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); const OWN_PREFIX: &str = "yumush"; const APP_CLASS: &str = "Stream/Output/Audio"; const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"]; @@ -46,19 +42,7 @@ impl AudioKind { } } -pub struct AudioCapture { - stop: Arc, - thread: Option>, -} - -impl Drop for AudioCapture { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } -} +pub type AudioCapture = Worker; #[derive(Default)] struct Node { @@ -103,25 +87,17 @@ pub fn apps() -> Vec { } pub fn start(mode: AudioMode, output: rtrb::Producer) -> AudioCapture { - let stop = Arc::new(AtomicBool::new(false)); - let thread = { - let stop = stop.clone(); - std::thread::Builder::new() - .name("share-audio".to_string()) - .spawn(move || { - let output = Rc::new(RefCell::new(output)); - while !stop.load(Ordering::Relaxed) { - if let Err(error) = run(&mode, &output, &stop) { - warn!("share audio: {error}, retrying"); - std::thread::sleep(RETRY_AFTER_ERROR); - } - } - }) - .inspect_err(|error| warn!("share audio not started: {error}")) - .ok() - }; - - AudioCapture { stop, thread } + Worker::spawn("share-audio", move |stop| { + let output = Rc::new(RefCell::new(output)); + let is_sink = match &mode { + AudioMode::Everything { .. } => false, + AudioMode::Source(name) => nodes() + .unwrap_or_default() + .iter() + .any(|node| &node.name == name && node.class == "Audio/Sink"), + }; + supervise("share audio", stop, || run(&mode, &output, is_sink, stop)); + }) } fn nodes() -> Result, Box> { @@ -343,6 +319,7 @@ fn format_values() -> Option> { fn run( mode: &AudioMode, output: &Rc>>, + is_sink: bool, stop: &AtomicBool, ) -> Result<(), Box> { pw::init(); @@ -355,9 +332,11 @@ fn run( let error_failed = failed.clone(); let _core_listener = core .add_listener_local() - .error(move |_, _, _, message| { + .error(move |id, _, _, message| { warn!("pipewire: {message}"); - error_failed.set(true); + if id == pw::core::PW_ID_CORE { + error_failed.set(true); + } }) .register(); @@ -378,12 +357,6 @@ fn run( AudioMode::Everything { .. } => None, AudioMode::Source(name) => Some(name.as_str()), }; - let is_sink = target.is_some_and(|target| { - nodes() - .unwrap_or_default() - .iter() - .any(|node| node.name == target && node.class == "Audio/Sink") - }); let mut props = properties! { *pw::keys::MEDIA_TYPE => "Audio", diff --git a/crates/client/src/share/audio_capture_windows.rs b/crates/client/src/share/audio_capture_windows.rs index 1e3aa97..a78e63d 100644 --- a/crates/client/src/share/audio_capture_windows.rs +++ b/crates/client/src/share/audio_capture_windows.rs @@ -2,11 +2,7 @@ use std::{ collections::{HashMap, VecDeque}, error::Error, process, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, - thread::JoinHandle, + sync::atomic::{AtomicBool, Ordering}, time::Duration, }; @@ -19,25 +15,13 @@ use wasapi::{ }; use super::audio::{AudioApp, AudioKind, AudioMode}; +use crate::voice::audio::{Worker, supervise}; const STOP_CHECK: Duration = Duration::from_millis(100); -const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); const BUFFER_HNS: i64 = 200_000; const BYTES_PER_SAMPLE: usize = 4; -pub struct AudioCapture { - stop: Arc, - thread: Option>, -} - -impl Drop for AudioCapture { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } -} +pub type AudioCapture = Worker; fn with_com(body: impl FnOnce() -> T) -> T { if let Err(error) = initialize_mta().ok() { @@ -99,27 +83,12 @@ fn sessions() -> Result, Box> { } pub fn start(mode: AudioMode, output: Producer) -> AudioCapture { - let stop = Arc::new(AtomicBool::new(false)); - let thread = { - let stop = stop.clone(); - std::thread::Builder::new() - .name("share-audio".to_string()) - .spawn(move || { - with_com(|| { - let mut output = output; - while !stop.load(Ordering::Relaxed) { - if let Err(error) = run(&mode, &mut output, &stop) { - warn!("share audio: {error}, retrying"); - std::thread::sleep(RETRY_AFTER_ERROR); - } - } - }) - }) - .inspect_err(|error| warn!("share audio not started: {error}")) - .ok() - }; - - AudioCapture { stop, thread } + Worker::spawn("share-audio", move |stop| { + with_com(|| { + let mut output = output; + supervise("share audio", stop, || run(&mode, &mut output, stop)); + }) + }) } fn wave_format() -> WaveFormat { @@ -143,6 +112,9 @@ fn run( AudioClient::new_application_loopback_client(process::id(), false)? } AudioMode::Source(node) => { + if !sessions()?.iter().any(|app| &app.node == node) { + return Err("share audio app is not running".into()); + } AudioClient::new_application_loopback_client(node.parse()?, true)? } }; diff --git a/crates/client/src/share/camera.rs b/crates/client/src/share/camera.rs index b8e91c7..e93bc4e 100644 --- a/crates/client/src/share/camera.rs +++ b/crates/client/src/share/camera.rs @@ -24,6 +24,7 @@ use super::{ const OPEN_TIMEOUT: Duration = Duration::from_secs(10); const RETRY_DELAY: Duration = Duration::from_millis(5); +const MAX_FAILURES: u32 = 200; const WANTED_FORMATS: [FrameFormat; 3] = [FrameFormat::YUYV, FrameFormat::NV12, FrameFormat::MJPEG]; type Negotiated = (u32, u32, u32); @@ -129,11 +130,21 @@ fn run( let format = camera.camera_format(); let _ = negotiated.send(Ok((format.width(), format.height(), format.frame_rate()))); let started = Instant::now(); + let mut failures = 0; while !stop.load(Ordering::Relaxed) { - let Ok(buffer) = camera.frame() else { - std::thread::sleep(RETRY_DELAY); - continue; + let buffer = match camera.frame() { + Ok(buffer) => buffer, + Err(error) => { + failures += 1; + if failures >= MAX_FAILURES { + tracing::warn!(%error, "camera lost"); + break; + } + std::thread::sleep(RETRY_DELAY); + continue; + } }; + failures = 0; let Some((width, height, bgra)) = to_bgra(&buffer) else { continue; }; @@ -157,13 +168,6 @@ fn to_bgra(buffer: &Buffer) -> Option<(u32, u32, Vec)> { FrameFormat::YUYV => Some((width, height, pixel::yuyv_to_bgra(data, width, height)?)), FrameFormat::NV12 => Some((width, height, pixel::nv12_to_bgra(data, width, height)?)), FrameFormat::MJPEG => mjpeg_to_bgra(data), - FrameFormat::GRAY if data.len() == (width * height) as usize => Some(( - width, - height, - data.iter() - .flat_map(|&luma| [luma, luma, luma, 255]) - .collect(), - )), _ => None, } } diff --git a/crates/client/src/share/capture.rs b/crates/client/src/share/capture.rs index 2b5fad6..274a90c 100644 --- a/crates/client/src/share/capture.rs +++ b/crates/client/src/share/capture.rs @@ -47,7 +47,8 @@ pub struct Capture { pub frames: Receiver, stop: Arc, thread: Option>, - _session: Option>, + session: Option>, + runtime: tokio::runtime::Handle, _fake: Option, } @@ -57,10 +58,16 @@ impl Drop for Capture { if let Some(thread) = self.thread.take() { let _ = thread.join(); } + if let Some(session) = self.session.take() { + self.runtime.spawn(async move { + let _ = session.close().await; + }); + } } } pub async fn open() -> Result { + let runtime = tokio::runtime::Handle::current(); if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") { let (width, height, refresh, frames, generator) = fake::start(&spec); return Ok(Capture { @@ -70,7 +77,8 @@ pub async fn open() -> Result { frames, stop: Arc::new(AtomicBool::new(false)), thread: None, - _session: None, + session: None, + runtime, _fake: Some(generator), }); } @@ -79,9 +87,39 @@ pub async fn open() -> Result { .create_session(Default::default()) .await .map_err(text)?; + let (node_id, fd) = match pick(&screencast, &session).await { + Ok(picked) => picked, + Err(error) => { + let _ = session.close().await; + return Err(error); + } + }; + match launch(fd, node_id).await { + Ok(((width, height, refresh), frames, stop, thread)) => Ok(Capture { + width, + height, + refresh, + frames, + stop, + thread: Some(thread), + session: Some(session), + runtime, + _fake: None, + }), + Err(error) => { + let _ = session.close().await; + Err(error) + } + } +} + +async fn pick( + screencast: &Screencast, + session: &Session, +) -> Result<(u32, OwnedFd), String> { screencast .select_sources( - &session, + session, SelectSourcesOptions::default() .set_cursor_mode(CursorMode::EMBEDDED) .set_sources(SourceType::MONITOR | SourceType::WINDOW) @@ -93,19 +131,24 @@ pub async fn open() -> Result { .response() .map_err(text)?; let streams = screencast - .start(&session, None, Default::default()) + .start(session, None, Default::default()) .await .map_err(text)? .response() .map_err(text)?; let stream = streams.streams().first().ok_or("no screen stream")?; let node_id = stream.pipe_wire_node_id(); - let (portal_width, portal_height) = stream.size().unwrap_or((0, 0)); let fd = screencast - .open_pipe_wire_remote(&session, Default::default()) + .open_pipe_wire_remote(session, Default::default()) .await .map_err(text)?; + Ok((node_id, fd)) +} +async fn launch( + fd: OwnedFd, + node_id: u32, +) -> Result<(Negotiated, Receiver, Arc, JoinHandle<()>), String> { let (negotiated_tx, negotiated_rx) = sync_channel::(1); let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); let stop = Arc::new(AtomicBool::new(false)); @@ -126,19 +169,14 @@ pub async fn open() -> Result { .await .ok() .flatten(); - let (width, height, refresh) = - negotiated.unwrap_or((portal_width as u32, portal_height as u32, DEFAULT_REFRESH)); - - Ok(Capture { - width, - height, - refresh, - frames: frames_rx, - stop, - thread: Some(thread), - _session: Some(session), - _fake: None, - }) + match negotiated { + Some(size) => Ok((size, frames_rx, stop, thread)), + None => { + stop.store(true, Ordering::Relaxed); + let _ = thread.join(); + Err("screen capture did not start".into()) + } + } } fn text(error: impl std::fmt::Display) -> String { diff --git a/crates/client/src/share/capture_windows.rs b/crates/client/src/share/capture_windows.rs index c376962..71cbb96 100644 --- a/crates/client/src/share/capture_windows.rs +++ b/crates/client/src/share/capture_windows.rs @@ -6,7 +6,7 @@ use std::{ use windows_capture::{ capture::{CaptureControl, Context, GraphicsCaptureApiHandler}, frame::Frame as CaptureFrame, - graphics_capture_api::InternalCaptureControl, + graphics_capture_api::{GraphicsCaptureApi, InternalCaptureControl}, monitor::Monitor, settings::{ ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings, @@ -57,11 +57,15 @@ pub async fn open() -> Result { .filter(|refresh| *refresh > 1) .unwrap_or(DEFAULT_REFRESH); + let border = match GraphicsCaptureApi::is_border_settings_supported() { + Ok(true) => DrawBorderSettings::WithoutBorder, + _ => DrawBorderSettings::Default, + }; let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); let settings = Settings::new( monitor, - CursorCaptureSettings::WithCursor, - DrawBorderSettings::WithoutBorder, + CursorCaptureSettings::Default, + border, SecondaryWindowSettings::Default, MinimumUpdateIntervalSettings::Default, DirtyRegionSettings::Default, diff --git a/crates/client/src/share/convert.rs b/crates/client/src/share/convert.rs deleted file mode 100644 index ed5a70d..0000000 --- a/crates/client/src/share/convert.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub use pixel::I420; - -use super::frame::Frame; - -pub fn bgra_to_i420(frame: &Frame, width: u32, height: u32) -> Option { - let source = pixel::Bgra { - data: &frame.bgra, - width: frame.width, - height: frame.height, - stride: frame.stride, - }; - pixel::bgra_to_i420(&source, width, height) -} diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index cb2b367..f53d0e7 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -6,13 +6,13 @@ use std::thread; use common::share::{Codec, Layer}; -use super::convert; use super::frame::{Encoded, Frame}; -use crate::media::decode::{Engine, VideoDecoder}; +use crate::media::decode::Engine; const SOFTWARE: Codec = Codec::H264; const DEFAULT_MAX_HEIGHT: u32 = 2160; const KEYFRAME_SECONDS: u32 = 2; +const SLACK_MS: u32 = 4; pub struct Capabilities { pub encode: Vec, @@ -42,10 +42,7 @@ fn probe() -> &'static Probe { Probe { capabilities: Capabilities { encode, - decode: Codec::ALL - .into_iter() - .filter(|codec| VideoDecoder::for_codec(*codec).is_some()) - .collect(), + decode: Codec::ALL.to_vec(), max_height, }, hardware: codecs, @@ -121,7 +118,7 @@ impl Backend { match self { Self::Hardware(encoder) => encoder.encode(frame, settings, force), Self::H264(encoder) => { - let planes = convert::bgra_to_i420(frame, settings.width, settings.height)?; + let planes = frame.to_i420(settings.width, settings.height)?; let picture = ec_h264::PictureView::i420( planes.width, planes.height, @@ -146,7 +143,7 @@ mod hardware { use common::share::Codec; use super::{Settings, report}; - use crate::share::{convert, frame::Frame}; + use crate::share::frame::Frame; pub struct Encoder(ec_hw::HwEncoder); @@ -178,7 +175,7 @@ mod hardware { }; self.0.encode_rgb(&rgb, meta) } else { - let planes = convert::bgra_to_i420(frame, settings.width, settings.height)?; + let planes = frame.to_i420(settings.width, settings.height)?; let picture = ec_hw::I420 { y: planes.y, u: planes.u, @@ -249,12 +246,12 @@ fn run( }; let mut applied = 1.0; let interval = 1000 / settings.fps; - let mut last: Option = None; + let mut due = 0u32; for frame in input { - if last.is_some_and(|last| frame.timestamp_ms.wrapping_sub(last) < interval) { + if frame.timestamp_ms + SLACK_MS < due { continue; } - last = Some(frame.timestamp_ms); + due = due.max(frame.timestamp_ms.saturating_sub(SLACK_MS)) + interval; let wanted = f32::from_bits(scale.load(Ordering::Relaxed)); if wanted != applied { applied = wanted; diff --git a/crates/client/src/share/frame.rs b/crates/client/src/share/frame.rs index 13349b4..4fea924 100644 --- a/crates/client/src/share/frame.rs +++ b/crates/client/src/share/frame.rs @@ -14,6 +14,18 @@ pub struct Frame { pub bgra: Vec, } +impl Frame { + pub fn to_i420(&self, width: u32, height: u32) -> Option { + let source = pixel::Bgra { + data: &self.bgra, + width: self.width, + height: self.height, + stride: self.stride, + }; + pixel::bgra_to_i420(&source, width, height) + } +} + pub struct Encoded { pub layer: Layer, pub engine: Engine, diff --git a/crates/client/src/share/mod.rs b/crates/client/src/share/mod.rs index 29c8a46..ab9d4de 100644 --- a/crates/client/src/share/mod.rs +++ b/crates/client/src/share/mod.rs @@ -12,10 +12,13 @@ pub mod capture; #[path = "capture_windows.rs"] pub mod capture; pub mod congestion; -pub mod convert; pub mod encode; #[cfg(any(target_os = "linux", target_os = "windows"))] pub mod fake; pub mod frame; pub mod reassembly; pub mod session; +#[cfg(not(any(target_os = "linux", target_os = "windows")))] +mod unsupported; +#[cfg(not(any(target_os = "linux", target_os = "windows")))] +pub use unsupported::{audio_capture, camera, capture}; diff --git a/crates/client/src/share/reassembly.rs b/crates/client/src/share/reassembly.rs index 0be048d..d116878 100644 --- a/crates/client/src/share/reassembly.rs +++ b/crates/client/src/share/reassembly.rs @@ -88,7 +88,6 @@ pub struct Reassembler { pending: HashMap, last: Option, phase: Phase, - lost: bool, received_frames: u32, lost_frames: u32, } @@ -100,7 +99,6 @@ impl Reassembler { pending: HashMap::new(), last: None, phase: Phase::WaitingKeyframe, - lost: false, received_frames: 0, lost_frames: 0, } @@ -121,7 +119,6 @@ impl Reassembler { } if !self.pending.contains_key(&fragment.frame) && self.pending.len() >= PENDING_LIMIT { self.pending.clear(); - self.lost = true; self.phase = Phase::WaitingKeyframe; } let pending = self @@ -146,7 +143,6 @@ impl Reassembler { self.last = Some(frame); if skipped > 0 || data.is_none() { self.lost_frames += skipped + u32::from(data.is_none()); - self.lost = true; self.phase = Phase::WaitingKeyframe; self.pending.retain(|&older, _| is_newer(older, frame)); } @@ -166,8 +162,8 @@ impl Reassembler { }) } - pub fn take_lost(&mut self) -> bool { - std::mem::take(&mut self.lost) + pub fn needs_keyframe(&self) -> bool { + self.phase == Phase::WaitingKeyframe } pub fn loss_ratio(&mut self) -> f32 { diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/session.rs index c09a8f2..b13cac9 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/session.rs @@ -2,7 +2,7 @@ use std::{ cmp::Reverse, collections::{HashMap, VecDeque}, sync::{ - Arc, Mutex, + Arc, LazyLock, Mutex, atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering}, mpsc::{self, Receiver, RecvTimeoutError, Sender}, }, @@ -146,13 +146,11 @@ fn next(rx: &Receiver, stop: &AtomicBool) -> Option { None } -#[cfg(any(target_os = "linux", target_os = "windows"))] enum Input { Screen(Capture), Camera(Camera), } -#[cfg(any(target_os = "linux", target_os = "windows"))] impl Input { fn size(&self) -> (u32, u32, u32) { match self { @@ -170,10 +168,6 @@ impl Input { } } -#[cfg(not(any(target_os = "linux", target_os = "windows")))] -pub struct Sharing {} - -#[cfg(any(target_os = "linux", target_os = "windows"))] pub struct Sharing { encoders: Arc>, _feed: Worker, @@ -190,58 +184,22 @@ pub struct Sharing { sent: Arc>, } -#[cfg(not(any(target_os = "linux", target_os = "windows")))] impl Sharing { - pub async fn start( - _: Connection, - _: Kind, - _: Quality, - _: Vec, - _: Option, - ) -> Result<(Sharing, Source), String> { - Err("screen share needs linux".into()) - } - - pub fn update( - &mut self, - _: &Connection, - _: Quality, - _: Vec, - _: Option, - ) -> Result { - Err("screen share needs linux".into()) - } - - pub fn set_layers(&mut self, _: &[Layer]) {} - - pub fn keyframe(&self, _: Layer) {} - - pub fn stats(&self) -> Vec { - Vec::new() - } - - pub fn level(&self) -> Vec { - Vec::new() - } -} - -#[cfg(any(target_os = "linux", target_os = "windows"))] -impl Sharing { - fn clamp(top: Quality, height: u32, refresh: u32) -> Result { + fn clamp(top: Quality, height: u32, refresh: u32) -> Quality { let (resolutions, frame_rates) = options(height, refresh, encode::capabilities().max_height); - Ok(Quality { + Quality { resolution: resolutions .into_iter() .filter(|resolution| *resolution <= top.resolution) .max() - .ok_or("no share resolution")?, + .unwrap_or(Resolution::P360), fps: frame_rates .into_iter() .filter(|fps| *fps <= top.fps) .max() - .ok_or("no share fps")?, - }) + .unwrap_or(Fps::F15), + } } pub async fn start( @@ -267,7 +225,7 @@ impl Sharing { let source = Source { width, height, - top: Self::clamp(top, height, refresh)?, + top: Self::clamp(top, height, refresh), encode, }; @@ -333,7 +291,7 @@ impl Sharing { if encode.is_empty() { return Err("codec unavailable".into()); } - self.source.top = Self::clamp(top, self.source.height, self.refresh)?; + self.source.top = Self::clamp(top, self.source.height, self.refresh); self.source.encode = encode; if self.audio != audio { self.audio = audio.clone(); @@ -562,7 +520,7 @@ impl Watching { Kind::Camera => (None, None, None), }; - Watching { + let mut watching = Watching { clock, video, health, @@ -583,6 +541,15 @@ impl Watching { .unwrap_or(0), clean: 0, requested: None, + }; + watching.emitted = Some(watching.wanted()); + watching + } + + pub fn wanted(&self) -> Quality { + match self.quality { + WatchQuality::Fixed(quality) => quality, + WatchQuality::Auto => rungs()[self.rung], } } @@ -658,14 +625,11 @@ impl Watching { pub fn tick(&mut self) -> Vec { let (loss, served, lost) = { - let mut health = lock(&self.health); + let health = lock(&self.health); let due = self .requested .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); let lost = health.lost && due; - if lost { - health.lost = false; - } (health.loss, health.served, lost) }; let mut ticks = Vec::new(); @@ -673,13 +637,10 @@ impl Watching { self.requested = Some(Instant::now()); ticks.push(Tick::Keyframe); } - let wanted = match self.quality { - WatchQuality::Fixed(quality) => quality, - WatchQuality::Auto => { - self.adapt(loss, served); - rungs()[self.rung] - } - }; + if self.quality == WatchQuality::Auto { + self.adapt(loss, served); + } + let wanted = self.wanted(); if self.emitted != Some(wanted) { self.emitted = Some(wanted); ticks.push(Tick::Quality(wanted)); @@ -705,19 +666,22 @@ impl Watching { } } -fn rungs() -> Vec { - let mut rungs: Vec = Resolution::ALL - .into_iter() - .flat_map(|resolution| { - Fps::ALL - .into_iter() - .map(move |fps| Quality { resolution, fps }) - }) - .collect(); - rungs.sort_by_key(|quality| { - Reverse((quality.resolution.height() * quality.fps.value(), *quality)) +fn rungs() -> &'static [Quality] { + static RUNGS: LazyLock> = LazyLock::new(|| { + let mut rungs: Vec = Resolution::ALL + .into_iter() + .flat_map(|resolution| { + Fps::ALL + .into_iter() + .map(move |fps| Quality { resolution, fps }) + }) + .collect(); + rungs.sort_by_key(|quality| { + Reverse((quality.resolution.height() * quality.fps.value(), *quality)) + }); + rungs }); - rungs + &RUNGS } fn watch_video( @@ -747,10 +711,9 @@ fn watch_video( Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => break, } + lock(health).lost = reassembler.needs_keyframe(); if sampled.elapsed() >= SAMPLE { - let mut health = lock(health); - health.loss = reassembler.loss_ratio(); - health.lost |= reassembler.take_lost(); + lock(health).loss = reassembler.loss_ratio(); sampled = Instant::now(); } } diff --git a/crates/client/src/share/unsupported.rs b/crates/client/src/share/unsupported.rs new file mode 100644 index 0000000..33b6df5 --- /dev/null +++ b/crates/client/src/share/unsupported.rs @@ -0,0 +1,52 @@ +use std::sync::mpsc::Receiver; + +use super::{ + audio::{AudioApp, AudioMode}, + frame::Frame, +}; + +const UNSUPPORTED: &str = "screen share is not supported on this OS"; + +pub mod capture { + use super::*; + + pub struct Capture { + pub width: u32, + pub height: u32, + pub refresh: u32, + pub frames: Receiver, + } + + pub async fn open() -> Result { + Err(UNSUPPORTED.into()) + } +} + +pub mod camera { + use super::*; + + pub struct Camera { + pub width: u32, + pub height: u32, + pub refresh: u32, + pub frames: Receiver, + } + + pub fn open() -> Result { + Err(UNSUPPORTED.into()) + } +} + +pub mod audio_capture { + use super::*; + + pub struct AudioCapture; + + pub fn apps() -> Vec { + Vec::new() + } + + pub fn start(_: AudioMode, _: rtrb::Producer) -> AudioCapture { + AudioCapture + } +} diff --git a/crates/client/src/tray.rs b/crates/client/src/tray.rs index 33d8e52..9d88580 100644 --- a/crates/client/src/tray.rs +++ b/crates/client/src/tray.rs @@ -1,5 +1,7 @@ use tokio::sync::mpsc; +pub const AVAILABLE: bool = cfg!(target_os = "linux"); + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TrayAction { Show, @@ -12,23 +14,6 @@ pub struct TrayState { pub mentions: u32, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Badge { - None, - Unread, - Mention, -} - -impl TrayState { - fn badge(self) -> Badge { - match (self.messages, self.mentions) { - (_, 1..) => Badge::Mention, - (1.., _) => Badge::Unread, - _ => Badge::None, - } - } -} - #[derive(Clone)] pub struct TrayHandle(mpsc::UnboundedSender); @@ -39,45 +24,7 @@ impl TrayHandle { } #[cfg(target_os = "linux")] -pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { - use ksni::TrayMethods; - use tracing::warn; - - let (sender, receiver) = mpsc::unbounded_channel(); - let (state_sender, mut state_receiver) = mpsc::unbounded_channel(); - let tray = Tray { - sender, - state: TrayState::default(), - }; - - let _ = std::thread::Builder::new() - .name("tray".to_string()) - .spawn(move || { - let runtime = match tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - { - Ok(runtime) => runtime, - Err(error) => { - warn!("tray runtime: {error}"); - return; - } - }; - runtime.block_on(async move { - match tray.assume_sni_available(true).spawn().await { - Ok(handle) => { - while let Some(state) = state_receiver.recv().await { - handle.update(|tray| tray.state = state).await; - } - std::future::pending::<()>().await - } - Err(error) => warn!("tray: {error}"), - } - }); - }); - - (receiver, TrayHandle(state_sender)) -} +pub use linux::start; #[cfg(not(target_os = "linux"))] pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { @@ -88,123 +35,176 @@ pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { } #[cfg(target_os = "linux")] -struct Tray { - sender: mpsc::UnboundedSender, - state: TrayState, -} +mod linux { + use ksni::TrayMethods; + use tokio::sync::mpsc; + use tracing::warn; -#[cfg(target_os = "linux")] -impl ksni::Tray for Tray { - fn id(&self) -> String { - crate::NAME.to_string() - } + use super::{TrayAction, TrayHandle, TrayState}; - fn title(&self) -> String { - crate::NAME.to_string() + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum Badge { + None, + Unread, + Mention, } - fn icon_pixmap(&self) -> Vec { - vec![icon(self.state.badge())] - } - - fn status(&self) -> ksni::Status { - match self.state.badge() { - Badge::Mention => ksni::Status::NeedsAttention, - _ => ksni::Status::Active, + impl TrayState { + fn badge(self) -> Badge { + match (self.messages, self.mentions) { + (_, 1..) => Badge::Mention, + (1.., _) => Badge::Unread, + _ => Badge::None, + } } } - fn tool_tip(&self) -> ksni::ToolTip { - let description = match self.state.badge() { - Badge::None => String::new(), - _ => format!( - "{} unread · {} mentions", - self.state.messages, self.state.mentions - ), + pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { + let (sender, receiver) = mpsc::unbounded_channel(); + let (state_sender, mut state_receiver) = mpsc::unbounded_channel(); + let tray = Tray { + sender, + state: TrayState::default(), }; - ksni::ToolTip { - title: crate::NAME.to_string(), - description, - ..Default::default() - } + + let _ = std::thread::Builder::new() + .name("tray".to_string()) + .spawn(move || { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + warn!("tray runtime: {error}"); + return; + } + }; + runtime.block_on(async move { + match tray.assume_sni_available(true).spawn().await { + Ok(handle) => { + while let Some(state) = state_receiver.recv().await { + handle.update(|tray| tray.state = state).await; + } + std::future::pending::<()>().await + } + Err(error) => warn!("tray: {error}"), + } + }); + }); + + (receiver, TrayHandle(state_sender)) } - fn activate(&mut self, _x: i32, _y: i32) { - let _ = self.sender.send(TrayAction::Show); + struct Tray { + sender: mpsc::UnboundedSender, + state: TrayState, } - fn menu(&self) -> Vec> { - use ksni::menu::StandardItem; + impl ksni::Tray for Tray { + fn id(&self) -> String { + crate::NAME.to_string() + } - vec![ - StandardItem { - label: "Show".to_string(), - activate: Box::new(|tray: &mut Self| { - let _ = tray.sender.send(TrayAction::Show); - }), - ..Default::default() + fn title(&self) -> String { + crate::NAME.to_string() + } + + fn icon_pixmap(&self) -> Vec { + vec![icon(self.state.badge())] + } + + fn status(&self) -> ksni::Status { + match self.state.badge() { + Badge::Mention => ksni::Status::NeedsAttention, + _ => ksni::Status::Active, } - .into(), - StandardItem { - label: "Quit".to_string(), - activate: Box::new(|tray: &mut Self| { - let _ = tray.sender.send(TrayAction::Quit); - }), + } + + fn tool_tip(&self) -> ksni::ToolTip { + let description = match self.state.badge() { + Badge::None => String::new(), + _ => format!( + "{} unread · {} mentions", + self.state.messages, self.state.mentions + ), + }; + ksni::ToolTip { + title: crate::NAME.to_string(), + description, ..Default::default() } - .into(), - ] - } -} + } -#[cfg(target_os = "linux")] -const ICON_SIZE: i32 = 32; -#[cfg(target_os = "linux")] -const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; -#[cfg(target_os = "linux")] -const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; -#[cfg(target_os = "linux")] -const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); -#[cfg(target_os = "linux")] -const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; -#[cfg(target_os = "linux")] -const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; + fn activate(&mut self, _x: i32, _y: i32) { + let _ = self.sender.send(TrayAction::Show); + } -#[cfg(target_os = "linux")] -fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { - let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); - (radius - distance + 0.5).clamp(0.0, 1.0) -} + fn menu(&self) -> Vec> { + use ksni::menu::StandardItem; -#[cfg(target_os = "linux")] -fn icon(badge: Badge) -> ksni::Icon { - let dot = match badge { - Badge::None => None, - Badge::Unread => Some(UNREAD_COLOR), - Badge::Mention => Some(MENTION_COLOR), - }; - let data = (0..ICON_SIZE * ICON_SIZE) - .flat_map(|index| { - let x = (index % ICON_SIZE) as f32 + 0.5; - let y = (index / ICON_SIZE) as f32 + 0.5; - let base = ICON_DROPS - .iter() - .map(|drop| coverage(x, y, *drop)) - .fold(0.0, f32::max); - let ([red, green, blue], alpha) = match dot { - Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), - Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { - (ICON_COLOR, 0.0) + vec![ + StandardItem { + label: "Show".to_string(), + activate: Box::new(|tray: &mut Self| { + let _ = tray.sender.send(TrayAction::Show); + }), + ..Default::default() } - _ => (ICON_COLOR, base), - }; - [(alpha * 255.0) as u8, red, green, blue] - }) - .collect(); - - ksni::Icon { - width: ICON_SIZE, - height: ICON_SIZE, - data, + .into(), + StandardItem { + label: "Quit".to_string(), + activate: Box::new(|tray: &mut Self| { + let _ = tray.sender.send(TrayAction::Quit); + }), + ..Default::default() + } + .into(), + ] + } + } + + const ICON_SIZE: i32 = 32; + const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; + const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; + const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); + const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; + const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; + + fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { + let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); + (radius - distance + 0.5).clamp(0.0, 1.0) + } + + fn icon(badge: Badge) -> ksni::Icon { + let dot = match badge { + Badge::None => None, + Badge::Unread => Some(UNREAD_COLOR), + Badge::Mention => Some(MENTION_COLOR), + }; + let data = (0..ICON_SIZE * ICON_SIZE) + .flat_map(|index| { + let x = (index % ICON_SIZE) as f32 + 0.5; + let y = (index / ICON_SIZE) as f32 + 0.5; + let base = ICON_DROPS + .iter() + .map(|drop| coverage(x, y, *drop)) + .fold(0.0, f32::max); + let ([red, green, blue], alpha) = match dot { + Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), + Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { + (ICON_COLOR, 0.0) + } + _ => (ICON_COLOR, base), + }; + [(alpha * 255.0) as u8, red, green, blue] + }) + .collect(); + + ksni::Icon { + width: ICON_SIZE, + height: ICON_SIZE, + data, + } } } diff --git a/crates/client/src/voice/audio.rs b/crates/client/src/voice/audio.rs index be543a8..04672f6 100644 --- a/crates/client/src/voice/audio.rs +++ b/crates/client/src/voice/audio.rs @@ -22,14 +22,6 @@ mod backend; #[cfg(target_os = "windows")] #[path = "audio/wasapi.rs"] mod backend; -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] -mod backend { - use super::Devices; - - pub fn devices() -> Devices { - Devices::default() - } -} const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); @@ -58,7 +50,6 @@ pub struct Choice { pub enum Audio { Silent, Tone(Worker), - #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] Device(backend::Backend), } @@ -82,20 +73,10 @@ pub fn start(capture: Option, playback: Playback, choice: Choice) -> Au Mode::Tone => Audio::Tone(Worker::spawn("voice-tone", move |stop| { tone(capture.as_ref(), &playback, stop) })), - Mode::Device => device(capture, playback, choice), + Mode::Device => Audio::Device(backend::start(capture, playback, choice)), } } -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] -fn device(capture: Option, playback: Playback, choice: Choice) -> Audio { - Audio::Device(backend::start(capture, playback, choice)) -} - -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] -fn device(_: Option, _: Playback, _: Choice) -> Audio { - Audio::Silent -} - pub fn devices() -> Devices { match mode() { Mode::Off | Mode::Tone => Devices::default(), diff --git a/crates/client/src/voice/audio/coreaudio.rs b/crates/client/src/voice/audio/coreaudio.rs index 4918439..4c52e6c 100644 --- a/crates/client/src/voice/audio/coreaudio.rs +++ b/crates/client/src/voice/audio/coreaudio.rs @@ -76,26 +76,21 @@ fn attempt( stop: &AtomicBool, ) -> Result<(), Box> { let output_id = output_device(choice); - let mut output = playback_unit(playback.clone(), output_id.0)?; + let _output = playback_unit(playback.clone(), output_id.0)?; let device = capture.and_then(|_| input_device(choice)); - let mut input = capture.zip(device).and_then(|(capture, device)| { + let input = capture.zip(device).and_then(|(capture, device)| { capture_unit(device, capture.clone()) .inspect_err(|error| warn!("voice capture unavailable: {error}")) .ok() }); - let outcome = watch( + watch( stop, choice, capture.is_some(), input.as_ref(), device, output_id, - ); - stop_unit(&mut output); - if let Some((unit, _)) = input.as_mut() { - stop_unit(unit); - } - outcome?; + )?; Ok(()) } @@ -126,12 +121,6 @@ fn watch( Ok(()) } -fn stop_unit(unit: &mut AudioUnit) { - if let Err(error) = unit.stop() { - warn!("voice audio stop failed: {error}"); - } -} - fn format(sample_rate: f64, channels: u32) -> StreamFormat { StreamFormat { sample_rate, @@ -182,6 +171,7 @@ fn capture_unit(device: u32, capture: Capture) -> Result<(AudioUnit, f64), Error let mut resampler = (rate != f64::from(VOICE_SAMPLE_RATE)).then(|| Resampler::new(rate)); let mut downmix = Downmix::default(); let mut mixed = Vec::new(); + let mut resampled = Vec::new(); unit.set_input_callback(move |args: Args| { let Args { data, .. } = args; let mut channels = data.channels(); @@ -193,7 +183,10 @@ fn capture_unit(device: u32, capture: Capture) -> Result<(AudioUnit, f64), Error mixed.clear(); mixed.extend(downmix.mix(frames)); match resampler.as_mut() { - Some(resampler) => record(&capture, resampler.resample(&mixed)), + Some(resampler) => { + resampler.resample(&mixed, &mut resampled); + record(&capture, resampled.iter().copied()); + } None => record(&capture, mixed.iter().copied()), } Ok(()) @@ -218,50 +211,23 @@ impl Resampler { } } - fn resample<'a>(&'a mut self, input: &'a [f32]) -> Resampled<'a> { - Resampled { - resampler: self, - input, + fn resample(&mut self, input: &[f32], out: &mut Vec) { + out.clear(); + while (self.position as usize) < input.len() { + let index = self.position as usize; + let fraction = (self.position - index as f64) as f32; + let a = if index == 0 { + self.previous + } else { + input[index - 1] + }; + let b = input[index]; + out.push(a + (b - a) * fraction); + self.position += self.step; } - } -} - -struct Resampled<'a> { - resampler: &'a mut Resampler, - input: &'a [f32], -} - -impl Resampled<'_> { - fn at(&self, index: usize) -> f32 { - if index == 0 { - self.resampler.previous - } else { - self.input[index - 1] - } - } -} - -impl Iterator for Resampled<'_> { - type Item = f32; - - fn next(&mut self) -> Option { - let index = self.resampler.position as usize; - if index >= self.input.len() { - return None; - } - let fraction = (self.resampler.position - index as f64) as f32; - let (a, b) = (self.at(index), self.at(index + 1)); - self.resampler.position += self.resampler.step; - Some(a + (b - a) * fraction) - } -} - -impl Drop for Resampled<'_> { - fn drop(&mut self) { - for _ in self.by_ref() {} - self.resampler.position -= self.input.len() as f64; - if let Some(&last) = self.input.last() { - self.resampler.previous = last; + self.position -= input.len() as f64; + if let Some(&last) = input.last() { + self.previous = last; } } } diff --git a/crates/client/src/voice/audio/pipewire.rs b/crates/client/src/voice/audio/pipewire.rs index 6fb7812..cd517d9 100644 --- a/crates/client/src/voice/audio/pipewire.rs +++ b/crates/client/src/voice/audio/pipewire.rs @@ -7,7 +7,13 @@ use std::{ use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; use pipewire as pw; -use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType}; +use pw::{ + loop_::Timeout, + properties::properties, + spa, + stream::{StreamBox, StreamListener, StreamState}, + types::ObjectType, +}; use spa::pod::Pod; use super::{ @@ -16,9 +22,7 @@ use super::{ }; use crate::voice::{Capture, Playback}; -pub struct Backend { - _worker: Worker, -} +pub type Backend = Worker; pub fn devices() -> Devices { collect_devices().unwrap_or_default() @@ -32,7 +36,6 @@ fn collect_devices() -> Result> { let registry = core.get_registry_rc()?; let devices = Rc::new(RefCell::new(Devices::default())); - let done = Rc::new(Cell::new(false)); let failed = Rc::new(Cell::new(false)); let pending = core.sync(0)?; @@ -40,22 +43,18 @@ fn collect_devices() -> Result> { let _core_listener = core .add_listener_local() .done({ - let done = done.clone(); let mainloop = mainloop.clone(); move |id, seq| { if id == pw::core::PW_ID_CORE && seq == pending { - done.set(true); mainloop.quit(); } } }) .error({ - let done = done.clone(); let failed = failed.clone(); let mainloop = mainloop.clone(); move |_, _, _, _| { failed.set(true); - done.set(true); mainloop.quit(); } }) @@ -75,9 +74,6 @@ fn collect_devices() -> Result> { let Some(node) = props.get(*pw::keys::NODE_NAME) else { return; }; - if node == "yumush" { - return; - } let device = Device { id: node.to_string(), name: props @@ -95,9 +91,7 @@ fn collect_devices() -> Result> { }) .register(); - while !done.get() { - mainloop.run(); - } + mainloop.run(); if failed.get() { return Err("pipewire devices".into()); @@ -106,13 +100,11 @@ fn collect_devices() -> Result> { } pub fn start(capture: Option, playback: Playback, choice: Choice) -> Backend { - Backend { - _worker: Worker::spawn("voice-audio", move |stop| { - supervise("voice audio", stop, || { - run(capture.as_ref(), &playback, &choice, stop) - }) - }), - } + Worker::spawn("voice-audio", move |stop| { + supervise("voice audio", stop, || { + run(capture.as_ref(), &playback, &choice, stop) + }) + }) } fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::PropertiesBox { @@ -185,49 +177,10 @@ fn run( | pw::stream::StreamFlags::MAP_BUFFERS | pw::stream::StreamFlags::RT_PROCESS; - let capture_stream = pw::stream::StreamBox::new( - &core, - "yumush-capture", - stream_properties("Capture", choice.input.as_deref()), - )?; - let capture = capture.cloned(); - let connect_capture = capture.is_some(); - let _capture_listener = capture_stream - .add_local_listener_with_user_data(()) - .state_changed(state_watch(&failed)) - .process(move |stream, _| { - let Some(mut buffer) = stream.dequeue_buffer() else { - return; - }; - let Some(data) = buffer.datas_mut().first_mut() else { - return; - }; - let size = data.chunk().size() as usize; - let Some(bytes) = data.data() else { - return; - }; - let bytes = &bytes[..size.min(bytes.len())]; - let Some(capture) = &capture else { - return; - }; - let samples = bytes - .as_chunks::<4>() - .0 - .iter() - .copied() - .map(f32::from_le_bytes); - record(capture, samples); - }) - .register()?; - if connect_capture { - let mut capture_params = [Pod::from_bytes(&capture_values).ok_or("pipewire format")?]; - capture_stream.connect( - spa::utils::Direction::Input, - None, - flags, - &mut capture_params, - )?; - } + let _capture = capture + .cloned() + .map(|capture| capture_stream(&core, capture, choice, &failed, &capture_values, flags)) + .transpose()?; let playback_stream = pw::stream::StreamBox::new( &core, @@ -283,6 +236,48 @@ fn run( Ok(()) } +fn capture_stream<'c>( + core: &'c pw::core::Core, + capture: Capture, + choice: &Choice, + failed: &Rc>, + values: &[u8], + flags: pw::stream::StreamFlags, +) -> Result<(StreamListener<()>, StreamBox<'c>), Box> { + let stream = StreamBox::new( + core, + "yumush-capture", + stream_properties("Capture", choice.input.as_deref()), + )?; + let listener = stream + .add_local_listener_with_user_data(()) + .state_changed(state_watch(failed)) + .process(move |stream, _| { + let Some(mut buffer) = stream.dequeue_buffer() else { + return; + }; + let Some(data) = buffer.datas_mut().first_mut() else { + return; + }; + let size = data.chunk().size() as usize; + let Some(bytes) = data.data() else { + return; + }; + let bytes = &bytes[..size.min(bytes.len())]; + let samples = bytes + .as_chunks::<4>() + .0 + .iter() + .copied() + .map(f32::from_le_bytes); + record(&capture, samples); + }) + .register()?; + let mut params = [Pod::from_bytes(values).ok_or("pipewire format")?]; + stream.connect(spa::utils::Direction::Input, None, flags, &mut params)?; + Ok((listener, stream)) +} + fn state_watch( failed: &Rc>, ) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static { diff --git a/crates/client/src/voice/audio/wasapi.rs b/crates/client/src/voice/audio/wasapi.rs index cc19ade..171cdfe 100644 --- a/crates/client/src/voice/audio/wasapi.rs +++ b/crates/client/src/voice/audio/wasapi.rs @@ -20,12 +20,10 @@ use crate::voice::{Capture, Playback}; const CHECK_DEFAULT_EVERY: Duration = Duration::from_secs(1); -pub struct Backend { - _workers: Vec, -} +pub type Backend = Vec; struct Target<'a> { - enumerator: &'a DeviceEnumerator, + enumerator: DeviceEnumerator, direction: Direction, id: String, choice: Option<&'a str>, @@ -72,23 +70,24 @@ fn list( pub fn start(capture: Option, playback: Playback, choice: Choice) -> Backend { let input = choice.input; let output = choice.output; - let mut workers = vec![Worker::spawn("voice render", move |stop| { - with_com(|| { - supervise("voice render", stop, || { - run_render(&playback, stop, output.as_deref()) - }) - }) + let mut workers = vec![worker("voice render", move |stop| { + run_render(&playback, stop, output.as_deref()) })]; if let Some(capture) = capture { - workers.push(Worker::spawn("voice capture", move |stop| { - with_com(|| { - supervise("voice capture", stop, || { - run_capture(&capture, stop, input.as_deref()) - }) - }) + workers.push(worker("voice capture", move |stop| { + run_capture(&capture, stop, input.as_deref()) })); } - Backend { _workers: workers } + workers +} + +fn worker( + name: &'static str, + mut run: impl FnMut(&AtomicBool) -> Result<(), Box> + Send + 'static, +) -> Worker { + Worker::spawn(name, move |stop| { + with_com(|| supervise(name, stop, || run(stop))) + }) } fn with_com(body: impl FnOnce() -> T) -> T { @@ -170,34 +169,42 @@ fn default_changed(target: &Target, checked: &mut Instant) -> Result Ok(false), - Some(chosen) if find_device(target.enumerator, target.direction, chosen).is_some() => { + Some(chosen) if find_device(&target.enumerator, target.direction, chosen).is_some() => { Ok(true) } - _ => Ok(default_id(target.enumerator, target.direction)? != target.id), + _ => Ok(default_id(&target.enumerator, target.direction)? != target.id), } } -fn run_capture( - capture: &Capture, - stop: &AtomicBool, +fn open( + direction: Direction, choice: Option<&str>, -) -> Result<(), Box> { +) -> Result<(Target<'_>, AudioClient, Handle), Box> { let enumerator = DeviceEnumerator::new()?; - let device = open_device(&enumerator, Direction::Capture, choice)?; + let device = open_device(&enumerator, direction, choice)?; let target = Target { - enumerator: &enumerator, - direction: Direction::Capture, id: device.get_id()?, + enumerator, + direction, choice, }; let mut client = device.get_iaudioclient()?; - init_shared_event(&mut client, Direction::Capture)?; + init_shared_event(&mut client, direction)?; let event = client.set_get_eventhandle()?; + Ok((target, client, event)) +} + +fn run_capture( + capture: &Capture, + stop: &AtomicBool, + choice: Option<&str>, +) -> Result<(), Box> { + let (target, client, event) = open(Direction::Capture, choice)?; let reader = client.get_audiocaptureclient()?; client.start_stream()?; let result = capture_frames(capture, stop, &target, &event, &reader); - client.stop_stream()?; + let _ = client.stop_stream(); result } @@ -236,17 +243,7 @@ fn run_render( stop: &AtomicBool, choice: Option<&str>, ) -> Result<(), Box> { - let enumerator = DeviceEnumerator::new()?; - let device = open_device(&enumerator, Direction::Render, choice)?; - let target = Target { - enumerator: &enumerator, - direction: Direction::Render, - id: device.get_id()?, - choice, - }; - let mut client = device.get_iaudioclient()?; - init_shared_event(&mut client, Direction::Render)?; - let event = client.set_get_eventhandle()?; + let (target, client, event) = open(Direction::Render, choice)?; let writer = client.get_audiorenderclient()?; let silence = vec![0u8; client.get_available_space_in_frames()? as usize * BYTES_PER_FRAME]; @@ -254,7 +251,7 @@ fn run_render( client.start_stream()?; let result = render_frames(playback, stop, &target, &event, &client, &writer); - client.stop_stream()?; + let _ = client.stop_stream(); result } diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index 29c8fab..93a0a8e 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -116,7 +116,7 @@ impl Speaker { fn decode_next(&mut self) -> (Vec, bool) { let (decoded, real) = match ( self.jitter.remove(&self.next), - self.jitter.get(&(self.next + 1)), + self.jitter.get(&self.next.wrapping_add(1)), ) { (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true), (None, Some(following)) => ( @@ -129,7 +129,7 @@ impl Speaker { false, ), }; - self.next += 1; + self.next = self.next.wrapping_add(1); let samples = match decoded { Ok(samples) => self.scratch[..samples].to_vec(), diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index 7b77fa9..befe365 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -3,7 +3,6 @@ use std::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, }, - thread::JoinHandle, time::Duration, }; @@ -14,13 +13,12 @@ use common::{ }; use quinn::Connection; use rtrb::{Consumer, Producer, RingBuffer}; -use tracing::warn; pub mod audio; pub mod engine; use crate::settings::VoiceSettings; -use audio::{Audio, Choice}; +use audio::{Audio, Choice, Worker}; use engine::{Engine, SILENT_DB, Traffic}; const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; @@ -45,8 +43,7 @@ pub struct VoiceSample { pub struct Voice { engine: Arc>, connection: Option, - stop: Arc, - worker: Option>, + _worker: Worker, capture: Capture, playback: Playback, choice: Choice, @@ -55,7 +52,6 @@ pub struct Voice { pub fn start(connection: Option, settings: &VoiceSettings) -> Voice { let engine = Arc::new(Mutex::new(Engine::new())); - let stop = Arc::new(AtomicBool::new(false)); let (capture_producer, from_capture) = RingBuffer::new(RING_SAMPLES); let (to_playback, playback_consumer) = RingBuffer::new(PLAYBACK_RING); let capture: Capture = Arc::new(Mutex::new(capture_producer)); @@ -69,27 +65,21 @@ pub fn start(connection: Option, settings: &VoiceSettings) -> Voice let link = connection.clone(); let worker = { let engine = engine.clone(); - let stop = stop.clone(); - std::thread::Builder::new() - .name("voice-worker".to_string()) - .spawn(move || { - work( - &engine, - connection.as_ref(), - from_capture, - to_playback, - &stop, - ) - }) - .inspect_err(|error| warn!("voice worker not started: {error}")) - .ok() + Worker::spawn("voice-worker", move |stop| { + work( + &engine, + connection.as_ref(), + from_capture, + to_playback, + stop, + ) + }) }; let mut voice = Voice { engine, connection: link, - stop, - worker, + _worker: worker, capture, playback, choice: settings.choice.clone(), @@ -335,12 +325,3 @@ impl Voice { self.with_engine((), |engine| engine.set_talking(talking)); } } - -impl Drop for Voice { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some(worker) = self.worker.take() { - let _ = worker.join(); - } - } -} diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index 25f7e3d..0e6588f 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -4,29 +4,15 @@ use bitcode::{Decode, Encode}; #[macro_export] macro_rules! error_from { - ($target:ty { $($rest:tt)* }) => { - $crate::error_from!(@arm $target, $($rest)*); - }; - - (@arm $target:ty, $source:ty => $variant:path as $middle:ty, $($rest:tt)*) => { - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(<$middle>::from(value).into()) - } - } - $crate::error_from!(@arm $target, $($rest)*); - }; - - (@arm $target:ty, $source:ty => $variant:path, $($rest:tt)*) => { - impl From<$source> for $target { - fn from(value: $source) -> Self { - $variant(value) + ($target:ty { $($source:ty => $variant:path as $middle:ty),+ $(,)? }) => { + $( + impl From<$source> for $target { + fn from(value: $source) -> Self { + $variant(<$middle>::from(value)) + } } - } - $crate::error_from!(@arm $target, $($rest)*); + )+ }; - - (@arm $target:ty,) => {}; } macro_rules! from_display { @@ -47,7 +33,6 @@ pub enum InvalidInput { TooLong { maximum: usize, actual: usize }, TooLarge { maximum: u64, actual: u64 }, Empty, - NotASCII, MultiLine, ForbiddenCharacter, NotJpeg, @@ -81,7 +66,6 @@ impl Display for InvalidInput { ) } InvalidInput::Empty => write!(f, "empty"), - InvalidInput::NotASCII => write!(f, "not ASCII"), InvalidInput::MultiLine => write!(f, "contains line break"), InvalidInput::ForbiddenCharacter => write!(f, "contains forbidden character"), InvalidInput::NotJpeg => write!(f, "not JPEG"), diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index 0dffe55..742316e 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -162,8 +162,12 @@ pub struct Unread { } pub fn mentions(body: &str, username: &str) -> bool { - body.to_lowercase() - .contains(&format!("@{}", username.to_lowercase())) + let body = body.to_lowercase(); + let needle = format!("@{}", username.to_lowercase()); + body.match_indices(&needle).any(|(at, _)| { + !body[at + needle.len()..] + .starts_with(|next: char| next.is_ascii_alphanumeric() || matches!(next, '_' | '-')) + }) } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -468,7 +472,6 @@ pub struct ServerBan { pub kind: ServerBanKind, pub value: String, pub reason: Option, - pub created_by: Option, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -476,7 +479,6 @@ pub struct InviteCode { pub code: String, pub uses_left: u32, pub expires_at: Option, - pub created_by: Option, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs index 4fcaac8..ca15394 100644 --- a/crates/common/src/network.rs +++ b/crates/common/src/network.rs @@ -2,26 +2,17 @@ use bitcode::{DecodeOwned, Encode}; use quinn::{RecvStream, SendStream}; use crate::{ - constant::{ - MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_ATTACHMENTS_PER_MESSAGE, MAXIMUM_AVATAR_BYTES, - MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT, - }, error::Error, event::Event, request::{Request, UploadHeader}, response::Response, }; -const ATTACHMENT_MAX_ENCODED_LENGTH: usize = MAXIMUM_ATTACHMENT_NAME_LENGTH * 4 + 128; pub const UPLOAD_HEADER_MAX_LENGTH: usize = 1024; pub const DOWNLOAD_REQUEST_MAX_READ_LENGTH: usize = 1024; - -const MESSAGE_MAX_ENCODED_LENGTH: usize = - MAXIMUM_MESSAGE_LENGTH * 2 + MAXIMUM_ATTACHMENTS_PER_MESSAGE * ATTACHMENT_MAX_ENCODED_LENGTH; -pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_AVATAR_BYTES + MESSAGE_MAX_ENCODED_LENGTH; -pub const EVENT_MAX_ENCODED_LENGTH: usize = - MESSAGE_MAX_ENCODED_LENGTH * (MAXIMUM_FORWARD_MESSAGES + 2); -pub const RESPONSE_MAX_READ_LENGTH: usize = EVENT_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; +pub const REQUEST_MAX_READ_LENGTH: usize = 64 * 1024; +pub const EVENT_MAX_ENCODED_LENGTH: usize = 16 * 1024 * 1024; +pub const RESPONSE_MAX_READ_LENGTH: usize = 16 * 1024 * 1024; #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -46,13 +37,13 @@ impl StreamKind { #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DownloadStatus { +enum DownloadStatus { Ok = 0, Error = 1, } impl DownloadStatus { - pub fn parse(byte: u8) -> Option { + fn parse(byte: u8) -> Option { match byte { 0 => Some(DownloadStatus::Ok), 1 => Some(DownloadStatus::Error), @@ -73,17 +64,27 @@ pub async fn receive_stream_kind(receive_stream: &mut RecvStream) -> Result, send_stream: &mut SendStream, ) -> Result<(), Error> { - send_stream.write_all(&[status as u8]).await?; + match reply { + Ok(length) => { + send_stream.write_all(&[DownloadStatus::Ok as u8]).await?; + send_stream.write_all(&length.to_le_bytes()).await?; + } + Err(error) => { + send_stream + .write_all(&[DownloadStatus::Error as u8]) + .await?; + send_encoded(&error, send_stream).await?; + } + } + Ok(()) } -pub async fn receive_download_status( - receive_stream: &mut RecvStream, -) -> Result { +async fn receive_download_status(receive_stream: &mut RecvStream) -> Result { let mut byte = [0u8; 1]; receive_stream.read_exact(&mut byte).await?; diff --git a/crates/common/src/share.rs b/crates/common/src/share.rs index 6615fe0..21898e5 100644 --- a/crates/common/src/share.rs +++ b/crates/common/src/share.rs @@ -176,26 +176,6 @@ pub fn options(source_height: u32, refresh: u32, max_height: u32) -> (Vec Vec { - let rungs = [ - top, - Quality { - resolution: Resolution::P720, - fps: Fps::F30, - }, - Quality { - resolution: Resolution::P360, - fps: Fps::F15, - }, - ]; - let mut ladder: Vec = rungs - .into_iter() - .filter(|rung| rung.resolution <= top.resolution && rung.fps <= top.fps) - .collect(); - ladder.dedup(); - ladder -} - pub fn best_codec(encode: &[Codec], decode: &[Codec]) -> Option { Codec::PREFERENCE .into_iter() diff --git a/crates/common/src/time.rs b/crates/common/src/time.rs index ea36244..42c2ef7 100644 --- a/crates/common/src/time.rs +++ b/crates/common/src/time.rs @@ -27,6 +27,6 @@ pub fn range_bounds( ) -> (Option, Option) { ( after_ms.map(id_bound), - before_ms.map(|before| id_bound(before + 1)), + before_ms.map(|before| id_bound(before.saturating_add(1))), ) } diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index e2606e7..22883dc 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -35,51 +35,28 @@ fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidI check_length(text.chars().count(), minimum, maximum) } -fn check( - input: &str, - minimum: usize, - maximum: usize, - ascii_only: bool, -) -> Result<(), InvalidInput> { - if ascii_only && !input.is_ascii() { - return Err(InvalidInput::NotASCII); +fn check_name(name: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { + let allowed = name.bytes().all(|byte| byte.is_ascii_graphic() || byte == b' '); + if !allowed || name != name.trim() { + return Err(InvalidInput::ForbiddenCharacter); } - check_length(input.len(), minimum, maximum) + check_length(name.len(), minimum, maximum) } pub fn validate_username(username: &str) -> Result<(), Error> { - check( - username, - MINIMUM_USERNAME_LENGTH, - MAXIMUM_USERNAME_LENGTH, - true, - ) - .map_err(invalid(Field::User)) + check_name(username, MINIMUM_USERNAME_LENGTH, MAXIMUM_USERNAME_LENGTH) + .map_err(invalid(Field::User)) } pub fn validate_password(password: &str) -> Result<(), Error> { - check( - password, - MINIMUM_PASSWORD_LENGTH, - MAXIMUM_PASSWORD_LENGTH, - false, - ) - .map_err(invalid(Field::Password)) + check_length(password.len(), MINIMUM_PASSWORD_LENGTH, MAXIMUM_PASSWORD_LENGTH) + .map_err(invalid(Field::Password)) } pub fn validate_community_name(name: &str) -> Result<(), Error> { - check( - name, - MINIMUM_COMMUNITY_NAME_LENGTH, - MAXIMUM_COMMUNITY_NAME_LENGTH, - true, - ) - .map_err(invalid(Field::Community)) -} - -pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> { - check(body, MINIMUM_MESSAGE_LENGTH, maximum, false).map_err(invalid(Field::Message)) + check_name(name, MINIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_COMMUNITY_NAME_LENGTH) + .map_err(invalid(Field::Community)) } pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> { @@ -88,7 +65,7 @@ pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> R } else { 0 }; - check(body, minimum, maximum, false).map_err(invalid(Field::Message)) + check_length(body.len(), minimum, maximum).map_err(invalid(Field::Message)) } pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { @@ -189,12 +166,16 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { Ok(()) } -pub fn validate_announcement(text: &str) -> Result<(), Error> { +fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { if text.contains(['\n', '\r']) { - return Err(invalid(Field::Announcement)(InvalidInput::MultiLine)); + return Err(InvalidInput::MultiLine); } - check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(invalid(Field::Announcement)) + check_text(text, minimum, maximum) +} + +pub fn validate_announcement(text: &str) -> Result<(), Error> { + check_line(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(invalid(Field::Announcement)) } pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> { @@ -220,10 +201,8 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> { let Some(reason) = reason else { return Ok(()); }; - if reason.contains(['\n', '\r']) { - return Err(invalid(Field::Reason)(InvalidInput::MultiLine)); - } - check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(invalid(Field::Reason)) + + check_line(reason, 1, MAXIMUM_REASON_LENGTH).map_err(invalid(Field::Reason)) } pub fn validate_forward(count: usize) -> Result<(), Error> { @@ -231,11 +210,7 @@ pub fn validate_forward(count: usize) -> Result<(), Error> { } pub fn validate_status(status: &str) -> Result<(), Error> { - if status.contains(['\n', '\r']) { - return Err(invalid(Field::Status)(InvalidInput::MultiLine)); - } - - check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(invalid(Field::Status)) + check_line(status, 0, MAXIMUM_STATUS_LENGTH).map_err(invalid(Field::Status)) } pub fn validate_device(name: &str) -> Result<(), Error> { diff --git a/crates/pixel/src/lib.rs b/crates/pixel/src/lib.rs index 7220035..52c5635 100644 --- a/crates/pixel/src/lib.rs +++ b/crates/pixel/src/lib.rs @@ -11,6 +11,10 @@ const BYTES_PER_PIXEL: u32 = 4; const RANGE: YuvRange = YuvRange::Limited; const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt709; +fn blank(width: u32, height: u32) -> Vec { + vec![0; (width * height * BYTES_PER_PIXEL) as usize] +} + pub struct Bgra<'a> { pub data: &'a [u8], pub width: u32, @@ -49,7 +53,7 @@ pub fn yuv_to_bgra( width, height, }; - let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; + let mut out = blank(width, height); yuv::yuv420_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; if width <= max_width { return Some((width, height, out)); @@ -82,7 +86,7 @@ pub fn yuyv_to_bgra(data: &[u8], width: u32, height: u32) -> Option> { width, height, }; - let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; + let mut out = blank(width, height); yuv::yuyv422_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; Some(out) } @@ -103,7 +107,7 @@ pub fn nv12_to_bgra(data: &[u8], width: u32, height: u32) -> Option> { width, height, }; - let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; + let mut out = blank(width, height); yuv::yuv_nv12_to_bgra( &image, &mut out, @@ -117,14 +121,14 @@ pub fn nv12_to_bgra(data: &[u8], width: u32, height: u32) -> Option> { } pub fn bgra_to_i420(source: &Bgra, width: u32, height: u32) -> Option { - let scaled = (source.width, source.height) != (width, height); - let resized = match scaled { - true => scale(source, width, height)?, - false => Vec::new(), + let resized = if (source.width, source.height) != (width, height) { + Some(scale(source, width, height)?) + } else { + None }; - let (data, stride) = match scaled { - true => (resized.as_slice(), width * BYTES_PER_PIXEL), - false => (source.data, source.stride), + let (data, stride) = match &resized { + Some(pixels) => (pixels.as_slice(), width * BYTES_PER_PIXEL), + None => (source.data, source.stride), }; let mut planes = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420); yuv::bgra_to_yuv420( diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index 063888f..40fed44 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -15,8 +15,8 @@ use common::{ Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, }, network::{ - DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, receive_upload_header, - send_download_status, send_encoded, send_response, + DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded, receive_upload_header, + send_download_reply, send_response, }, permission, request::{DownloadRequest, UploadHeader}, @@ -37,7 +37,6 @@ use crate::{ community, database::{self, DB, new_id}, error::Error, - message, request::{actor_rank, ensure}, server_settings, user, }; @@ -111,7 +110,7 @@ pub async fn bind( (message_id, attachment_id.as_str(), user_id, community_id), ) .await?; - message::expect_one(bound)?; + database::expect_one(bound)?; } Ok(()) @@ -185,10 +184,10 @@ pub async fn copy( } pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result, Error> { - message::ids_where( - "SELECT id FROM attachment WHERE message_id = ?1", - message_id, + database::ids( conn, + "SELECT id FROM attachment WHERE message_id = ?1", + (message_id,), ) .await } @@ -284,12 +283,7 @@ async fn over_quota( 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 used: i64 = row.get(0)?; + let used = database::scalar_i64(conn, sql, (key,)).await?; Ok(used as u64 + size > limit) } @@ -328,10 +322,10 @@ async fn ensure_quota( } pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result, Error> { - message::ids_where( - "SELECT id FROM attachment WHERE uploader_id = ?1", - user_id, + database::ids( conn, + "SELECT id FROM attachment WHERE uploader_id = ?1", + (user_id,), ) .await } @@ -604,17 +598,23 @@ pub async fn download( let request: DownloadRequest = receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; - match locate(user, &request, db, directory).await { - Ok((path, length)) => { - send_download_status(DownloadStatus::Ok, &mut send_stream).await?; - send_stream.write_all(&length.to_le_bytes()).await?; - stream_file(&path, &mut send_stream).await?; - } - Err(error) => { - let error: CommonError = error.into(); - send_download_status(DownloadStatus::Error, &mut send_stream).await?; - send_encoded(&error, &mut send_stream).await?; - } + let located = locate(user, &request, db, directory) + .await + .map_err(CommonError::from); + send_file(located, &mut send_stream).await +} + +pub async fn send_file( + located: Result<(PathBuf, u64), CommonError>, + send_stream: &mut SendStream, +) -> Result<(), Error> { + let reply = located + .as_ref() + .map(|(_, length)| *length) + .map_err(Clone::clone); + send_download_reply(reply, send_stream).await?; + if let Ok((path, _)) = located { + stream_file(&path, send_stream).await?; } send_stream.finish()?; @@ -651,16 +651,19 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { drop(rows); for entry in std::fs::read_dir(directory)? { - let entry = entry?; + let Ok(entry) = entry else { continue }; let name = entry.file_name().to_string_lossy().into_owned(); let id = name .strip_suffix(THUMB_SUFFIX) .or_else(|| name.strip_suffix(PART_SUFFIX)) .unwrap_or(&name); - let stale = entry.metadata()?.modified()? < stale_at; + let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { + continue; + }; + let stale = modified < stale_at && id < stale_id.as_str(); if stale && !ids.contains(id) { - std::fs::remove_file(entry.path())?; + let _ = std::fs::remove_file(entry.path()); } } @@ -669,7 +672,7 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { #[cfg(test)] mod tests { - use std::{io::Cursor, path::Path, sync::Mutex}; + use std::{io::Cursor, sync::Mutex}; use common::{ model::{AttachmentKind, Rank}, @@ -700,17 +703,13 @@ mod tests { .write_to(&mut png, ImageFormat::Png) .unwrap(); let png = png.into_inner(); - let directory = Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../target/attachment-tests" - )); - std::fs::create_dir_all(directory).unwrap(); + let directory = test::directory(); let header = UploadHeader { community_id: community.id.clone(), name: "pixel.png".to_string(), size: png.len() as u64, }; - let attachment = store(&user, &header, &mut png.as_slice(), &db, directory) + let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) .await .unwrap(); @@ -742,6 +741,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(thumb_path(directory, &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 5de60a1..2368fad 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -12,7 +12,7 @@ use crate::{database::new_id, error::Error, invite, server_ban, server_settings, const SALT_LENGTH: usize = 16; const TOKEN_LENGTH: usize = 32; -fn random_bytes() -> Result<[u8; N], Error> { +pub(crate) fn random_bytes() -> Result<[u8; N], Error> { let mut bytes = [0u8; N]; getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; @@ -137,9 +137,6 @@ pub async fn register( invite_code: Option<&str>, conn: &mut Connection, ) -> Result<(User, String), Error> { - validate_username(username)?; - validate_password(password)?; - let tx = conn.transaction().await?; if server_ban::username_banned(username, &tx).await? { return Err(CommonError::Banned.into()); @@ -148,6 +145,7 @@ pub async fn register( invite::consume(invite_code.ok_or(CommonError::RegistrationClosed)?, &tx).await?; } let user = create_account(username, password, &tx).await?; + admit(&user, &tx).await?; let token = open_session(&user.id, &tx).await?; tx.commit().await?; diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs index 345cfe6..5e787f9 100644 --- a/crates/server/src/backup.rs +++ b/crates/server/src/backup.rs @@ -3,10 +3,7 @@ use std::path::{Path, PathBuf}; use common::{ error::Error as CommonError, model::{AdminAction, BackupInfo, User}, - network::{ - DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, send_download_status, - send_encoded, - }, + network::{DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded}, permission, request::Request, time, @@ -123,19 +120,8 @@ pub async fn download( let request: Request = receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; - match locate(user, request, db, directory).await { - Ok((path, length)) => { - send_download_status(DownloadStatus::Ok, &mut send_stream).await?; - send_stream.write_all(&length.to_le_bytes()).await?; - attachment::stream_file(&path, &mut send_stream).await?; - } - Err(error) => { - let error: CommonError = error.into(); - send_download_status(DownloadStatus::Error, &mut send_stream).await?; - send_encoded(&error, &mut send_stream).await?; - } - } - send_stream.finish()?; - - Ok(()) + let located = locate(user, request, db, directory) + .await + .map_err(CommonError::from); + attachment::send_file(located, &mut send_stream).await } diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs index 6f798ed..43a795c 100644 --- a/crates/server/src/certificate.rs +++ b/crates/server/src/certificate.rs @@ -43,7 +43,15 @@ fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { .map_err(certificate_error)?; fs::write(certificate_path, certified.cert.pem())?; - fs::write(key_path, certified.signing_key.serialize_pem())?; + let _ = fs::remove_file(key_path); + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + std::io::Write::write_all( + &mut options.open(key_path)?, + certified.signing_key.serialize_pem().as_bytes(), + )?; Ok(()) } diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs index bc44834..fc34a35 100644 --- a/crates/server/src/community.rs +++ b/crates/server/src/community.rs @@ -107,22 +107,11 @@ pub async fn create(name: &str, conn: &Connection) -> Result { }) } -pub async fn create_direct(conn: &Connection) -> Result { +pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result { let id = new_id(); conn.execute( "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", - (id.as_str(), Kind::Direct.as_str()), - ) - .await?; - - Ok(id) -} - -pub async fn create_notes(conn: &Connection) -> Result { - let id = new_id(); - conn.execute( - "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", - (id.as_str(), Kind::Notes.as_str()), + (id.as_str(), kind.as_str()), ) .await?; @@ -306,17 +295,17 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result Result { - let mut rows = conn - .query( - "SELECT kind = ?2, name FROM community WHERE id = ?1", - (community_id, Kind::Direct.as_str()), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let direct: i64 = row.get(0)?; - if direct == 0 { - return Ok(row.get(1)?); - } + let prefix = match kind(community_id, conn).await? { + Kind::Group => { + let mut rows = conn + .query("SELECT name FROM community WHERE id = ?1", (community_id,)) + .await?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; + return Ok(row.get(0)?); + } + Kind::Direct => "DM", + Kind::Notes => "Notes", + }; let mut rows = conn .query( @@ -329,7 +318,7 @@ pub async fn label(community_id: &str, conn: &Connection) -> Result(0)?); } - Ok(format!("DM · {}", usernames.join(" & "))) + Ok(format!("{prefix} · {}", usernames.join(" & "))) } #[cfg(test)] diff --git a/crates/server/src/database.rs b/crates/server/src/database.rs index 0c2795f..2bec64e 100644 --- a/crates/server/src/database.rs +++ b/crates/server/src/database.rs @@ -1,5 +1,6 @@ use std::time::Duration; +use common::error::Error as CommonError; use turso::Connection; use crate::error::Error; @@ -320,6 +321,37 @@ pub async fn scalar_i64( Ok(row.get(0)?) } +pub async fn exists( + conn: &Connection, + sql: &str, + params: impl turso::IntoParams, +) -> Result { + Ok(scalar_i64(conn, sql, params).await? != 0) +} + +pub async fn ids( + conn: &Connection, + sql: &str, + params: impl turso::IntoParams, +) -> Result, Error> { + let mut rows = conn.query(sql, params).await?; + + let mut ids = Vec::new(); + while let Some(row) = rows.next().await? { + ids.push(row.get(0)?); + } + + Ok(ids) +} + +pub fn expect_one(affected: u64) -> Result<(), Error> { + if affected != 1 { + return Err(CommonError::NotFound.into()); + } + + Ok(()) +} + async fn migrate(db: &DB) -> Result<(), Error> { let mut conn = connect(db).await?; let applied = user_version(&conn).await?; @@ -335,14 +367,7 @@ async fn migrate(db: &DB) -> Result<(), Error> { } async fn user_version(conn: &Connection) -> Result { - let mut rows = conn.query("PRAGMA user_version", ()).await?; - let row = rows - .next() - .await? - .ok_or(turso::Error::QueryReturnedNoRows)?; - let version: i64 = row.get(0)?; - - Ok(version as usize) + Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize) } pub fn new_id() -> String { diff --git a/crates/server/src/direct.rs b/crates/server/src/direct.rs index 7633c8c..d031ef9 100644 --- a/crates/server/src/direct.rs +++ b/crates/server/src/direct.rs @@ -32,7 +32,7 @@ pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result Error::Common as common::error::Error, std::io::Error => Error::Common as common::error::Error, quinn::ConnectionError => Error::Common as common::error::Error, - quinn::ConnectError => Error::Common as common::error::Error, quinn::ReadError => Error::Common as common::error::Error, - quinn::ReadToEndError => Error::Common as common::error::Error, quinn::ReadExactError => Error::Common as common::error::Error, quinn::WriteError => Error::Common as common::error::Error, quinn::ClosedStream => Error::Common as common::error::Error, diff --git a/crates/server/src/friend.rs b/crates/server/src/friend.rs index a847fcf..dfc4e95 100644 --- a/crates/server/src/friend.rs +++ b/crates/server/src/friend.rs @@ -23,9 +23,7 @@ async fn pair_exists( second: &str, conn: &Connection, ) -> Result { - let count = database::scalar_i64(conn, sql, (first, second)).await?; - - Ok(count > 0) + database::exists(conn, sql, (first, second)).await } async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result { diff --git a/crates/server/src/invitation.rs b/crates/server/src/invitation.rs index 1b217b4..378b975 100644 --- a/crates/server/src/invitation.rs +++ b/crates/server/src/invitation.rs @@ -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 count = database::scalar_i64( + database::exists( conn, - "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2", + "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", (community_id, user_id), ) - .await?; - - Ok(count > 0) + .await } pub async fn insert( diff --git a/crates/server/src/invite.rs b/crates/server/src/invite.rs index d6e97d3..6a56bb1 100644 --- a/crates/server/src/invite.rs +++ b/crates/server/src/invite.rs @@ -5,14 +5,13 @@ use common::{ }; use turso::Connection; -use crate::{error::Error, user}; +use crate::{authentication, error::Error}; const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; const CODE_LENGTH: usize = 8; fn generate() -> Result { - let mut bytes = [0u8; CODE_LENGTH]; - getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; + let bytes = authentication::random_bytes::()?; Ok(bytes .iter() @@ -43,16 +42,12 @@ pub async fn create( code, uses_left: uses, expires_at, - created_by: Some(created_by.clone()), }) } pub async fn list(conn: &Connection) -> Result, Error> { let mut rows = conn - .query( - &format!("SELECT c.code, c.uses_left, c.expires_at, {} FROM invite_code c LEFT JOIN user u ON u.id = c.created_by", user::user_columns("u")), - (), - ) + .query("SELECT code, uses_left, expires_at FROM invite_code", ()) .await?; let mut codes = Vec::new(); @@ -63,7 +58,6 @@ pub async fn list(conn: &Connection) -> Result, Error> { code: row.get(0)?, uses_left: uses_left as u32, expires_at: expires_at.map(|millis| millis as u64), - created_by: user::from_row_at(&row, 3)?, }); } diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index e64666d..4129a30 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -41,6 +41,12 @@ const SERVER_CONFIG_FILE_PATH: &str = concat!( "/../../configs/server_config.toml" ); +fn config_path() -> PathBuf { + std::env::var_os("YUMUSH_CONFIG_DIR") + .map(|dir| PathBuf::from(dir).join("server_config.toml")) + .unwrap_or_else(|| PathBuf::from(SERVER_CONFIG_FILE_PATH)) +} + pub struct ServerConfig { pub database_path: String, pub server_address: String, @@ -49,7 +55,7 @@ pub struct ServerConfig { } fn load_config() -> Result { - let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?; + let content = std::fs::read_to_string(config_path())?; let config = Config::parse(&content)?; Ok(ServerConfig { diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index 5863d4a..463cb2c 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -11,7 +11,7 @@ use common::{ }; use turso::{Connection, Row}; -use crate::{attachment, community, database::new_id, error::Error, user}; +use crate::{attachment, community, database, database::new_id, error::Error, user}; const SEARCH_LIMIT: usize = 200; @@ -256,25 +256,6 @@ 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, @@ -425,7 +406,7 @@ pub async fn close_poll(message_id: &str, conn: &Connection) -> Result Result Result Result, Error> { - ids_where("SELECT id FROM message WHERE user_id = ?1", user_id, conn).await + database::ids( + conn, + "SELECT id FROM message WHERE user_id = ?1", + (user_id,), + ) + .await } pub async fn search( @@ -562,15 +548,14 @@ async fn origin(sources: &[Message], conn: &Connection) -> Result let mut rows = conn .query( - "SELECT name, kind FROM community WHERE id = ?1", - (community_id.as_str(),), + "SELECT name FROM community WHERE id = ?1 AND kind = ?2", + (community_id.as_str(), community::Kind::Group.as_str()), ) .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let name: String = row.get(0)?; - let kind: String = row.get(1)?; - - Ok((kind != "direct").then_some(name)) + Ok(match rows.next().await? { + Some(row) => Some(row.get(0)?), + None => None, + }) } async fn entry(source: &Message, conn: &Connection) -> Result { diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index f06bf1a..a6b92c5 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -95,7 +95,11 @@ pub struct Services { impl Presence { pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) { - self.0.lock().unwrap().insert( + let mut signed = self.0.lock().unwrap(); + if connection.close_reason().is_some() { + return; + } + signed.insert( connection.stable_id(), Signed { user_id: user_id.to_string(), @@ -105,6 +109,14 @@ impl Presence { ); } + pub fn is_online(&self, user_id: &str) -> bool { + self.0 + .lock() + .unwrap() + .values() + .any(|signed| signed.user_id == user_id) + } + pub fn sign_out(&self, connection_id: usize) { self.0.lock().unwrap().remove(&connection_id); } @@ -166,12 +178,9 @@ enum Event { connection: Connection, send_stream: SendStream, }, - SignedIn { - connection_id: usize, - user_id: String, - }, - SignedOut { + Signed { connection_id: usize, + user_id: Option, }, Broadcast(Box), } @@ -254,12 +263,17 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro )); while let Ok(streams) = connection.accept_bi().await { - tokio::spawn(route( + let route = route( connection.clone(), Arc::clone(&state), streams, shared.clone(), - )); + ); + tokio::spawn(async move { + if let Err(error) = route.await { + warn!("stream: {error}"); + } + }); } shared.services.presence.sign_out(connection.stable_id()); @@ -267,7 +281,6 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro if let Some((user_id, token)) = signed_in(&state) { let conn = database::connect(&shared.db).await?; - authentication::seen(&user_id, &token, &conn).await?; let mut broadcasts = request::leave_connection_voice( &shared.services.voice, &shared.services.share, @@ -278,6 +291,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro broadcasts .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); publish(&shared, broadcasts).await; + authentication::seen(&user_id, &token, &conn).await?; } Ok(()) @@ -285,7 +299,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro async fn relay_datagrams(connection: Connection, state: Arc>, shared: Shared) { while let Ok(bytes) = connection.read_datagram().await { - if signed_user_id(&state).is_some() { + if matches!(*state.lock().unwrap(), State::Authenticated { .. }) { shared.services.voice.relay(connection.stable_id(), &bytes); let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); publish(&shared, broadcasts).await; @@ -299,12 +313,13 @@ async fn route( (send_stream, mut receive_stream): (SendStream, RecvStream), shared: Shared, ) -> Result<(), Error> { - match receive_stream_kind(&mut receive_stream).await? { + let kind = receive_stream_kind(&mut receive_stream).await?; + let user = signed_user(&state); + match kind { StreamKind::Request => { answer(connection, state, (send_stream, receive_stream), shared).await } StreamKind::Upload => { - let user = signed_user(&state); attachment::upload( user.as_ref(), receive_stream, @@ -315,7 +330,6 @@ async fn route( .await } StreamKind::Download => { - let user = signed_user(&state); attachment::download( user.as_ref(), receive_stream, @@ -326,7 +340,6 @@ async fn route( .await } StreamKind::Backup => { - let user = signed_user(&state); backup::download( user.as_ref(), receive_stream, @@ -362,29 +375,27 @@ async fn answer( if before != after { let connection_id = connection.stable_id(); - let (event, presence_user_id) = match after { - Some((user_id, token)) => { - shared - .services - .presence - .sign_in(&connection, &user_id, &token); - ( - Event::SignedIn { - connection_id, - user_id: user_id.clone(), - }, - Some(user_id), - ) - } - None => { - shared.services.presence.sign_out(connection_id); - let user_id = before.map(|(user_id, _)| user_id); - (Event::SignedOut { connection_id }, user_id) + shared.services.visits.forget(connection_id); + match &after { + Some((user_id, token)) => shared.services.presence.sign_in(&connection, user_id, token), + None => shared.services.presence.sign_out(connection_id), + } + let before_id = before.map(|(user_id, _)| user_id); + let after_id = after.map(|(user_id, _)| user_id); + let _ = shared + .event_sender + .send(Event::Signed { + connection_id, + user_id: after_id.clone(), + }) + .await; + if let Some(user_id) = &before_id { + broadcast_presence(&shared, user_id).await; + } + if after_id != before_id { + if let Some(user_id) = &after_id { + broadcast_presence(&shared, user_id).await; } - }; - let _ = shared.event_sender.send(event).await; - if let Some(user_id) = presence_user_id { - broadcast_presence(&shared, &user_id).await; } } @@ -422,13 +433,6 @@ fn signed_user(state: &Mutex) -> Option { } } -fn signed_user_id(state: &Mutex) -> Option { - match &*state.lock().unwrap() { - State::Anonymous => None, - State::Authenticated { user, .. } => Some(user.id.clone()), - } -} - fn signed_in(state: &Mutex) -> Option<(String, String)> { match &*state.lock().unwrap() { State::Anonymous => None, @@ -470,7 +474,7 @@ async fn the_actor(mut event_receiver: mpsc::Receiver, visits: Visits) { writer, }); } - Event::SignedIn { + Event::Signed { connection_id, user_id, } => { @@ -478,15 +482,7 @@ async fn the_actor(mut event_receiver: mpsc::Receiver, visits: Visits) { .iter_mut() .find(|session| session.connection_id == connection_id) { - session.user_id = Some(user_id); - } - } - Event::SignedOut { connection_id } => { - if let Some(session) = sessions - .iter_mut() - .find(|session| session.connection_id == connection_id) - { - session.user_id = None; + session.user_id = user_id; } } Event::Broadcast(broadcast) => { @@ -506,13 +502,10 @@ async fn the_actor(mut event_receiver: mpsc::Receiver, visits: Visits) { match session.event_sender.try_send(Arc::clone(&event)) { Ok(()) => true, - Err(mpsc::error::TrySendError::Full(_)) => { - warn!("session buffer is full {user_id}"); - session.writer.abort(); - false - } - Err(mpsc::error::TrySendError::Closed(_)) => { + Err(error) => { + warn!("session dropped {user_id}: {error}"); session.writer.abort(); + session.connection.close(0u32.into(), b"slow"); false } } diff --git a/crates/server/src/notes.rs b/crates/server/src/notes.rs index b1d8293..3e96aa0 100644 --- a/crates/server/src/notes.rs +++ b/crates/server/src/notes.rs @@ -19,7 +19,7 @@ pub async fn open(me: &str, conn: &mut Connection) -> Result { let community_id = match find(me, &tx).await? { Some(community_id) => community_id, None => { - let community_id = community::create_notes(&tx).await?; + let community_id = community::create_fixed(community::Kind::Notes, &tx).await?; user_community::join(me, &community_id, Rank::Owner, &tx).await?; tx.execute( "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)", diff --git a/crates/server/src/overview.rs b/crates/server/src/overview.rs index fd7d631..39cc7e1 100644 --- a/crates/server/src/overview.rs +++ b/crates/server/src/overview.rs @@ -13,11 +13,11 @@ pub async fn read( "SELECT (SELECT COUNT(*) FROM user), (SELECT COUNT(*) FROM user WHERE role = ?1), - (SELECT COUNT(*) FROM community WHERE kind != ?2), + (SELECT COUNT(*) FROM community WHERE kind = ?2), (SELECT COALESCE(SUM(size), 0) FROM attachment) + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar) + (SELECT COALESCE(SUM(length(data)), 0) FROM community_avatar)", - (Role::Builder.as_str(), Kind::Direct.as_str()), + (Role::Builder.as_str(), Kind::Group.as_str()), ) .await?; let row = rows diff --git a/crates/server/src/report.rs b/crates/server/src/report.rs index c67e907..5c152b4 100644 --- a/crates/server/src/report.rs +++ b/crates/server/src/report.rs @@ -17,14 +17,12 @@ pub async fn is_open( message_id: Option<&str>, conn: &Connection, ) -> Result { - let found = database::scalar_i64( + database::exists( conn, "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), ) - .await?; - - Ok(found != 0) + .await } pub async fn insert( diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 5614a10..cf7ed73 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -17,8 +17,8 @@ use common::{ share::{Kind, Share}, time::{self, MINUTE_MILLIS}, validate::{ - validate_avatar_size, validate_forward, validate_message_body, validate_new_message, - validate_poll, validate_reaction, validate_reason, validate_server_settings, validate_vote, + validate_avatar_size, validate_forward, validate_new_message, validate_poll, + validate_reaction, validate_reason, validate_server_settings, validate_vote, }, }; use turso::Connection; @@ -88,23 +88,16 @@ async fn dispatch( let (user, token) = authentication::register(&username, &password, invite.as_deref(), &mut conn) .await?; - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; - sign_in(state, user, token, broadcasts) + enter(state, user, token, voice, share, connection, &conn).await? } Request::Login { username, password } => { limit_logins(rate_limit, connection, &conn).await?; let (user, token) = authentication::login(&username, &password, &conn).await?; - stats::mark_active(&user.id, &conn).await?; - record_address(&user, connection, &conn).await?; - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; - sign_in(state, user, token, broadcasts) + enter(state, user, token, voice, share, connection, &conn).await? } Request::Resume { token } => { let user = authentication::resume(&token, &conn).await?; - stats::mark_active(&user.id, &conn).await?; - record_address(&user, connection, &conn).await?; - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; - sign_in(state, user, token, broadcasts) + enter(state, user, token, voice, share, connection, &conn).await? } Request::Detach => { authenticated(state, &conn).await?; @@ -347,6 +340,9 @@ async fn dispatch( let mut broadcasts = user_updated(&user, &conn).await?; if permission::is_builder(role) { broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); + } else { + user::set_ghost(&user_id, false, &conn).await?; + presence.disconnect(&user_id); } (Response::User(user), broadcasts) } @@ -438,6 +434,8 @@ async fn dispatch( tx.commit().await?; if me.id == user_id { set_state(state, State::Anonymous); + } else { + presence.disconnect(&user_id); } (Response::User(deleted), broadcasts) } @@ -733,9 +731,11 @@ async fn dispatch( Request::UpdateMessage { message_id, body } => { let me = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; + allowed(&me, &existing.community_id, &conn, permission::can_post).await?; ensure(existing.user_id == me.id)?; - validate_message_body( + validate_new_message( &body, + 0, server_settings::read(&conn).await?.max_message_length as usize, )?; let updated = message::update(&message_id, &body, &conn).await?; @@ -1847,7 +1847,7 @@ async fn effective_presence( user_id: &str, conn: &Connection, ) -> Result { - if !presence.user_ids().iter().any(|id| id == user_id) { + if !presence.is_online(user_id) { return Ok(Presence::Offline); } @@ -2082,6 +2082,22 @@ async fn share_left( Ok(broadcasts) } +async fn enter( + state: &Mutex, + user: User, + token: String, + voice: &Voice, + share: &Shares, + connection: Option<&quinn::Connection>, + conn: &Connection, +) -> Result { + stats::mark_active(&user.id, conn).await?; + record_address(&user, connection, conn).await?; + let broadcasts = leave_connection_voice(voice, share, connection, conn).await?; + + Ok(sign_in(state, user, token, broadcasts)) +} + fn sign_in(state: &Mutex, user: User, token: String, broadcasts: Vec) -> Outcome { set_state( state, diff --git a/crates/server/src/server_ban.rs b/crates/server/src/server_ban.rs index 96a2e5a..729e15f 100644 --- a/crates/server/src/server_ban.rs +++ b/crates/server/src/server_ban.rs @@ -7,7 +7,6 @@ use turso::Connection; use crate::{ database::{self, new_id}, error::Error, - user, }; pub async fn insert( @@ -30,7 +29,7 @@ pub async fn insert( pub async fn list(conn: &Connection) -> Result, Error> { let mut rows = conn .query( - &format!("SELECT b.id, b.kind, b.value, b.reason, {} FROM server_ban b LEFT JOIN user u ON u.id = b.created_by ORDER BY b.kind, b.value", user::user_columns("u")), + "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", (), ) .await?; @@ -43,7 +42,6 @@ pub async fn list(conn: &Connection) -> Result, Error> { kind: ServerBanKind::parse(&text).ok_or(CommonError::Server)?, value: row.get(2)?, reason: row.get(3)?, - created_by: user::from_row_at(&row, 4)?, }); } @@ -51,14 +49,12 @@ pub async fn list(conn: &Connection) -> Result, Error> { } async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result { - let found = database::scalar_i64( + database::exists( conn, "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", (kind.as_str(), value), ) - .await?; - - Ok(found != 0) + .await } pub async fn username_banned(username: &str, conn: &Connection) -> Result { diff --git a/crates/server/src/server_settings.rs b/crates/server/src/server_settings.rs index 594a232..1925517 100644 --- a/crates/server/src/server_settings.rs +++ b/crates/server/src/server_settings.rs @@ -1,7 +1,7 @@ use common::model::ServerSettings; use turso::Connection; -use crate::error::Error; +use crate::{error::Error, user}; const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute"; @@ -25,35 +25,23 @@ pub async fn read(conn: &Connection) -> Result { .next() .await? .ok_or(turso::Error::QueryReturnedNoRows)?; - let registration_open: i64 = row.get(1)?; - let max_attachment_bytes: i64 = row.get(2)?; - let maintenance: i64 = row.get(3)?; - let user_quota_bytes: i64 = row.get(4)?; - 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)?; - let messages_per_minute: i64 = row.get(12)?; - let logins_per_minute: i64 = row.get(13)?; + let int = |index: usize| -> Result { Ok(row.get(index)?) }; Ok(ServerSettings { name: row.get(0)?, - registration_open: registration_open != 0, - max_attachment_bytes: max_attachment_bytes as u64, - maintenance: maintenance != 0, - user_quota_bytes: user_quota_bytes as u64, - 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, - 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, - messages_per_minute: messages_per_minute as u32, - logins_per_minute: logins_per_minute as u32, + registration_open: user::bool_at(&row, 1)?, + max_attachment_bytes: int(2)? as u64, + maintenance: user::bool_at(&row, 3)?, + user_quota_bytes: int(4)? as u64, + community_quota_bytes: int(5)? as u64, + message_retention_days: int(6)? as u32, + attachment_retention_days: int(7)? as u32, + announcement: row.get(8)?, + max_communities_per_user: int(9)? as u32, + max_message_length: int(10)? as u32, + max_avatar_bytes: int(11)? as u64, + messages_per_minute: int(12)? as u32, + logins_per_minute: int(13)? as u32, }) } diff --git a/crates/server/src/share.rs b/crates/server/src/share.rs index 06f8605..da92eb1 100644 --- a/crates/server/src/share.rs +++ b/crates/server/src/share.rs @@ -308,10 +308,9 @@ impl Shares { } pub fn relay(&self, connection_id: usize, packet: &[u8]) -> Vec { - let datagram = Datagram::decode(packet); - let kind = match datagram { - Some(Datagram::Video(fragment)) => fragment.kind, - Some(Datagram::ShareAudio { .. }) => Kind::Screen, + let (kind, fragment) = match Datagram::decode(packet) { + Some(Datagram::Video(fragment)) => (fragment.kind, Some(fragment)), + Some(Datagram::ShareAudio { .. }) => (Kind::Screen, None), _ => return Vec::new(), }; let mut sharings = self.0.lock().unwrap(); @@ -325,30 +324,24 @@ impl Shares { return Vec::new(); }; let bytes = Bytes::from(relay); - match datagram { - Some(Datagram::Video(fragment)) => { - let before = sharing.layers(); - for viewer in &mut sharing.viewers { - if fragment.keyframe { - viewer.forward = viewer.forward.on_keyframe(fragment.layer); - } - if viewer.forward.live() == Some(fragment.layer) { - let _ = viewer.connection.send_datagram(bytes.clone()); - } - } - - layers_changed(sharer_id, kind, sharing, before) - .into_iter() - .collect() + let Some(fragment) = fragment else { + for viewer in &sharing.viewers { + let _ = viewer.connection.send_datagram(bytes.clone()); } - Some(Datagram::ShareAudio { .. }) => { - for viewer in &sharing.viewers { - let _ = viewer.connection.send_datagram(bytes.clone()); - } - - Vec::new() + return Vec::new(); + }; + let before = sharing.layers(); + for viewer in &mut sharing.viewers { + if fragment.keyframe { + viewer.forward = viewer.forward.on_keyframe(fragment.layer); + } + if viewer.forward.live() == Some(fragment.layer) { + let _ = viewer.connection.send_datagram(bytes.clone()); } - _ => Vec::new(), } + + layers_changed(sharer_id, kind, sharing, before) + .into_iter() + .collect() } } diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index ca4d617..6806969 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -8,7 +8,10 @@ use common::{ use image::ImageFormat; use turso::{Connection, Row}; -use crate::{database::new_id, error::Error}; +use crate::{ + database::{self, new_id}, + error::Error, +}; pub fn user_columns(alias: &str) -> String { format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") @@ -46,6 +49,32 @@ async fn one(sql: &str, params: impl turso::IntoParams, conn: &Connection) -> Re from_row(&row) } +async fn set(column: &str, params: impl turso::IntoParams, conn: &Connection) -> Result<(), Error> { + conn.execute( + &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"), + params, + ) + .await?; + + Ok(()) +} + +async fn set_returning( + column: &str, + params: impl turso::IntoParams, + conn: &Connection, +) -> Result { + one( + &format!( + "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), + params, + conn, + ) + .await +} + pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { one( &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")), @@ -71,10 +100,7 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result { } 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(CommonError::NotFound)?; - - bool_at(&row, 0) + database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await } pub async fn by_username(username: &str, conn: &Connection) -> Result, Error> { @@ -140,29 +166,13 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result< return Err(CommonError::Taken.into()); } - one( - &format!( - "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, username), - conn, - ) - .await + set_returning("username", (user_id, username), conn).await } pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result { validate_status(status)?; - one( - &format!( - "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, status), - conn, - ) - .await + set_returning("status", (user_id, status), conn).await } pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { @@ -217,15 +227,7 @@ async fn set_avatar_id( avatar_id: Option<&str>, conn: &Connection, ) -> Result { - one( - &format!( - "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, avatar_id), - conn, - ) - .await + set_returning("avatar_id", (user_id, avatar_id), conn).await } pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error> { @@ -241,15 +243,7 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error } pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result { - one( - &format!( - "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", - user_columns("user") - ), - (user_id, role.as_str()), - conn, - ) - .await + set_returning("role", (user_id, role.as_str()), conn).await } pub async fn suspended(user_id: &str, conn: &Connection) -> Result { @@ -270,20 +264,16 @@ pub async fn set_timeout( until: Option, conn: &Connection, ) -> Result<(), Error> { - conn.execute( - "UPDATE user SET suspended_until = ?2 WHERE id = ?1", + set( + "suspended_until", (user_id, until.map(|until| until as i64)), + conn, ) - .await?; - - Ok(()) + .await } pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), Error> { - conn.execute("UPDATE user SET last_ip = ?2 WHERE id = ?1", (user_id, ip)) - .await?; - - Ok(()) + set("last_ip", (user_id, ip), conn).await } pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, Error> { @@ -296,48 +286,24 @@ pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, } pub async fn builder_ids(conn: &Connection) -> Result, Error> { - let mut rows = conn - .query( - "SELECT id FROM user WHERE role = ?1", - (Role::Builder.as_str(),), - ) - .await?; - let mut ids = Vec::new(); - while let Some(row) = rows.next().await? { - ids.push(row.get(0)?); - } - - Ok(ids) + database::ids( + conn, + "SELECT id FROM user WHERE role = ?1", + (Role::Builder.as_str(),), + ) + .await } pub async fn set_suspended(user_id: &str, suspended: bool, conn: &Connection) -> Result<(), Error> { - conn.execute( - "UPDATE user SET suspended = ?2 WHERE id = ?1", - (user_id, i64::from(suspended)), - ) - .await?; - - Ok(()) + set("suspended", (user_id, i64::from(suspended)), conn).await } pub async fn set_voice_muted(user_id: &str, muted: bool, conn: &Connection) -> Result<(), Error> { - conn.execute( - "UPDATE user SET voice_muted = ?2 WHERE id = ?1", - (user_id, i64::from(muted)), - ) - .await?; - - Ok(()) + set("voice_muted", (user_id, i64::from(muted)), conn).await } pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), Error> { - conn.execute( - "UPDATE user SET ghost = ?2 WHERE id = ?1", - (user_id, i64::from(ghost)), - ) - .await?; - - Ok(()) + set("ghost", (user_id, i64::from(ghost)), conn).await } pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { @@ -366,13 +332,7 @@ pub async fn update_presence( presence: Presence, conn: &Connection, ) -> Result<(), Error> { - conn.execute( - "UPDATE user SET presence = ?2 WHERE id = ?1", - (user_id, presence.as_str()), - ) - .await?; - - Ok(()) + set("presence", (user_id, presence.as_str()), conn).await } pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result { @@ -394,13 +354,7 @@ pub async fn set_password_hash( password_hash: &str, conn: &Connection, ) -> Result<(), Error> { - conn.execute( - "UPDATE user SET password_hash = ?2 WHERE id = ?1", - (user_id, password_hash), - ) - .await?; - - Ok(()) + set("password_hash", (user_id, password_hash), conn).await } pub async fn all(conn: &Connection) -> Result, Error> { diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index 6524d5c..9c45cba 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -1,10 +1,12 @@ +use std::collections::HashMap; + use common::{ error::Error as CommonError, - model::{Ban, Member, Rank, Unread}, + model::{Ban, Member, Rank, Unread, mentions}, }; use turso::{Connection, Row}; -use crate::{community, error::Error, user}; +use crate::{community, database, error::Error, user}; fn rank_of(row: &Row, index: usize) -> Result { let text: String = row.get(index)?; @@ -91,26 +93,47 @@ pub async fn unreads( username: &str, conn: &Connection, ) -> Result, Error> { - let mention = format!("@{}", username.to_lowercase()); let mut rows = conn .query( - "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read) AND instr(lower(m.body), ?2) > 0), uc.last_read FROM user_community uc WHERE uc.user_id = ?1", - (user_id, mention.as_str()), + "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), uc.last_read FROM user_community uc WHERE uc.user_id = ?1", + (user_id,), ) .await?; let mut unreads = Vec::new(); while let Some(row) = rows.next().await? { let messages: i64 = row.get(1)?; - let mentions: i64 = row.get(2)?; unreads.push(Unread { community_id: row.get(0)?, messages: messages as u32, - mentions: mentions as u32, - last_read: row.get::>(3)?, + mentions: 0, + last_read: row.get::>(2)?, }); } + let mention = format!("@{}", username.to_lowercase()); + let mut rows = conn + .query( + "SELECT m.community_id, m.body FROM message m JOIN user_community uc ON uc.community_id = m.community_id AND uc.user_id = ?1 WHERE m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read) AND instr(lower(m.body), ?2) > 0", + (user_id, mention.as_str()), + ) + .await?; + + let mut mention_counts: HashMap = HashMap::new(); + while let Some(row) = rows.next().await? { + let body: String = row.get(1)?; + if mentions(&body, username) { + *mention_counts.entry(row.get::(0)?).or_default() += 1; + } + } + + for unread in &mut unreads { + unread.mentions = mention_counts + .get(&unread.community_id) + .copied() + .unwrap_or_default(); + } + Ok(unreads) } @@ -134,32 +157,23 @@ pub async fn members(community_id: &str, conn: &Connection) -> Result Result { - let mut rows = conn - .query( - "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3", - (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::Server)?; - let count: i64 = row.get(0)?; + let count = database::scalar_i64( + conn, + "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3", + (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), + ) + .await?; Ok(count as usize) } pub async fn owned(user_id: &str, conn: &Connection) -> Result, Error> { - let mut rows = conn - .query( - "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", - (user_id, Rank::Owner.as_str()), - ) - .await?; - - let mut community_ids = Vec::new(); - while let Some(row) = rows.next().await? { - community_ids.push(row.get(0)?); - } - - Ok(community_ids) + database::ids( + conn, + "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", + (user_id, Rank::Owner.as_str()), + ) + .await } pub async fn ban( @@ -192,16 +206,12 @@ pub async fn is_banned( community_id: &str, conn: &Connection, ) -> Result { - let mut rows = conn - .query( - "SELECT COUNT(*) FROM ban WHERE user_id = ?1 AND community_id = ?2", - (user_id, community_id), - ) - .await?; - let row = rows.next().await?.ok_or(CommonError::NotFound)?; - let count: i64 = row.get(0)?; - - Ok(count > 0) + database::exists( + conn, + "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)", + (user_id, community_id), + ) + .await } pub async fn bans(community_id: &str, conn: &Connection) -> Result, Error> { diff --git a/crates/server/src/voice.rs b/crates/server/src/voice.rs index 67cdf3f..92ae013 100644 --- a/crates/server/src/voice.rs +++ b/crates/server/src/voice.rs @@ -59,6 +59,14 @@ impl Room { .any(|participant| !participant.ghost) } + fn user_ids(&self, keep: impl Fn(&Participant) -> bool) -> Vec { + self.participants + .iter() + .filter(|participant| keep(participant)) + .map(|participant| participant.user_id.clone()) + .collect() + } + fn admit(&mut self) { if self.occupied() { self.outcome = Outcome::Answered; @@ -159,12 +167,7 @@ impl Voice { .lock() .unwrap() .get(community_id) - .map(|room| { - room.participants - .iter() - .map(|participant| participant.user_id.clone()) - .collect() - }) + .map(|room| room.user_ids(|_| true)) .unwrap_or_default() } @@ -178,7 +181,7 @@ impl Voice { pub fn leave_connection(&self, connection_id: usize) -> Option { let mut rooms = self.0.lock().unwrap(); - let user_id = find(&rooms, connection_id)?.user_id.clone(); + let user_id = find(&rooms, connection_id)?.1.user_id.clone(); leave_locked(&mut rooms, &user_id) } @@ -201,13 +204,7 @@ impl Voice { .lock() .unwrap() .get(community_id) - .map(|room| { - room.participants - .iter() - .filter(|participant| !participant.ghost) - .map(|participant| participant.user_id.clone()) - .collect() - }) + .map(|room| room.user_ids(|participant| !participant.ghost)) .unwrap_or_default() } @@ -217,19 +214,11 @@ impl Voice { .unwrap() .iter() .map(|(community_id, room)| { - let user_ids = room - .participants - .iter() - .map(|participant| participant.user_id.clone()) - .collect(); - let ghost_ids = room - .participants - .iter() - .filter(|participant| participant.ghost) - .map(|participant| participant.user_id.clone()) - .collect(); - - (community_id.clone(), user_ids, ghost_ids) + ( + community_id.clone(), + room.user_ids(|_| true), + room.user_ids(|participant| participant.ghost), + ) }) .collect() } @@ -251,18 +240,7 @@ impl Voice { return; }; let rooms = self.0.lock().unwrap(); - let Some(room) = rooms.values().find(|room| { - room.participants - .iter() - .any(|participant| participant.connection.stable_id() == connection_id) - }) else { - return; - }; - let Some(sender) = room - .participants - .iter() - .find(|participant| participant.connection.stable_id() == connection_id) - else { + let Some((room, sender)) = find(&rooms, connection_id) else { return; }; if sender.muted { @@ -294,11 +272,13 @@ impl Voice { } } -fn find(rooms: &Rooms, connection_id: usize) -> Option<&Participant> { - rooms - .values() - .flat_map(|room| &room.participants) - .find(|participant| participant.connection.stable_id() == connection_id) +fn find(rooms: &Rooms, connection_id: usize) -> Option<(&Room, &Participant)> { + rooms.values().find_map(|room| { + room.participants + .iter() + .find(|participant| participant.connection.stable_id() == connection_id) + .map(|sender| (room, sender)) + }) } fn left(community_id: &str, participant: Participant, call: Option) -> Left { diff --git a/crates/spectrum/src/lib.rs b/crates/spectrum/src/lib.rs index 0eec0e5..8159291 100644 --- a/crates/spectrum/src/lib.rs +++ b/crates/spectrum/src/lib.rs @@ -39,13 +39,11 @@ impl Analyzer { } pub fn bands(&self, samples: &[f32]) -> Vec { - let offset = WINDOW.saturating_sub(samples.len()); let mut buffer = vec![Complex::default(); WINDOW]; - for (index, sample) in samples.iter().rev().take(WINDOW).enumerate() { - let at = WINDOW - 1 - index; - if at >= offset { - buffer[at].re = sample * self.hann[at]; - } + let tail = &samples[samples.len().saturating_sub(WINDOW)..]; + let start = WINDOW - tail.len(); + for (index, sample) in tail.iter().enumerate() { + buffer[start + index].re = sample * self.hann[start + index]; } self.fft.process(&mut buffer); self.edges