Simplify the whole workspace and fix the bugs found on the way
Browse files at this commitd58bc1979903a6140f9cfbc1232fc118714e2cf0Parent: b2c96e7- refactor
- simplify the whole workspace and fix the bugs found on the way
92 changed files +2554 -2904
- crates/client/Cargo.toml +3 -7
- crates/client/src/accounts.rs +3 -23
- crates/client/src/gui.rs +2 -0
- crates/client/src/gui/auth.rs +13 -36
- crates/client/src/gui/builder.rs +35 -4
- crates/client/src/gui/builder/access.rs +10 -22
- crates/client/src/gui/builder/backups.rs +13 -8
- crates/client/src/gui/builder/communities.rs +5 -8
- crates/client/src/gui/builder/log.rs +27 -35
- crates/client/src/gui/builder/messages.rs +20 -14
- crates/client/src/gui/builder/reports.rs +23 -32
- crates/client/src/gui/builder/server.rs +27 -18
- crates/client/src/gui/builder/storage.rs +21 -20
- crates/client/src/gui/builder/ui.rs +24 -19
- crates/client/src/gui/builder/users.rs +8 -10
- crates/client/src/gui/camera_view.rs +24 -30
- crates/client/src/gui/chat.rs +133 -160
- crates/client/src/gui/community_settings.rs +48 -73
- crates/client/src/gui/composer.rs +123 -96
- crates/client/src/gui/forward.rs +8 -11
- crates/client/src/gui/media_view.rs +1 -1
- crates/client/src/gui/message_actions.rs +95 -129
- crates/client/src/gui/poll.rs +25 -32
- crates/client/src/gui/profile.rs +16 -24
- crates/client/src/gui/settings_page.rs +44 -48
- crates/client/src/gui/share_view.rs +43 -46
- crates/client/src/gui/sidebar.rs +99 -109
- crates/client/src/gui/snippet.rs +7 -8
- crates/client/src/gui/social.rs +14 -35
- crates/client/src/gui/voice_note.rs +21 -13
- crates/client/src/gui/widget.rs +116 -0
- crates/client/src/lib.rs +27 -2
- crates/client/src/main.rs +5 -1
- crates/client/src/media/decode.rs +60 -52
- crates/client/src/media/meter.rs +8 -9
- crates/client/src/media/mod.rs +7 -5
- crates/client/src/media/resample.rs +6 -5
- crates/client/src/media/voice_note.rs +3 -7
- crates/client/src/mutes.rs +5 -19
- crates/client/src/network.rs +378 -504
- crates/client/src/settings.rs +32 -34
- crates/client/src/share/audio_capture.rs +19 -46
- crates/client/src/share/audio_capture_windows.rs +12 -40
- crates/client/src/share/camera.rs +14 -10
- crates/client/src/share/capture.rs +57 -19
- crates/client/src/share/capture_windows.rs +7 -3
- crates/client/src/share/convert.rs +0 -13
- crates/client/src/share/encode.rs +9 -12
- crates/client/src/share/frame.rs +12 -0
- crates/client/src/share/mod.rs +4 -1
- crates/client/src/share/reassembly.rs +2 -6
- crates/client/src/share/session.rs +40 -77
- crates/client/src/share/unsupported.rs +52 -0
- crates/client/src/tray.rs +154 -154
- crates/client/src/voice/audio.rs +1 -20
- crates/client/src/voice/audio/coreaudio.rs +25 -59
- crates/client/src/voice/audio/pipewire.rs +60 -65
- crates/client/src/voice/audio/wasapi.rs +37 -40
- crates/client/src/voice/engine.rs +2 -2
- crates/client/src/voice/mod.rs +12 -31
- crates/common/src/error.rs +7 -23
- crates/common/src/model.rs +6 -4
- crates/common/src/network.rs +21 -20
- crates/common/src/share.rs +0 -20
- crates/common/src/time.rs +1 -1
- crates/common/src/validate.rs +22 -47
- crates/pixel/src/lib.rs +14 -10
- crates/server/src/attachment.rs +37 -38
- crates/server/src/authentication.rs +2 -4
- crates/server/src/backup.rs +5 -19
- crates/server/src/certificate.rs +9 -1
- crates/server/src/community.rs +14 -25
- crates/server/src/database.rs +33 -8
- crates/server/src/direct.rs +1 -1
- crates/server/src/error.rs +0 -2
- crates/server/src/friend.rs +1 -3
- crates/server/src/invitation.rs +3 -5
- crates/server/src/invite.rs +3 -9
- crates/server/src/lib.rs +7 -1
- crates/server/src/message.rs +15 -30
- crates/server/src/network.rs +52 -59
- crates/server/src/notes.rs +1 -1
- crates/server/src/overview.rs +2 -2
- crates/server/src/report.rs +2 -4
- crates/server/src/request.rs +30 -14
- crates/server/src/server_ban.rs +3 -7
- crates/server/src/server_settings.rs +15 -27
- crates/server/src/share.rs +19 -26
- crates/server/src/user.rs +51 -97
- crates/server/src/user_community.rs +49 -39
- crates/server/src/voice.rs +24 -44
- crates/spectrum/src/lib.rs +4 -6
crates/client/Cargo.tomlmodified+3 -7
| @@ -15,14 +15,9 @@ gpui-kit = { version = "0.11.0", features = ["syntect"] } | |||
| 15 | ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 15 | ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 16 | ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 16 | ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 17 | ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 17 | ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 18 | -ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | ||
| 19 | -ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | ||
| 20 | ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 18 | ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 21 | ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 19 | ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 22 | ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 20 | ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 23 | -ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | ||
| 24 | -ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | ||
| 25 | -ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | ||
| 26 | ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 21 | ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 27 | ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 22 | ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| 28 | ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } | 23 | ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "c2d94dab62fc63b19f3abf4efefbb6e6131955b4" } |
| @@ -32,13 +27,14 @@ ureq = "3.5.2" | |||
| 32 | bytes = "1.12.2" | 27 | bytes = "1.12.2" |
| 33 | tracing = "0.1.44" | 28 | tracing = "0.1.44" |
| 34 | tracing-subscriber = "0.3.23" | 29 | tracing-subscriber = "0.3.23" |
| 35 | -uuid = "1.29.3" | ||
| 36 | jiff = "1.0.2" | 30 | jiff = "1.0.2" |
| 37 | dirs = "7.0.0" | 31 | dirs = "7.0.0" |
| 38 | image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } | 32 | image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } |
| 39 | -nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } | ||
| 40 | rtrb = "0.4.1" | 33 | rtrb = "0.4.1" |
| 41 | 34 | ||
| 35 | +[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] | ||
| 36 | +nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } | ||
| 37 | + | ||
| 42 | [target.'cfg(target_os = "linux")'.dependencies] | 38 | [target.'cfg(target_os = "linux")'.dependencies] |
| 43 | pipewire = { version = "0.10.1", features = ["v0_3_49"] } | 39 | pipewire = { version = "0.10.1", features = ["v0_3_49"] } |
| 44 | ksni = "0.3.7" | 40 | ksni = "0.3.7" |
crates/client/src/accounts.rsmodified+3 -23
| @@ -1,9 +1,6 @@ | |||
| 1 | -use std::{fs, path::PathBuf}; | ||
| 2 | - | ||
| 3 | use common::model::User; | 1 | use common::model::User; |
| 4 | -use tracing::warn; | ||
| 5 | 2 | ||
| 6 | -use crate::config_file; | 3 | +use crate::{read_config, write_config}; |
| 7 | 4 | ||
| 8 | #[derive(Debug, Clone, PartialEq, Eq)] | 5 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 9 | pub struct Account { | 6 | pub struct Account { |
| @@ -70,8 +67,7 @@ impl Accounts { | |||
| 70 | } | 67 | } |
| 71 | 68 | ||
| 72 | pub fn load() -> Accounts { | 69 | pub fn load() -> Accounts { |
| 73 | - let Some(content) = config_file("accounts").and_then(|path| fs::read_to_string(path).ok()) | 70 | + let Some(content) = read_config("accounts") else { |
| 74 | - else { | ||
| 75 | return Accounts::default(); | 71 | return Accounts::default(); |
| 76 | }; | 72 | }; |
| 77 | let mut accounts = Accounts::default(); | 73 | let mut accounts = Accounts::default(); |
| @@ -92,9 +88,6 @@ pub fn load() -> Accounts { | |||
| 92 | } | 88 | } |
| 93 | 89 | ||
| 94 | fn save(accounts: &Accounts) { | 90 | fn save(accounts: &Accounts) { |
| 95 | - let Some(path) = config_file("accounts") else { | ||
| 96 | - return; | ||
| 97 | - }; | ||
| 98 | let mut content: String = accounts | 91 | let mut content: String = accounts |
| 99 | .list | 92 | .list |
| 100 | .iter() | 93 | .iter() |
| @@ -109,18 +102,5 @@ fn save(accounts: &Accounts) { | |||
| 109 | content.push_str(&format!("active\t{active}\n")); | 102 | content.push_str(&format!("active\t{active}\n")); |
| 110 | } | 103 | } |
| 111 | 104 | ||
| 112 | - if let Err(error) = write_private(&path, &content) { | 105 | + write_config("accounts", &content); |
| 113 | - warn!("save accounts failed: {error}"); | ||
| 114 | - } | ||
| 115 | -} | ||
| 116 | - | ||
| 117 | -fn write_private(path: &PathBuf, content: &str) -> std::io::Result<()> { | ||
| 118 | - if let Some(parent) = path.parent() { | ||
| 119 | - fs::create_dir_all(parent)?; | ||
| 120 | - } | ||
| 121 | - let mut options = fs::OpenOptions::new(); | ||
| 122 | - options.write(true).create(true).truncate(true); | ||
| 123 | - #[cfg(unix)] | ||
| 124 | - std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); | ||
| 125 | - std::io::Write::write_all(&mut options.open(path)?, content.as_bytes()) | ||
| 126 | } | 106 | } |
crates/client/src/gui.rsmodified+2 -0
| @@ -61,6 +61,7 @@ mod voice_note; | |||
| 61 | mod voice_settings; | 61 | mod voice_settings; |
| 62 | mod voice_stats; | 62 | mod voice_stats; |
| 63 | mod wave; | 63 | mod wave; |
| 64 | +mod widget; | ||
| 64 | 65 | ||
| 65 | use auth::Auth; | 66 | use auth::Auth; |
| 66 | use chat::{Chat, View}; | 67 | use chat::{Chat, View}; |
| @@ -1076,6 +1077,7 @@ impl Yumush { | |||
| 1076 | fn end_session(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 1077 | fn end_session(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 1077 | self.end_voice(cx); | 1078 | self.end_voice(cx); |
| 1078 | self.leave_settings(); | 1079 | self.leave_settings(); |
| 1080 | + self.stop_playing(cx); | ||
| 1079 | self.user = None; | 1081 | self.user = None; |
| 1080 | self.chat.reset(); | 1082 | self.chat.reset(); |
| 1081 | self.change_page(Route::Login, window, cx); | 1083 | self.change_page(Route::Login, window, cx); |
crates/client/src/gui/auth.rsmodified+13 -36
| @@ -1,19 +1,20 @@ | |||
| 1 | -use super::{ | ||
| 2 | - Tooltip as _, | ||
| 3 | - settings_page::{segment, segment_track}, | ||
| 4 | - text, | ||
| 5 | -}; | ||
| 6 | use gpui_kit::{ | 1 | use gpui_kit::{ |
| 7 | - Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, | 2 | + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, |
| 8 | - component::input::{Input, InputEvent, InputState}, | 3 | + StatefulInteractiveElement, Styled, Window, |
| 4 | + assets::IconName, | ||
| 5 | + component::{ | ||
| 6 | + Icon, | ||
| 7 | + input::{Input, InputEvent, InputState}, | ||
| 8 | + }, | ||
| 9 | div, px, | 9 | div, px, |
| 10 | }; | 10 | }; |
| 11 | 11 | ||
| 12 | -use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon}; | 12 | +use super::{ |
| 13 | - | 13 | + Palette, Route, Tooltip as _, Yumush, badge, clickable, connection_notice, hoverable, |
| 14 | -use crate::gui::{ | 14 | + new_input, notify_error, palette, primary_button, |
| 15 | - Palette, Route, Yumush, badge, clickable, connection_notice, hoverable, new_input, | 15 | + settings_page::{segment, segment_track}, |
| 16 | - notify_error, palette, primary_button, | 16 | + text, |
| 17 | + widget::{field, frame}, | ||
| 17 | }; | 18 | }; |
| 18 | 19 | ||
| 19 | pub struct Auth { | 20 | pub struct Auth { |
| @@ -87,32 +88,10 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) { | |||
| 87 | .detach(); | 88 | .detach(); |
| 88 | } | 89 | } |
| 89 | 90 | ||
| 90 | -pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div { | ||
| 91 | - frame(palette, Input::new(input)) | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | fn password_field(palette: Palette, input: &Entity<InputState>) -> Div { | 91 | fn password_field(palette: Palette, input: &Entity<InputState>) -> Div { |
| 95 | frame(palette, Input::new(input).mask_toggle()) | 92 | frame(palette, Input::new(input).mask_toggle()) |
| 96 | } | 93 | } |
| 97 | 94 | ||
| 98 | -fn frame(palette: Palette, input: Input) -> Div { | ||
| 99 | - div() | ||
| 100 | - .h(px(32.)) | ||
| 101 | - .flex() | ||
| 102 | - .items_center() | ||
| 103 | - .rounded(px(8.)) | ||
| 104 | - .border_1() | ||
| 105 | - .border_color(palette.border) | ||
| 106 | - .bg(palette.field) | ||
| 107 | - .child( | ||
| 108 | - input | ||
| 109 | - .appearance(false) | ||
| 110 | - .text_color(palette.text) | ||
| 111 | - .flex_1() | ||
| 112 | - .min_w_0(), | ||
| 113 | - ) | ||
| 114 | -} | ||
| 115 | - | ||
| 116 | impl Yumush { | 95 | impl Yumush { |
| 117 | pub(super) fn auth_page(&self, route: Route, cx: &mut Context<Self>) -> impl IntoElement { | 96 | pub(super) fn auth_page(&self, route: Route, cx: &mut Context<Self>) -> impl IntoElement { |
| 118 | let palette = palette(cx); | 97 | let palette = palette(cx); |
| @@ -183,9 +162,7 @@ impl Yumush { | |||
| 183 | .children(connection_notice(&self.connection, palette)), | 162 | .children(connection_notice(&self.connection, palette)), |
| 184 | ) | 163 | ) |
| 185 | } | 164 | } |
| 186 | -} | ||
| 187 | 165 | ||
| 188 | -impl Yumush { | ||
| 189 | fn saved_accounts(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> { | 166 | fn saved_accounts(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> { |
| 190 | if self.accounts.list.is_empty() { | 167 | if self.accounts.list.is_empty() { |
| 191 | return None; | 168 | return None; |
crates/client/src/gui/builder.rsmodified+35 -4
| @@ -11,7 +11,7 @@ mod ui; | |||
| 11 | mod users; | 11 | mod users; |
| 12 | mod voice; | 12 | mod voice; |
| 13 | 13 | ||
| 14 | -use std::{fmt::Display, future::Future}; | 14 | +use std::{fmt::Display, future::Future, path::PathBuf}; |
| 15 | 15 | ||
| 16 | use common::{ | 16 | use common::{ |
| 17 | model::{CommunityKind, Member, Role}, | 17 | model::{CommunityKind, Member, Role}, |
| @@ -21,7 +21,7 @@ use gpui_kit::{ | |||
| 21 | AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, | 21 | AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, |
| 22 | StatefulInteractiveElement, Styled, Window, | 22 | StatefulInteractiveElement, Styled, Window, |
| 23 | assets::IconName, | 23 | assets::IconName, |
| 24 | - component::{Icon, switch::Switch}, | 24 | + component::{Icon, input::InputState, switch::Switch}, |
| 25 | div, | 25 | div, |
| 26 | prelude::FluentBuilder as _, | 26 | prelude::FluentBuilder as _, |
| 27 | px, | 27 | px, |
| @@ -30,10 +30,14 @@ use gpui_kit::{ | |||
| 30 | use self::ui::{accent_button, icon_button, page_heading, plain_button}; | 30 | use self::ui::{accent_button, icon_button, page_heading, plain_button}; |
| 31 | use super::{ | 31 | use super::{ |
| 32 | Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, | 32 | Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, |
| 33 | - text, | 33 | + text, widget::search_text, |
| 34 | }; | 34 | }; |
| 35 | use crate::network::NetworkHandle; | 35 | use crate::network::NetworkHandle; |
| 36 | 36 | ||
| 37 | +pub(super) fn save_directory() -> PathBuf { | ||
| 38 | + dirs::download_dir().unwrap_or_else(std::env::temp_dir) | ||
| 39 | +} | ||
| 40 | + | ||
| 37 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 38 | pub(super) enum BuilderTab { | 42 | pub(super) enum BuilderTab { |
| 39 | Overview, | 43 | Overview, |
| @@ -304,7 +308,10 @@ impl Yumush { | |||
| 304 | BuilderTab::Overview => self.load_overview(window, cx), | 308 | BuilderTab::Overview => self.load_overview(window, cx), |
| 305 | BuilderTab::Users => self.load_users(window, cx), | 309 | BuilderTab::Users => self.load_users(window, cx), |
| 306 | BuilderTab::Communities => self.load_builder_communities(window, cx), | 310 | BuilderTab::Communities => self.load_builder_communities(window, cx), |
| 307 | - BuilderTab::Messages => {} | 311 | + BuilderTab::Messages => { |
| 312 | + self.load_users(window, cx); | ||
| 313 | + self.load_builder_communities(window, cx); | ||
| 314 | + } | ||
| 308 | BuilderTab::Storage => { | 315 | BuilderTab::Storage => { |
| 309 | self.load_users(window, cx); | 316 | self.load_users(window, cx); |
| 310 | self.load_builder_communities(window, cx); | 317 | self.load_builder_communities(window, cx); |
| @@ -416,6 +423,30 @@ impl Yumush { | |||
| 416 | .map(|summary| summary.community.id.clone()) | 423 | .map(|summary| summary.community.id.clone()) |
| 417 | } | 424 | } |
| 418 | 425 | ||
| 426 | + pub(super) fn filter_user( | ||
| 427 | + &self, | ||
| 428 | + input: &Entity<InputState>, | ||
| 429 | + cx: &App, | ||
| 430 | + ) -> Option<Option<String>> { | ||
| 431 | + let name = search_text(input, cx); | ||
| 432 | + if name.is_empty() { | ||
| 433 | + return Some(None); | ||
| 434 | + } | ||
| 435 | + self.resolve_user(&name).map(Some) | ||
| 436 | + } | ||
| 437 | + | ||
| 438 | + pub(super) fn filter_community( | ||
| 439 | + &self, | ||
| 440 | + input: &Entity<InputState>, | ||
| 441 | + cx: &App, | ||
| 442 | + ) -> Option<Option<String>> { | ||
| 443 | + let name = search_text(input, cx); | ||
| 444 | + if name.is_empty() { | ||
| 445 | + return Some(None); | ||
| 446 | + } | ||
| 447 | + self.resolve_community(&name).map(Some) | ||
| 448 | + } | ||
| 449 | + | ||
| 419 | fn set_ghost_state(&mut self, ghost: bool) { | 450 | fn set_ghost_state(&mut self, ghost: bool) { |
| 420 | self.chat.ghost = ghost; | 451 | self.chat.ghost = ghost; |
| 421 | let Some(me) = self.user.as_ref() else { | 452 | let Some(me) = self.user.as_ref() else { |
crates/client/src/gui/builder/access.rsmodified+10 -22
| @@ -4,9 +4,12 @@ use gpui_kit::{ | |||
| 4 | Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px, | 4 | Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px, |
| 5 | }; | 5 | }; |
| 6 | 6 | ||
| 7 | -use super::ui::{accent_button, card, card_header, icon_button, pill, toolbar}; | 7 | +use super::ui::{ |
| 8 | + accent_button, card, card_header, confirmed, delete_icon_button, fixed, icon_button, pill, | ||
| 9 | + toolbar, | ||
| 10 | +}; | ||
| 8 | use crate::gui::STAMP; | 11 | use crate::gui::STAMP; |
| 9 | -use crate::gui::{Palette, Yumush, auth::field, entity_action, millis_time, notify_error, text}; | 12 | +use crate::gui::{Palette, Yumush, entity_action, millis_time, notify_error, text, widget::field}; |
| 10 | 13 | ||
| 11 | fn list_card(header: Div, rows: Vec<Div>, empty: &str, palette: Palette) -> Div { | 14 | fn list_card(header: Div, rows: Vec<Div>, empty: &str, palette: Palette) -> Div { |
| 12 | let body = if rows.is_empty() { | 15 | let body = if rows.is_empty() { |
| @@ -43,11 +46,6 @@ fn invite_row( | |||
| 43 | || "never".to_string(), | 46 | || "never".to_string(), |
| 44 | |at| format!("expires {}", millis_time(at, STAMP)), | 47 | |at| format!("expires {}", millis_time(at, STAMP)), |
| 45 | ); | 48 | ); |
| 46 | - let (delete_icon, delete_tip, delete_color) = if pending { | ||
| 47 | - (IconName::Check, "Confirm", palette.on_accent) | ||
| 48 | - } else { | ||
| 49 | - (IconName::Trash, "Delete", palette.danger) | ||
| 50 | - }; | ||
| 51 | 49 | ||
| 52 | div() | 50 | div() |
| 53 | .min_h(px(44.)) | 51 | .min_h(px(44.)) |
| @@ -90,11 +88,9 @@ fn invite_row( | |||
| 90 | yumush.copy_invite(©_code, cx) | 88 | yumush.copy_invite(©_code, cx) |
| 91 | }), | 89 | }), |
| 92 | )) | 90 | )) |
| 93 | - .child(icon_button( | 91 | + .child(delete_icon_button( |
| 94 | format!("delete_invite_{}", invite.code), | 92 | format!("delete_invite_{}", invite.code), |
| 95 | - delete_icon, | 93 | + pending, |
| 96 | - delete_tip, | ||
| 97 | - delete_color, | ||
| 98 | palette, | 94 | palette, |
| 99 | entity_action(entity, move |yumush, window, cx| { | 95 | entity_action(entity, move |yumush, window, cx| { |
| 100 | yumush.delete_invite(&delete_code, window, cx) | 96 | yumush.delete_invite(&delete_code, window, cx) |
| @@ -212,12 +208,10 @@ impl Yumush { | |||
| 212 | window: &mut Window, | 208 | window: &mut Window, |
| 213 | cx: &mut Context<Self>, | 209 | cx: &mut Context<Self>, |
| 214 | ) { | 210 | ) { |
| 215 | - if self.chat.pending_invite_delete.as_deref() != Some(code) { | 211 | + if !confirmed(&mut self.chat.pending_invite_delete, code) { |
| 216 | - self.chat.pending_invite_delete = Some(code.to_string()); | ||
| 217 | cx.notify(); | 212 | cx.notify(); |
| 218 | return; | 213 | return; |
| 219 | } | 214 | } |
| 220 | - self.chat.pending_invite_delete = None; | ||
| 221 | let network = self.network.clone(); | 215 | let network = self.network.clone(); |
| 222 | let code = code.to_string(); | 216 | let code = code.to_string(); |
| 223 | 217 | ||
| @@ -255,14 +249,8 @@ impl Yumush { | |||
| 255 | 249 | ||
| 256 | pub(super) fn access_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { | 250 | pub(super) fn access_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { |
| 257 | let controls = toolbar(vec![ | 251 | let controls = toolbar(vec![ |
| 258 | - div() | 252 | + fixed(80., field(palette, &self.chat.invite_uses)), |
| 259 | - .w(px(80.)) | 253 | + fixed(90., field(palette, &self.chat.invite_hours)), |
| 260 | - .child(field(palette, &self.chat.invite_uses)) | ||
| 261 | - .into_any_element(), | ||
| 262 | - div() | ||
| 263 | - .w(px(90.)) | ||
| 264 | - .child(field(palette, &self.chat.invite_hours)) | ||
| 265 | - .into_any_element(), | ||
| 266 | accent_button( | 254 | accent_button( |
| 267 | "create_invite", | 255 | "create_invite", |
| 268 | "Create", | 256 | "Create", |
crates/client/src/gui/builder/backups.rsmodified+13 -8
| @@ -4,7 +4,10 @@ use gpui_kit::{ | |||
| 4 | component::Icon, div, prelude::FluentBuilder as _, px, | 4 | component::Icon, div, prelude::FluentBuilder as _, px, |
| 5 | }; | 5 | }; |
| 6 | 6 | ||
| 7 | -use super::ui::{accent_button, card, card_header, delete_icon_button, icon_button, list_row}; | 7 | +use super::{ |
| 8 | + save_directory, | ||
| 9 | + ui::{accent_button, card, card_header, confirmed, delete_icon_button, icon_button, list_row}, | ||
| 10 | +}; | ||
| 8 | use crate::gui::{DATE, Palette, Yumush, entity_action, millis_time, notify_error, storage, text}; | 11 | use crate::gui::{DATE, Palette, Yumush, entity_action, millis_time, notify_error, storage, text}; |
| 9 | 12 | ||
| 10 | fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity<Yumush>, palette: Palette) -> Div { | 13 | fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity<Yumush>, palette: Palette) -> Div { |
| @@ -139,12 +142,10 @@ impl Yumush { | |||
| 139 | } | 142 | } |
| 140 | 143 | ||
| 141 | fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) { | 144 | fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 142 | - if self.pending_backup_delete.as_deref() != Some(name) { | 145 | + if !confirmed(&mut self.pending_backup_delete, name) { |
| 143 | - self.pending_backup_delete = Some(name.to_string()); | ||
| 144 | cx.notify(); | 146 | cx.notify(); |
| 145 | return; | 147 | return; |
| 146 | } | 148 | } |
| 147 | - self.pending_backup_delete = None; | ||
| 148 | let network = self.network.clone(); | 149 | let network = self.network.clone(); |
| 149 | let name = name.to_string(); | 150 | let name = name.to_string(); |
| 150 | 151 | ||
| @@ -161,14 +162,18 @@ impl Yumush { | |||
| 161 | } | 162 | } |
| 162 | 163 | ||
| 163 | fn export_backup(&self, name: &str, window: &mut Window, cx: &mut Context<Self>) { | 164 | fn export_backup(&self, name: &str, window: &mut Window, cx: &mut Context<Self>) { |
| 164 | - let directory = dirs::download_dir().unwrap_or_else(std::env::temp_dir); | 165 | + let target = cx.prompt_for_new_path(&save_directory(), Some(name)); |
| 165 | - let target = cx.prompt_for_new_path(&directory, Some(name)); | ||
| 166 | let network = self.network.clone(); | 166 | let network = self.network.clone(); |
| 167 | let name = name.to_string(); | 167 | let name = name.to_string(); |
| 168 | 168 | ||
| 169 | cx.spawn_in(window, async move |this, cx| { | 169 | cx.spawn_in(window, async move |this, cx| { |
| 170 | - let Ok(Ok(Some(target))) = target.await else { | 170 | + let target = match target.await { |
| 171 | - return; | 171 | + Ok(Ok(Some(target))) => target, |
| 172 | + Ok(Err(error)) => { | ||
| 173 | + notify_error(&this, cx, error); | ||
| 174 | + return; | ||
| 175 | + } | ||
| 176 | + _ => return, | ||
| 172 | }; | 177 | }; |
| 173 | if let Err(error) = network.download_backup(&name, target).await { | 178 | if let Err(error) = network.download_backup(&name, target).await { |
| 174 | notify_error(&this, cx, error); | 179 | notify_error(&this, cx, error); |
crates/client/src/gui/builder/communities.rsmodified+5 -8
| @@ -6,11 +6,11 @@ use gpui_kit::{ | |||
| 6 | 6 | ||
| 7 | use super::{ | 7 | use super::{ |
| 8 | Transfer, | 8 | Transfer, |
| 9 | - ui::{card, icon_button, pill, plain_button, rows_body}, | 9 | + ui::{card, confirmed, icon_button, pill, plain_button, rows_body}, |
| 10 | }; | 10 | }; |
| 11 | use crate::gui::{ | 11 | use crate::gui::{ |
| 12 | - Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text, | 12 | + Palette, Yumush, avatar, chat::View, community_icon, entity_action, notify_error, |
| 13 | - entity_action, notify_error, profile::user_link, text, | 13 | + profile::user_link, text, widget::search_text, |
| 14 | }; | 14 | }; |
| 15 | 15 | ||
| 16 | impl Yumush { | 16 | impl Yumush { |
| @@ -63,12 +63,10 @@ impl Yumush { | |||
| 63 | window: &mut Window, | 63 | window: &mut Window, |
| 64 | cx: &mut Context<Self>, | 64 | cx: &mut Context<Self>, |
| 65 | ) { | 65 | ) { |
| 66 | - if self.chat.pending_community_delete.as_deref() != Some(community_id) { | 66 | + if !confirmed(&mut self.chat.pending_community_delete, community_id) { |
| 67 | - self.chat.pending_community_delete = Some(community_id.to_string()); | ||
| 68 | cx.notify(); | 67 | cx.notify(); |
| 69 | return; | 68 | return; |
| 70 | } | 69 | } |
| 71 | - self.chat.pending_community_delete = None; | ||
| 72 | let network = self.network.clone(); | 70 | let network = self.network.clone(); |
| 73 | let community_id = community_id.to_string(); | 71 | let community_id = community_id.to_string(); |
| 74 | 72 | ||
| @@ -171,8 +169,7 @@ impl Yumush { | |||
| 171 | let Some(transfer) = self.chat.transfer.as_mut() else { | 169 | let Some(transfer) = self.chat.transfer.as_mut() else { |
| 172 | return; | 170 | return; |
| 173 | }; | 171 | }; |
| 174 | - if transfer.pending.as_deref() != Some(user_id) { | 172 | + if !confirmed(&mut transfer.pending, user_id) { |
| 175 | - transfer.pending = Some(user_id.to_string()); | ||
| 176 | window.refresh(); | 173 | window.refresh(); |
| 177 | cx.notify(); | 174 | cx.notify(); |
| 178 | return; | 175 | return; |
crates/client/src/gui/builder/log.rsmodified+27 -35
| @@ -3,22 +3,25 @@ use common::{ | |||
| 3 | time::{created_at_ms, now_ms}, | 3 | time::{created_at_ms, now_ms}, |
| 4 | }; | 4 | }; |
| 5 | use gpui_kit::{ | 5 | use gpui_kit::{ |
| 6 | - AnyElement, App, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, | 6 | + AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, |
| 7 | assets::IconName, | 7 | assets::IconName, |
| 8 | - component::{Icon, WindowExt, input::InputState, notification::Notification, select::Select}, | 8 | + component::{Icon, WindowExt, notification::Notification, select::Select}, |
| 9 | div, | 9 | div, |
| 10 | prelude::FluentBuilder as _, | 10 | prelude::FluentBuilder as _, |
| 11 | px, | 11 | px, |
| 12 | }; | 12 | }; |
| 13 | use jiff::Timestamp; | 13 | use jiff::Timestamp; |
| 14 | 14 | ||
| 15 | -use super::ui::{accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar}; | 15 | +use super::{ |
| 16 | + save_directory, | ||
| 17 | + ui::{accent_button, card, end_of_day_ms, fixed, list_row, pill, start_of_day_ms, toolbar}, | ||
| 18 | +}; | ||
| 16 | use crate::gui::STAMP; | 19 | use crate::gui::STAMP; |
| 17 | use crate::gui::{ | 20 | use crate::gui::{ |
| 18 | Palette, Yumush, | 21 | Palette, Yumush, |
| 19 | - auth::field, | 22 | + community_settings::user_name, |
| 20 | - community_settings::{search_text, user_name}, | 23 | + entity_action, id_time, millis_time, notify_error, text, |
| 21 | - entity_action, id_time, millis_time, text, | 24 | + widget::{field, search_text}, |
| 22 | }; | 25 | }; |
| 23 | 26 | ||
| 24 | fn builder_log_text(entry: &AdminLogEntry) -> String { | 27 | fn builder_log_text(entry: &AdminLogEntry) -> String { |
| @@ -155,14 +158,6 @@ fn action_icon(action: &AdminAction) -> IconName { | |||
| 155 | } | 158 | } |
| 156 | } | 159 | } |
| 157 | 160 | ||
| 158 | -fn fixed(width: f32, control: impl IntoElement) -> AnyElement { | ||
| 159 | - div() | ||
| 160 | - .w(px(width)) | ||
| 161 | - .flex_shrink_0() | ||
| 162 | - .child(control) | ||
| 163 | - .into_any_element() | ||
| 164 | -} | ||
| 165 | - | ||
| 166 | fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { | 161 | fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { |
| 167 | list_row() | 162 | list_row() |
| 168 | .child( | 163 | .child( |
| @@ -206,8 +201,8 @@ impl Yumush { | |||
| 206 | return; | 201 | return; |
| 207 | } | 202 | } |
| 208 | let (Some(actor_id), Some(target_id)) = ( | 203 | let (Some(actor_id), Some(target_id)) = ( |
| 209 | - self.log_user(&self.chat.builder_log_actor, cx), | 204 | + self.filter_user(&self.chat.builder_log_actor, cx), |
| 210 | - self.log_user(&self.chat.builder_log_target, cx), | 205 | + self.filter_user(&self.chat.builder_log_target, cx), |
| 211 | ) else { | 206 | ) else { |
| 212 | window.push_notification(Notification::error("Unknown user"), cx); | 207 | window.push_notification(Notification::error("Unknown user"), cx); |
| 213 | return; | 208 | return; |
| @@ -237,31 +232,28 @@ impl Yumush { | |||
| 237 | ); | 232 | ); |
| 238 | } | 233 | } |
| 239 | 234 | ||
| 240 | - pub(super) fn log_user(&self, input: &Entity<InputState>, cx: &App) -> Option<Option<String>> { | ||
| 241 | - let name = search_text(input, cx); | ||
| 242 | - if name.is_empty() { | ||
| 243 | - return Some(None); | ||
| 244 | - } | ||
| 245 | - | ||
| 246 | - self.resolve_user(&name).map(Some) | ||
| 247 | - } | ||
| 248 | - | ||
| 249 | pub(super) fn export_builder_log(&self, window: &mut Window, cx: &mut Context<Self>) { | 235 | pub(super) fn export_builder_log(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 250 | - let Some(directory) = dirs::download_dir() else { | ||
| 251 | - window.push_notification(Notification::error("No download folder"), cx); | ||
| 252 | - return; | ||
| 253 | - }; | ||
| 254 | let name = format!( | 236 | let name = format!( |
| 255 | "yumush-admin-log-{}.csv", | 237 | "yumush-admin-log-{}.csv", |
| 256 | millis_time(now_ms(), "%Y%m%d-%H%M%S") | 238 | millis_time(now_ms(), "%Y%m%d-%H%M%S") |
| 257 | ); | 239 | ); |
| 258 | - let path = directory.join(name); | 240 | + let target = cx.prompt_for_new_path(&save_directory(), Some(&name)); |
| 259 | - match std::fs::write(&path, builder_log_csv(&self.chat.builder_logs)) { | 241 | + let csv = builder_log_csv(&self.chat.builder_logs); |
| 260 | - Ok(()) => { | 242 | + |
| 261 | - window.push_notification(Notification::success(path.display().to_string()), cx) | 243 | + cx.spawn_in(window, async move |this, cx| { |
| 244 | + let target = match target.await { | ||
| 245 | + Ok(Ok(Some(target))) => target, | ||
| 246 | + Ok(Err(error)) => { | ||
| 247 | + notify_error(&this, cx, error); | ||
| 248 | + return; | ||
| 249 | + } | ||
| 250 | + _ => return, | ||
| 251 | + }; | ||
| 252 | + if let Err(error) = std::fs::write(target, csv) { | ||
| 253 | + notify_error(&this, cx, error); | ||
| 262 | } | 254 | } |
| 263 | - Err(error) => window.push_notification(Notification::error(error.to_string()), cx), | 255 | + }) |
| 264 | - } | 256 | + .detach(); |
| 265 | } | 257 | } |
| 266 | 258 | ||
| 267 | pub(super) fn log_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { | 259 | pub(super) fn log_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { |
crates/client/src/gui/builder/messages.rsmodified+20 -14
| @@ -1,22 +1,25 @@ | |||
| 1 | use common::model::MessageHit; | 1 | use common::model::MessageHit; |
| 2 | use gpui_kit::{ | 2 | use gpui_kit::{ |
| 3 | AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, | 3 | AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, |
| 4 | - assets::IconName, div, prelude::FluentBuilder as _, px, | 4 | + assets::IconName, |
| 5 | + component::{WindowExt, notification::Notification}, | ||
| 6 | + div, | ||
| 7 | + prelude::FluentBuilder as _, | ||
| 8 | + px, | ||
| 5 | }; | 9 | }; |
| 6 | 10 | ||
| 7 | use super::ui::{ | 11 | use super::ui::{ |
| 8 | - accent_button, card, delete_icon_button, end_of_day_ms, icon_button, list_card, list_row, | 12 | + accent_button, card, confirmed, delete_icon_button, end_of_day_ms, icon_button, list_card, |
| 9 | - start_of_day_ms, | 13 | + list_row, start_of_day_ms, |
| 10 | }; | 14 | }; |
| 11 | use crate::gui::YEAR_STAMP; | 15 | use crate::gui::YEAR_STAMP; |
| 12 | use crate::gui::{ | 16 | use crate::gui::{ |
| 13 | - Palette, Yumush, | 17 | + Palette, Yumush, avatar, |
| 14 | - auth::field, | 18 | + community_settings::user_name, |
| 15 | - avatar, | ||
| 16 | - community_settings::{search_text, user_name}, | ||
| 17 | entity_action, id_time, notify_error, | 19 | entity_action, id_time, notify_error, |
| 18 | profile::user_link, | 20 | profile::user_link, |
| 19 | text, | 21 | text, |
| 22 | + widget::{field, search_text}, | ||
| 20 | }; | 23 | }; |
| 21 | 24 | ||
| 22 | fn message_hit_row( | 25 | fn message_hit_row( |
| @@ -205,10 +208,15 @@ impl Yumush { | |||
| 205 | 208 | ||
| 206 | pub(super) fn search_messages(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 209 | pub(super) fn search_messages(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 207 | let text = search_text(&self.chat.builder_message_text, cx); | 210 | let text = search_text(&self.chat.builder_message_text, cx); |
| 208 | - let username = search_text(&self.chat.builder_message_user, cx); | 211 | + let Some(user_id) = self.filter_user(&self.chat.builder_message_user, cx) else { |
| 209 | - let community = search_text(&self.chat.builder_message_community, cx); | 212 | + window.push_notification(Notification::error("Unknown user"), cx); |
| 210 | - let user_id = self.resolve_user(&username); | 213 | + return; |
| 211 | - let community_id = self.resolve_community(&community); | 214 | + }; |
| 215 | + let Some(community_id) = self.filter_community(&self.chat.builder_message_community, cx) | ||
| 216 | + else { | ||
| 217 | + window.push_notification(Notification::error("Unknown community"), cx); | ||
| 218 | + return; | ||
| 219 | + }; | ||
| 212 | let after_ms = start_of_day_ms(&search_text(&self.chat.builder_message_from, cx)); | 220 | let after_ms = start_of_day_ms(&search_text(&self.chat.builder_message_from, cx)); |
| 213 | let before_ms = end_of_day_ms(&search_text(&self.chat.builder_message_to, cx)); | 221 | let before_ms = end_of_day_ms(&search_text(&self.chat.builder_message_to, cx)); |
| 214 | let text = (!text.is_empty()).then_some(text); | 222 | let text = (!text.is_empty()).then_some(text); |
| @@ -240,12 +248,10 @@ impl Yumush { | |||
| 240 | window: &mut Window, | 248 | window: &mut Window, |
| 241 | cx: &mut Context<Self>, | 249 | cx: &mut Context<Self>, |
| 242 | ) { | 250 | ) { |
| 243 | - if self.chat.pending_message_delete.as_deref() != Some(message_id) { | 251 | + if !confirmed(&mut self.chat.pending_message_delete, message_id) { |
| 244 | - self.chat.pending_message_delete = Some(message_id.to_string()); | ||
| 245 | cx.notify(); | 252 | cx.notify(); |
| 246 | return; | 253 | return; |
| 247 | } | 254 | } |
| 248 | - self.chat.pending_message_delete = None; | ||
| 249 | let network = self.network.clone(); | 255 | let network = self.network.clone(); |
| 250 | let message_id = message_id.to_string(); | 256 | let message_id = message_id.to_string(); |
| 251 | 257 | ||
crates/client/src/gui/builder/reports.rsmodified+23 -32
| @@ -23,21 +23,13 @@ use crate::{ | |||
| 23 | network::NetworkHandle, | 23 | network::NetworkHandle, |
| 24 | }; | 24 | }; |
| 25 | 25 | ||
| 26 | -const REPORT_FILTERS: [(Option<ReportStatus>, &str); 4] = [ | 26 | +const REPORT_FILTERS: [Option<ReportStatus>; 4] = [ |
| 27 | - (Some(ReportStatus::Open), "Open"), | 27 | + Some(ReportStatus::Open), |
| 28 | - (Some(ReportStatus::Resolved), "Resolved"), | 28 | + Some(ReportStatus::Resolved), |
| 29 | - (Some(ReportStatus::Dismissed), "Dismissed"), | 29 | + Some(ReportStatus::Dismissed), |
| 30 | - (None, "All"), | 30 | + None, |
| 31 | ]; | 31 | ]; |
| 32 | 32 | ||
| 33 | -fn status_label(status: ReportStatus) -> &'static str { | ||
| 34 | - match status { | ||
| 35 | - ReportStatus::Open => "Open", | ||
| 36 | - ReportStatus::Resolved => "Resolved", | ||
| 37 | - ReportStatus::Dismissed => "Dismissed", | ||
| 38 | - } | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | fn status_color(status: ReportStatus, palette: Palette) -> Hsla { | 33 | fn status_color(status: ReportStatus, palette: Palette) -> Hsla { |
| 42 | match status { | 34 | match status { |
| 43 | ReportStatus::Open => palette.accent, | 35 | ReportStatus::Open => palette.accent, |
| @@ -166,25 +158,24 @@ impl Yumush { | |||
| 166 | } | 158 | } |
| 167 | 159 | ||
| 168 | pub(super) fn report_filters(&self, entity: &Entity<Self>, palette: Palette) -> Div { | 160 | pub(super) fn report_filters(&self, entity: &Entity<Self>, palette: Palette) -> Div { |
| 169 | - div() | 161 | + div().flex().child( |
| 170 | - .flex() | 162 | + segment_track(palette).children(REPORT_FILTERS.map(|status| { |
| 171 | - .child( | 163 | + let label = status.map_or("All", ReportStatus::label); |
| 172 | - segment_track(palette).children(REPORT_FILTERS.map(|(status, label)| { | 164 | + segment( |
| 173 | - segment( | 165 | + clickable( |
| 174 | - clickable( | 166 | + label, |
| 175 | - label, | ||
| 176 | - palette, | ||
| 177 | - entity_action(entity, move |yumush, window, cx| { | ||
| 178 | - yumush.select_report_filter(status, window, cx) | ||
| 179 | - }), | ||
| 180 | - ), | ||
| 181 | - self.chat.report_filter == status, | ||
| 182 | palette, | 167 | palette, |
| 183 | - ) | 168 | + entity_action(entity, move |yumush, window, cx| { |
| 184 | - .px(px(10.)) | 169 | + yumush.select_report_filter(status, window, cx) |
| 185 | - .child(label) | 170 | + }), |
| 186 | - })), | 171 | + ), |
| 187 | - ) | 172 | + self.chat.report_filter == status, |
| 173 | + palette, | ||
| 174 | + ) | ||
| 175 | + .px(px(10.)) | ||
| 176 | + .child(label) | ||
| 177 | + })), | ||
| 178 | + ) | ||
| 188 | } | 179 | } |
| 189 | 180 | ||
| 190 | pub(super) fn reports_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { | 181 | pub(super) fn reports_body(&self, entity: &Entity<Self>, palette: Palette) -> Vec<AnyElement> { |
| @@ -236,7 +227,7 @@ impl Yumush { | |||
| 236 | ), | 227 | ), |
| 237 | )) | 228 | )) |
| 238 | .child(pill( | 229 | .child(pill( |
| 239 | - status_label(report.status), | 230 | + report.status.label(), |
| 240 | status_color(report.status, palette), | 231 | status_color(report.status, palette), |
| 241 | palette, | 232 | palette, |
| 242 | )) | 233 | )) |
crates/client/src/gui/builder/server.rsmodified+27 -18
| @@ -1,19 +1,24 @@ | |||
| 1 | use common::model::ServerSettings; | 1 | use common::model::ServerSettings; |
| 2 | use gpui_kit::{ | 2 | use gpui_kit::{ |
| 3 | - AnyElement, App, Context, Entity, IntoElement, Window, component::input::InputState, | 3 | + AnyElement, App, Context, Entity, IntoElement, Window, |
| 4 | + component::{WindowExt, input::InputState, notification::Notification}, | ||
| 4 | }; | 5 | }; |
| 5 | 6 | ||
| 6 | use super::ui::{field_row, list_card, number, to_bytes, to_units}; | 7 | use super::ui::{field_row, list_card, number, to_bytes, to_units}; |
| 7 | -use crate::gui::{KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented}; | 8 | +use crate::gui::{KB, MB, Palette, Yumush, notify_error, settings_page::segmented, widget::field}; |
| 8 | 9 | ||
| 9 | fn input_text(input: &Entity<InputState>, cx: &App) -> String { | 10 | fn input_text(input: &Entity<InputState>, cx: &App) -> String { |
| 10 | input.read(cx).text().to_string() | 11 | input.read(cx).text().to_string() |
| 11 | } | 12 | } |
| 12 | 13 | ||
| 13 | -fn input_number(input: &Entity<InputState>, cx: &App) -> u32 { | 14 | +fn input_number(input: &Entity<InputState>, cx: &App) -> Option<u32> { |
| 14 | number(&input_text(input, cx)) | 15 | number(&input_text(input, cx)) |
| 15 | } | 16 | } |
| 16 | 17 | ||
| 18 | +fn input_bytes(input: &Entity<InputState>, unit: u64, cx: &App) -> Option<u64> { | ||
| 19 | + to_bytes(&input_text(input, cx), unit) | ||
| 20 | +} | ||
| 21 | + | ||
| 17 | fn set_input(input: &Entity<InputState>, text: &str, window: &mut Window, cx: &mut App) { | 22 | fn set_input(input: &Entity<InputState>, text: &str, window: &mut Window, cx: &mut App) { |
| 18 | input.update(cx, |input, cx| input.set_value(text, window, cx)); | 23 | input.update(cx, |input, cx| input.set_value(text, window, cx)); |
| 19 | } | 24 | } |
| @@ -95,26 +100,30 @@ impl Yumush { | |||
| 95 | ); | 100 | ); |
| 96 | } | 101 | } |
| 97 | 102 | ||
| 98 | - pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 103 | + fn server_form(&self, cx: &App) -> Option<ServerSettings> { |
| 99 | let chat = &self.chat; | 104 | let chat = &self.chat; |
| 100 | - let settings = ServerSettings { | 105 | + Some(ServerSettings { |
| 101 | name: input_text(&chat.server_name, cx), | 106 | name: input_text(&chat.server_name, cx), |
| 102 | registration_open: chat.server_registration_open, | 107 | registration_open: chat.server_registration_open, |
| 103 | - max_attachment_bytes: to_bytes(&input_text(&chat.server_limit, cx), MB as u64), | 108 | + max_attachment_bytes: input_bytes(&chat.server_limit, MB as u64, cx)?, |
| 104 | maintenance: chat.server_maintenance, | 109 | maintenance: chat.server_maintenance, |
| 105 | - user_quota_bytes: to_bytes(&input_text(&chat.server_user_quota, cx), MB as u64), | 110 | + user_quota_bytes: input_bytes(&chat.server_user_quota, MB as u64, cx)?, |
| 106 | - community_quota_bytes: to_bytes( | 111 | + community_quota_bytes: input_bytes(&chat.server_community_quota, MB as u64, cx)?, |
| 107 | - &input_text(&chat.server_community_quota, cx), | 112 | + message_retention_days: input_number(&chat.server_message_retention, cx)?, |
| 108 | - MB as u64, | 113 | + attachment_retention_days: input_number(&chat.server_attachment_retention, cx)?, |
| 109 | - ), | ||
| 110 | - message_retention_days: input_number(&chat.server_message_retention, cx), | ||
| 111 | - attachment_retention_days: input_number(&chat.server_attachment_retention, cx), | ||
| 112 | announcement: input_text(&chat.server_announcement, cx), | 114 | announcement: input_text(&chat.server_announcement, cx), |
| 113 | - max_communities_per_user: input_number(&chat.server_max_communities, cx), | 115 | + max_communities_per_user: input_number(&chat.server_max_communities, cx)?, |
| 114 | - max_message_length: input_number(&chat.server_max_message_length, cx), | 116 | + max_message_length: input_number(&chat.server_max_message_length, cx)?, |
| 115 | - max_avatar_bytes: to_bytes(&input_text(&chat.server_max_avatar, cx), KB as u64), | 117 | + max_avatar_bytes: input_bytes(&chat.server_max_avatar, KB as u64, cx)?, |
| 116 | - messages_per_minute: input_number(&chat.server_messages_per_minute, cx), | 118 | + messages_per_minute: input_number(&chat.server_messages_per_minute, cx)?, |
| 117 | - logins_per_minute: input_number(&chat.server_logins_per_minute, cx), | 119 | + logins_per_minute: input_number(&chat.server_logins_per_minute, cx)?, |
| 120 | + }) | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 124 | + let Some(settings) = self.server_form(cx) else { | ||
| 125 | + window.push_notification(Notification::error("Invalid number"), cx); | ||
| 126 | + return; | ||
| 118 | }; | 127 | }; |
| 119 | let network = self.network.clone(); | 128 | let network = self.network.clone(); |
| 120 | 129 | ||
crates/client/src/gui/builder/storage.rsmodified+21 -20
| @@ -1,23 +1,22 @@ | |||
| 1 | use common::model::AttachmentInfo; | 1 | use common::model::AttachmentInfo; |
| 2 | use gpui_kit::{ | 2 | use gpui_kit::{ |
| 3 | AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, | 3 | AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, |
| 4 | - assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, | 4 | + assets::IconName, |
| 5 | + component::{Icon, WindowExt, notification::Notification}, | ||
| 6 | + div, | ||
| 7 | + prelude::FluentBuilder as _, | ||
| 8 | + px, relative, | ||
| 5 | }; | 9 | }; |
| 6 | 10 | ||
| 7 | use super::ui::{ | 11 | use super::ui::{ |
| 8 | - accent_button, card, card_header, delete_icon_button, list_card, list_row, toolbar, | 12 | + accent_button, card, card_header, confirmed, delete_icon_button, fixed, list_card, list_row, |
| 13 | + toolbar, | ||
| 9 | }; | 14 | }; |
| 10 | use crate::gui::{ | 15 | use crate::gui::{ |
| 11 | - DATE, Palette, Yumush, | 16 | + DATE, Palette, Yumush, community_settings::user_name, entity_action, id_time, notify_error, |
| 12 | - auth::field, | 17 | + storage, text, widget::field, |
| 13 | - community_settings::{search_text, user_name}, | ||
| 14 | - entity_action, id_time, notify_error, storage, text, | ||
| 15 | }; | 18 | }; |
| 16 | 19 | ||
| 17 | -fn fixed(width: f32, control: impl IntoElement) -> Div { | ||
| 18 | - div().w(px(width)).flex_shrink_0().child(control) | ||
| 19 | -} | ||
| 20 | - | ||
| 21 | fn share(bytes: u64, max: u64) -> f32 { | 20 | fn share(bytes: u64, max: u64) -> f32 { |
| 22 | if max == 0 { | 21 | if max == 0 { |
| 23 | 0. | 22 | 0. |
| @@ -197,12 +196,11 @@ impl Yumush { | |||
| 197 | )); | 196 | )); |
| 198 | 197 | ||
| 199 | let controls = toolbar(vec![ | 198 | let controls = toolbar(vec![ |
| 200 | - fixed(160., field(palette, &self.chat.builder_attachment_user)).into_any_element(), | 199 | + fixed(160., field(palette, &self.chat.builder_attachment_user)), |
| 201 | fixed( | 200 | fixed( |
| 202 | 160., | 201 | 160., |
| 203 | field(palette, &self.chat.builder_attachment_community), | 202 | field(palette, &self.chat.builder_attachment_community), |
| 204 | - ) | 203 | + ), |
| 205 | - .into_any_element(), | ||
| 206 | accent_button( | 204 | accent_button( |
| 207 | "search_attachments", | 205 | "search_attachments", |
| 208 | "Search", | 206 | "Search", |
| @@ -272,10 +270,15 @@ impl Yumush { | |||
| 272 | } | 270 | } |
| 273 | 271 | ||
| 274 | pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context<Self>) { | 272 | pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 275 | - let username = search_text(&self.chat.builder_attachment_user, cx); | 273 | + let Some(user_id) = self.filter_user(&self.chat.builder_attachment_user, cx) else { |
| 276 | - let community = search_text(&self.chat.builder_attachment_community, cx); | 274 | + window.push_notification(Notification::error("Unknown user"), cx); |
| 277 | - let user_id = self.resolve_user(&username); | 275 | + return; |
| 278 | - let community_id = self.resolve_community(&community); | 276 | + }; |
| 277 | + let Some(community_id) = self.filter_community(&self.chat.builder_attachment_community, cx) | ||
| 278 | + else { | ||
| 279 | + window.push_notification(Notification::error("Unknown community"), cx); | ||
| 280 | + return; | ||
| 281 | + }; | ||
| 279 | let network = self.network.clone(); | 282 | let network = self.network.clone(); |
| 280 | 283 | ||
| 281 | cx.spawn_in(window, async move |this, cx| { | 284 | cx.spawn_in(window, async move |this, cx| { |
| @@ -301,12 +304,10 @@ impl Yumush { | |||
| 301 | window: &mut Window, | 304 | window: &mut Window, |
| 302 | cx: &mut Context<Self>, | 305 | cx: &mut Context<Self>, |
| 303 | ) { | 306 | ) { |
| 304 | - if self.chat.pending_attachment_delete.as_deref() != Some(attachment_id) { | 307 | + if !confirmed(&mut self.chat.pending_attachment_delete, attachment_id) { |
| 305 | - self.chat.pending_attachment_delete = Some(attachment_id.to_string()); | ||
| 306 | cx.notify(); | 308 | cx.notify(); |
| 307 | return; | 309 | return; |
| 308 | } | 310 | } |
| 309 | - self.chat.pending_attachment_delete = None; | ||
| 310 | let network = self.network.clone(); | 311 | let network = self.network.clone(); |
| 311 | let attachment_id = attachment_id.to_string(); | 312 | let attachment_id = attachment_id.to_string(); |
| 312 | 313 | ||
crates/client/src/gui/builder/ui.rsmodified+24 -19
| @@ -1,24 +1,38 @@ | |||
| 1 | -use crate::gui::{Palette, Tooltip as _, clickable, primary_button, text}; | 1 | +use crate::gui::{Palette, Tooltip as _, clickable, primary_button, text, widget}; |
| 2 | use gpui_kit::{ | 2 | use gpui_kit::{ |
| 3 | AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window, | 3 | AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window, |
| 4 | assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, | 4 | assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, |
| 5 | }; | 5 | }; |
| 6 | use jiff::{civil::Date, tz::TimeZone}; | 6 | use jiff::{civil::Date, tz::TimeZone}; |
| 7 | 7 | ||
| 8 | -pub(super) fn to_bytes(text: &str, unit: u64) -> u64 { | 8 | +pub(super) fn to_bytes(text: &str, unit: u64) -> Option<u64> { |
| 9 | - text.trim() | 9 | + text.trim().parse::<u64>().ok()?.checked_mul(unit) |
| 10 | - .parse::<u64>() | ||
| 11 | - .ok() | ||
| 12 | - .and_then(|units| units.checked_mul(unit)) | ||
| 13 | - .unwrap_or(0) | ||
| 14 | } | 10 | } |
| 15 | 11 | ||
| 16 | pub(super) fn to_units(bytes: u64, unit: u64) -> String { | 12 | pub(super) fn to_units(bytes: u64, unit: u64) -> String { |
| 17 | (bytes / unit).to_string() | 13 | (bytes / unit).to_string() |
| 18 | } | 14 | } |
| 19 | 15 | ||
| 20 | -pub(super) fn number(text: &str) -> u32 { | 16 | +pub(super) fn confirmed(pending: &mut Option<String>, id: &str) -> bool { |
| 21 | - text.trim().parse().unwrap_or(0) | 17 | + if pending.as_deref() == Some(id) { |
| 18 | + *pending = None; | ||
| 19 | + true | ||
| 20 | + } else { | ||
| 21 | + *pending = Some(id.to_string()); | ||
| 22 | + false | ||
| 23 | + } | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +pub(super) fn fixed(width: f32, control: impl IntoElement) -> AnyElement { | ||
| 27 | + div() | ||
| 28 | + .w(px(width)) | ||
| 29 | + .flex_shrink_0() | ||
| 30 | + .child(control) | ||
| 31 | + .into_any_element() | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +pub(super) fn number(text: &str) -> Option<u32> { | ||
| 35 | + text.trim().parse().ok() | ||
| 22 | } | 36 | } |
| 23 | 37 | ||
| 24 | pub(super) fn icon_button( | 38 | pub(super) fn icon_button( |
| @@ -29,16 +43,7 @@ pub(super) fn icon_button( | |||
| 29 | palette: Palette, | 43 | palette: Palette, |
| 30 | action: impl Fn(&mut Window, &mut App) + 'static, | 44 | action: impl Fn(&mut Window, &mut App) + 'static, |
| 31 | ) -> Stateful<Div> { | 45 | ) -> Stateful<Div> { |
| 32 | - clickable(id, palette, action) | 46 | + widget::icon_button(id, palette, icon, tip, action).text_color(color) |
| 33 | - .tip(tip) | ||
| 34 | - .size(px(26.)) | ||
| 35 | - .flex_shrink_0() | ||
| 36 | - .flex() | ||
| 37 | - .items_center() | ||
| 38 | - .justify_center() | ||
| 39 | - .rounded(px(6.)) | ||
| 40 | - .text_color(color) | ||
| 41 | - .child(Icon::new(icon).w(px(14.)).h(px(14.))) | ||
| 42 | } | 47 | } |
| 43 | 48 | ||
| 44 | pub(super) fn delete_icon_button( | 49 | pub(super) fn delete_icon_button( |
crates/client/src/gui/builder/users.rsmodified+8 -10
| @@ -16,13 +16,15 @@ use gpui_kit::{ | |||
| 16 | }; | 16 | }; |
| 17 | 17 | ||
| 18 | use super::ui::{ | 18 | use super::ui::{ |
| 19 | - accent_button, action_button, action_group, card, confirm_button, pill, plain_button, | 19 | + accent_button, action_button, action_group, card, confirm_button, confirmed, pill, plain_button, |
| 20 | }; | 20 | }; |
| 21 | use crate::{ | 21 | use crate::{ |
| 22 | gui::{ | 22 | gui::{ |
| 23 | - DATE, DAY, Palette, Tooltip as _, Yumush, auth::field, avatar, clickable, | 23 | + DATE, DAY, Palette, Tooltip as _, Yumush, avatar, clickable, entity_action, id_time, |
| 24 | - community_settings::search_text, entity_action, id_time, millis_time, notify_error, | 24 | + millis_time, notify_error, |
| 25 | - profile::user_link, text, | 25 | + profile::user_link, |
| 26 | + text, | ||
| 27 | + widget::{field, search_text}, | ||
| 26 | }, | 28 | }, |
| 27 | network::NetworkHandle, | 29 | network::NetworkHandle, |
| 28 | }; | 30 | }; |
| @@ -111,12 +113,10 @@ impl Yumush { | |||
| 111 | window: &mut Window, | 113 | window: &mut Window, |
| 112 | cx: &mut Context<Self>, | 114 | cx: &mut Context<Self>, |
| 113 | ) { | 115 | ) { |
| 114 | - if self.chat.pending_builder_delete.as_deref() != Some(user_id) { | 116 | + if !confirmed(&mut self.chat.pending_builder_delete, user_id) { |
| 115 | - self.chat.pending_builder_delete = Some(user_id.to_string()); | ||
| 116 | cx.notify(); | 117 | cx.notify(); |
| 117 | return; | 118 | return; |
| 118 | } | 119 | } |
| 119 | - self.chat.pending_builder_delete = None; | ||
| 120 | let network = self.network.clone(); | 120 | let network = self.network.clone(); |
| 121 | let user_id = user_id.to_string(); | 121 | let user_id = user_id.to_string(); |
| 122 | 122 | ||
| @@ -367,12 +367,10 @@ impl Yumush { | |||
| 367 | window: &mut Window, | 367 | window: &mut Window, |
| 368 | cx: &mut Context<Self>, | 368 | cx: &mut Context<Self>, |
| 369 | ) { | 369 | ) { |
| 370 | - if self.chat.pending_builder_purge.as_deref() != Some(user_id) { | 370 | + if !confirmed(&mut self.chat.pending_builder_purge, user_id) { |
| 371 | - self.chat.pending_builder_purge = Some(user_id.to_string()); | ||
| 372 | cx.notify(); | 371 | cx.notify(); |
| 373 | return; | 372 | return; |
| 374 | } | 373 | } |
| 375 | - self.chat.pending_builder_purge = None; | ||
| 376 | let network = self.network.clone(); | 374 | let network = self.network.clone(); |
| 377 | let user_id = user_id.to_string(); | 375 | let user_id = user_id.to_string(); |
| 378 | 376 | ||
crates/client/src/gui/camera_view.rsmodified+24 -30
| @@ -3,13 +3,16 @@ use std::sync::Arc; | |||
| 3 | use common::share::{Fps, Kind, Quality, Resolution}; | 3 | use common::share::{Fps, Kind, Quality, Resolution}; |
| 4 | use gpui_kit::{ | 4 | use gpui_kit::{ |
| 5 | Context, Entity, InteractiveElement, IntoElement, ObjectFit, ParentElement, RenderImage, | 5 | Context, Entity, InteractiveElement, IntoElement, ObjectFit, ParentElement, RenderImage, |
| 6 | - StatefulInteractiveElement, Styled, StyledImage, Task, Window, assets::IconName, | 6 | + StatefulInteractiveElement, Styled, StyledImage, Task, Window, assets::IconName, div, img, px, |
| 7 | - component::Icon, div, img, px, | ||
| 8 | }; | 7 | }; |
| 9 | 8 | ||
| 10 | use super::{ | 9 | use super::{ |
| 11 | - Palette, Tooltip as _, Yumush, clickable, media_view::to_render_image, notify_error, | 10 | + Palette, Tooltip as _, Yumush, clickable, |
| 12 | - share_view::FRAME_TICK, text, | 11 | + media_view::to_render_image, |
| 12 | + notify_error, | ||
| 13 | + share_view::FRAME_TICK, | ||
| 14 | + text, | ||
| 15 | + widget::{icon_button, spawn_warn}, | ||
| 13 | }; | 16 | }; |
| 14 | use crate::share::session::WatchQuality; | 17 | use crate::share::session::WatchQuality; |
| 15 | 18 | ||
| @@ -56,15 +59,11 @@ impl Yumush { | |||
| 56 | ); | 59 | ); |
| 57 | let network = self.network.clone(); | 60 | let network = self.network.clone(); |
| 58 | let user_id = user_id.clone(); | 61 | let user_id = user_id.clone(); |
| 59 | - cx.spawn(async move |_, _| { | 62 | + spawn_warn(cx, "camera watch", async move { |
| 60 | - if let Err(error) = network | 63 | + network |
| 61 | .watch_share(&user_id, Kind::Camera, CAMERA_TILE) | 64 | .watch_share(&user_id, Kind::Camera, CAMERA_TILE) |
| 62 | .await | 65 | .await |
| 63 | - { | 66 | + }); |
| 64 | - tracing::warn!("camera watch failed: {error}"); | ||
| 65 | - } | ||
| 66 | - }) | ||
| 67 | - .detach(); | ||
| 68 | changed = true; | 67 | changed = true; |
| 69 | } | 68 | } |
| 70 | 69 | ||
| @@ -184,29 +183,24 @@ pub(super) fn camera_toggle( | |||
| 184 | ) -> impl IntoElement { | 183 | ) -> impl IntoElement { |
| 185 | let entity = entity.clone(); | 184 | let entity = entity.clone(); |
| 186 | 185 | ||
| 187 | - clickable("camera_toggle", palette, move |window, cx| { | 186 | + icon_button( |
| 188 | - entity.update(cx, |yumush, cx| yumush.toggle_camera(window, cx)); | 187 | + "camera_toggle", |
| 189 | - }) | 188 | + palette, |
| 190 | - .tip(if on { | 189 | + if on { |
| 191 | - "Turn off camera" | ||
| 192 | - } else { | ||
| 193 | - "Turn on camera" | ||
| 194 | - }) | ||
| 195 | - .size(px(26.)) | ||
| 196 | - .flex() | ||
| 197 | - .items_center() | ||
| 198 | - .justify_center() | ||
| 199 | - .rounded(px(6.)) | ||
| 200 | - .text_color(if on { palette.ok } else { palette.muted }) | ||
| 201 | - .child( | ||
| 202 | - Icon::new(if on { | ||
| 203 | IconName::VideoOff | 190 | IconName::VideoOff |
| 204 | } else { | 191 | } else { |
| 205 | IconName::Video | 192 | IconName::Video |
| 206 | - }) | 193 | + }, |
| 207 | - .w(px(14.)) | 194 | + if on { |
| 208 | - .h(px(14.)), | 195 | + "Turn off camera" |
| 196 | + } else { | ||
| 197 | + "Turn on camera" | ||
| 198 | + }, | ||
| 199 | + move |window, cx| { | ||
| 200 | + entity.update(cx, |yumush, cx| yumush.toggle_camera(window, cx)); | ||
| 201 | + }, | ||
| 209 | ) | 202 | ) |
| 203 | + .text_color(if on { palette.ok } else { palette.muted }) | ||
| 210 | } | 204 | } |
| 211 | 205 | ||
| 212 | fn camera_tile( | 206 | fn camera_tile( |
crates/client/src/gui/chat.rsmodified+133 -160
| @@ -14,7 +14,7 @@ use crate::gui::{ | |||
| 14 | FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, | 14 | FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, |
| 15 | builder::{BuilderTab, Transfer}, | 15 | builder::{BuilderTab, Transfer}, |
| 16 | clickable, community_name, | 16 | clickable, community_name, |
| 17 | - community_settings::{BanSort, LogSort, search_text}, | 17 | + community_settings::{BanSort, LogSort}, |
| 18 | composer::{self, Composer}, | 18 | composer::{self, Composer}, |
| 19 | entity_action, hoverable, id_time, | 19 | entity_action, hoverable, id_time, |
| 20 | media_view::{self, Media}, | 20 | media_view::{self, Media}, |
| @@ -23,13 +23,15 @@ use crate::gui::{ | |||
| 23 | profile::profile_popover, | 23 | profile::profile_popover, |
| 24 | rank_tag, | 24 | rank_tag, |
| 25 | share_view::{self, Viewer}, | 25 | share_view::{self, Viewer}, |
| 26 | - sidebar::SidebarTab, | 26 | + sidebar::{SidebarTab, unread_badge}, |
| 27 | snippet, | 27 | snippet, |
| 28 | voice_note::{self, VoiceNote}, | 28 | voice_note::{self, VoiceNote}, |
| 29 | + widget::{icon_button, ok_or_notify, search_text, spawn_done}, | ||
| 29 | }; | 30 | }; |
| 30 | use crate::network::Levels; | 31 | use crate::network::Levels; |
| 31 | use crate::settings::VOLUME; | 32 | use crate::settings::VOLUME; |
| 32 | use crate::share::session::ShareSample; | 33 | use crate::share::session::ShareSample; |
| 34 | +use crate::voice::VoiceSample; | ||
| 33 | use common::{ | 35 | use common::{ |
| 34 | constant::MESSAGE_PAGE_LIMIT, | 36 | constant::MESSAGE_PAGE_LIMIT, |
| 35 | event::Event, | 37 | event::Event, |
| @@ -45,7 +47,7 @@ use common::{ | |||
| 45 | use gpui_kit::{ | 47 | use gpui_kit::{ |
| 46 | Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, | 48 | Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, |
| 47 | InteractiveElement, IntoElement, ParentElement, RenderOnce, ScrollHandle, | 49 | InteractiveElement, IntoElement, ParentElement, RenderOnce, ScrollHandle, |
| 48 | - StatefulInteractiveElement, Styled, Task, Window, | 50 | + StatefulInteractiveElement, Styled, Subscription, Task, Window, |
| 49 | assets::IconName, | 51 | assets::IconName, |
| 50 | base::Selectable, | 52 | base::Selectable, |
| 51 | component::{ | 53 | component::{ |
| @@ -54,15 +56,13 @@ use gpui_kit::{ | |||
| 54 | popover::Popover, | 56 | popover::Popover, |
| 55 | searchable_list::SearchableVec, | 57 | searchable_list::SearchableVec, |
| 56 | select::SelectState, | 58 | select::SelectState, |
| 59 | + slider::{SliderEvent, SliderState}, | ||
| 60 | + text::TextView, | ||
| 57 | }, | 61 | }, |
| 58 | div, | 62 | div, |
| 59 | prelude::FluentBuilder as _, | 63 | prelude::FluentBuilder as _, |
| 60 | px, relative, | 64 | px, relative, |
| 61 | }; | 65 | }; |
| 62 | -use gpui_kit::{ | ||
| 63 | - Subscription, | ||
| 64 | - component::slider::{SliderEvent, SliderState}, | ||
| 65 | -}; | ||
| 66 | 66 | ||
| 67 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 67 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 68 | pub enum View { | 68 | pub enum View { |
| @@ -241,7 +241,7 @@ pub struct Chat { | |||
| 241 | pub(super) builder_voice_rooms: Vec<VoiceRoom>, | 241 | pub(super) builder_voice_rooms: Vec<VoiceRoom>, |
| 242 | pub(super) voice_task: Option<Task<()>>, | 242 | pub(super) voice_task: Option<Task<()>>, |
| 243 | pub(super) user_volume: Option<UserVolume>, | 243 | pub(super) user_volume: Option<UserVolume>, |
| 244 | - pub(super) voice_samples: VecDeque<crate::voice::VoiceSample>, | 244 | + pub(super) voice_samples: VecDeque<VoiceSample>, |
| 245 | pub(super) share_sample: ShareSample, | 245 | pub(super) share_sample: ShareSample, |
| 246 | pub(super) share_loss: HashMap<String, VecDeque<f32>>, | 246 | pub(super) share_loss: HashMap<String, VecDeque<f32>>, |
| 247 | pub(super) stats_tab: StatsTab, | 247 | pub(super) stats_tab: StatsTab, |
| @@ -538,7 +538,13 @@ impl Chat { | |||
| 538 | Event::MessageUpdated(message) => { | 538 | Event::MessageUpdated(message) => { |
| 539 | if self.is_selected(&message.community_id) { | 539 | if self.is_selected(&message.community_id) { |
| 540 | self.update_pin(&message); | 540 | self.update_pin(&message); |
| 541 | - self.insert_messages([message], me); | 541 | + if let Some(existing) = self |
| 542 | + .messages | ||
| 543 | + .iter_mut() | ||
| 544 | + .find(|existing| existing.id == message.id) | ||
| 545 | + { | ||
| 546 | + *existing = message; | ||
| 547 | + } | ||
| 542 | } | 548 | } |
| 543 | } | 549 | } |
| 544 | Event::MessageDeleted(message) => { | 550 | Event::MessageDeleted(message) => { |
| @@ -715,16 +721,15 @@ impl Chat { | |||
| 715 | fn forget_message(&mut self, message_id: &str) { | 721 | fn forget_message(&mut self, message_id: &str) { |
| 716 | self.messages.retain(|existing| existing.id != message_id); | 722 | self.messages.retain(|existing| existing.id != message_id); |
| 717 | 723 | ||
| 718 | - let stale = match &self.composer { | 724 | + match &mut self.composer { |
| 719 | - Composer::Compose { reply } => reply.as_deref() == Some(message_id), | 725 | + Composer::Select { ids } => ids.retain(|id| id != message_id), |
| 720 | - Composer::Edit { message_id: edited } => edited == message_id, | 726 | + Composer::Compose { reply } if reply.as_deref() == Some(message_id) => { |
| 721 | - Composer::Select { .. } => false, | 727 | + self.composer = Composer::Compose { reply: None }; |
| 722 | - }; | 728 | + } |
| 723 | - if stale { | 729 | + Composer::Edit { message_id: edited } if edited.as_str() == message_id => { |
| 724 | - self.composer = Composer::Compose { reply: None }; | 730 | + self.composer = Composer::Compose { reply: None }; |
| 725 | - } | 731 | + } |
| 726 | - if let Composer::Select { ids } = &mut self.composer { | 732 | + _ => {} |
| 727 | - ids.retain(|id| id != message_id); | ||
| 728 | } | 733 | } |
| 729 | } | 734 | } |
| 730 | 735 | ||
| @@ -866,18 +871,23 @@ impl Chat { | |||
| 866 | } | 871 | } |
| 867 | } | 872 | } |
| 868 | 873 | ||
| 869 | - pub fn selected_community(&self) -> Option<&Community> { | 874 | + fn community(&self, community_id: &str) -> Option<&Community> { |
| 870 | self.communities | 875 | self.communities |
| 871 | .iter() | 876 | .iter() |
| 872 | .chain(self.opened.as_ref()) | 877 | .chain(self.opened.as_ref()) |
| 873 | - .find(|community| self.is_selected(&community.id)) | 878 | + .find(|community| community.id == community_id) |
| 879 | + } | ||
| 880 | + | ||
| 881 | + pub fn selected_community(&self) -> Option<&Community> { | ||
| 882 | + self.community(self.selected_community_id.as_deref()?) | ||
| 883 | + } | ||
| 884 | + | ||
| 885 | + fn member_entry(&self, user_id: &str) -> Option<&Member> { | ||
| 886 | + self.members.iter().find(|member| member.user.id == user_id) | ||
| 874 | } | 887 | } |
| 875 | 888 | ||
| 876 | pub fn member(&self, user_id: &str) -> Option<&User> { | 889 | pub fn member(&self, user_id: &str) -> Option<&User> { |
| 877 | - self.members | 890 | + self.member_entry(user_id).map(|member| &member.user) |
| 878 | - .iter() | ||
| 879 | - .map(|member| &member.user) | ||
| 880 | - .find(|user| user.id == user_id) | ||
| 881 | } | 891 | } |
| 882 | 892 | ||
| 883 | pub fn author(&self, user_id: &str) -> Option<&User> { | 893 | pub fn author(&self, user_id: &str) -> Option<&User> { |
| @@ -904,11 +914,7 @@ impl Chat { | |||
| 904 | } | 914 | } |
| 905 | 915 | ||
| 906 | pub fn rank_of(&self, user: &User) -> Option<Rank> { | 916 | pub fn rank_of(&self, user: &User) -> Option<Rank> { |
| 907 | - let rank = self | 917 | + let rank = self.member_entry(&user.id).map(|member| member.rank); |
| 908 | - .members | ||
| 909 | - .iter() | ||
| 910 | - .find(|member| member.user.id == user.id) | ||
| 911 | - .map(|member| member.rank); | ||
| 912 | 918 | ||
| 913 | permission::effective_rank(user.role, rank) | 919 | permission::effective_rank(user.role, rank) |
| 914 | } | 920 | } |
| @@ -941,14 +947,6 @@ impl Chat { | |||
| 941 | } | 947 | } |
| 942 | 948 | ||
| 943 | pub fn update_member(&mut self, user: &User) { | 949 | pub fn update_member(&mut self, user: &User) { |
| 944 | - if let Some(member) = self | ||
| 945 | - .members | ||
| 946 | - .iter_mut() | ||
| 947 | - .find(|member| member.user.id == user.id) | ||
| 948 | - { | ||
| 949 | - member.user = user.clone(); | ||
| 950 | - } | ||
| 951 | - | ||
| 952 | let peers = self | 950 | let peers = self |
| 953 | .communities | 951 | .communities |
| 954 | .iter_mut() | 952 | .iter_mut() |
| @@ -967,6 +965,8 @@ impl Chat { | |||
| 967 | .iter_mut() | 965 | .iter_mut() |
| 968 | .map(|invitation| &mut invitation.inviter), | 966 | .map(|invitation| &mut invitation.inviter), |
| 969 | ) | 967 | ) |
| 968 | + .chain(self.members.iter_mut().map(|member| &mut member.user)) | ||
| 969 | + .chain(self.users.values_mut()) | ||
| 970 | .chain(peers); | 970 | .chain(peers); |
| 971 | for existing in known.filter(|existing| existing.id == user.id) { | 971 | for existing in known.filter(|existing| existing.id == user.id) { |
| 972 | *existing = user.clone(); | 972 | *existing = user.clone(); |
| @@ -1056,6 +1056,15 @@ impl Chat { | |||
| 1056 | self.builder_voice_rooms.clear(); | 1056 | self.builder_voice_rooms.clear(); |
| 1057 | self.ringing.clear(); | 1057 | self.ringing.clear(); |
| 1058 | self.ring_task = None; | 1058 | self.ring_task = None; |
| 1059 | + self.ghost = false; | ||
| 1060 | + self.drafts.clear(); | ||
| 1061 | + self.shares.clear(); | ||
| 1062 | + self.typing.clear(); | ||
| 1063 | + self.typing_sent.clear(); | ||
| 1064 | + self.users.clear(); | ||
| 1065 | + self.user_requests.clear(); | ||
| 1066 | + self.user_volume = None; | ||
| 1067 | + self.card_menu = CardMenu::Main; | ||
| 1059 | self.set_voice_off(); | 1068 | self.set_voice_off(); |
| 1060 | } | 1069 | } |
| 1061 | 1070 | ||
| @@ -1067,11 +1076,7 @@ impl Chat { | |||
| 1067 | } | 1076 | } |
| 1068 | 1077 | ||
| 1069 | pub fn voice_room(&self) -> Option<&Community> { | 1078 | pub fn voice_room(&self) -> Option<&Community> { |
| 1070 | - let community_id = self.voice_community()?; | 1079 | + self.community(self.voice_community()?) |
| 1071 | - self.communities | ||
| 1072 | - .iter() | ||
| 1073 | - .chain(self.opened.as_ref()) | ||
| 1074 | - .find(|community| community.id == community_id) | ||
| 1075 | } | 1080 | } |
| 1076 | 1081 | ||
| 1077 | pub fn in_voice(&self, community_id: &str) -> bool { | 1082 | pub fn in_voice(&self, community_id: &str) -> bool { |
| @@ -1088,10 +1093,8 @@ impl Chat { | |||
| 1088 | } | 1093 | } |
| 1089 | 1094 | ||
| 1090 | pub fn voice_enabled(&self, community_id: &str) -> bool { | 1095 | pub fn voice_enabled(&self, community_id: &str) -> bool { |
| 1091 | - self.communities | 1096 | + self.community(community_id) |
| 1092 | - .iter() | 1097 | + .is_some_and(|community| community.voice_enabled) |
| 1093 | - .chain(self.opened.as_ref()) | ||
| 1094 | - .any(|community| community.id == community_id && community.voice_enabled) | ||
| 1095 | } | 1098 | } |
| 1096 | 1099 | ||
| 1097 | pub fn share_of(&self, community_id: &str, user_id: &str, kind: Kind) -> Option<&Share> { | 1100 | pub fn share_of(&self, community_id: &str, user_id: &str, kind: Kind) -> Option<&Share> { |
| @@ -1164,12 +1167,8 @@ pub(super) fn create_community( | |||
| 1164 | let network = this.network.clone(); | 1167 | let network = this.network.clone(); |
| 1165 | 1168 | ||
| 1166 | cx.spawn_in(window, async move |this, cx| { | 1169 | cx.spawn_in(window, async move |this, cx| { |
| 1167 | - let community = match network.create_community(&name).await { | 1170 | + let Some(community) = ok_or_notify(network.create_community(&name).await, &this, cx) else { |
| 1168 | - Ok(community) => community, | 1171 | + return; |
| 1169 | - Err(error) => { | ||
| 1170 | - notify_error(&this, cx, error); | ||
| 1171 | - return; | ||
| 1172 | - } | ||
| 1173 | }; | 1172 | }; |
| 1174 | 1173 | ||
| 1175 | let _ = this.update_in(cx, |yumush, window, cx| { | 1174 | let _ = this.update_in(cx, |yumush, window, cx| { |
| @@ -1239,7 +1238,7 @@ impl Yumush { | |||
| 1239 | .flex() | 1238 | .flex() |
| 1240 | .flex_row() | 1239 | .flex_row() |
| 1241 | .size_full() | 1240 | .size_full() |
| 1242 | - .child(self.sidebar(&entity, &self.search_query(cx), palette)) | 1241 | + .child(self.sidebar(&entity, &search_text(&self.chat.search_input, cx), palette)) |
| 1243 | .child(self.main_panel(&entity, palette, cx)) | 1242 | .child(self.main_panel(&entity, palette, cx)) |
| 1244 | .children(self.fullscreen_viewer(&entity, palette)) | 1243 | .children(self.fullscreen_viewer(&entity, palette)) |
| 1245 | } | 1244 | } |
| @@ -1424,7 +1423,7 @@ impl Yumush { | |||
| 1424 | .absolute() | 1423 | .absolute() |
| 1425 | .top(px(-6.)) | 1424 | .top(px(-6.)) |
| 1426 | .right(px(-6.)) | 1425 | .right(px(-6.)) |
| 1427 | - .children(super::sidebar::unread_badge( | 1426 | + .children(unread_badge( |
| 1428 | palette, | 1427 | palette, |
| 1429 | false, | 1428 | false, |
| 1430 | Some(&Unread { | 1429 | Some(&Unread { |
| @@ -1468,12 +1467,10 @@ impl Yumush { | |||
| 1468 | .messages | 1467 | .messages |
| 1469 | .iter() | 1468 | .iter() |
| 1470 | .enumerate() | 1469 | .enumerate() |
| 1471 | - .flat_map(|(index, message)| { | 1470 | + .map(|(index, message)| { |
| 1472 | let first = | 1471 | let first = |
| 1473 | index == 0 || self.chat.messages[index - 1].user_id != message.user_id; | 1472 | index == 0 || self.chat.messages[index - 1].user_id != message.user_id; |
| 1474 | - let divider = (divider == Some(index)) | 1473 | + let row = render_message( |
| 1475 | - .then(|| new_divider(palette).into_any_element()); | ||
| 1476 | - divider.into_iter().chain([render_message( | ||
| 1477 | message, | 1474 | message, |
| 1478 | first, | 1475 | first, |
| 1479 | index > 0, | 1476 | index > 0, |
| @@ -1481,12 +1478,22 @@ impl Yumush { | |||
| 1481 | self.user.as_ref(), | 1478 | self.user.as_ref(), |
| 1482 | entity, | 1479 | entity, |
| 1483 | palette, | 1480 | palette, |
| 1484 | - )]) | 1481 | + ); |
| 1482 | + if divider == Some(index) { | ||
| 1483 | + div() | ||
| 1484 | + .flex() | ||
| 1485 | + .flex_col() | ||
| 1486 | + .child(new_divider(palette)) | ||
| 1487 | + .child(row) | ||
| 1488 | + .into_any_element() | ||
| 1489 | + } else { | ||
| 1490 | + row | ||
| 1491 | + } | ||
| 1485 | }), | 1492 | }), |
| 1486 | ) | 1493 | ) |
| 1487 | } | 1494 | } |
| 1488 | 1495 | ||
| 1489 | - fn composer(&self, entity: &Entity<Self>, palette: Palette) -> gpui_kit::AnyElement { | 1496 | + fn composer(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement { |
| 1490 | if let Composer::Select { ids } = &self.chat.composer { | 1497 | if let Composer::Select { ids } = &self.chat.composer { |
| 1491 | return div() | 1498 | return div() |
| 1492 | .p(px(16.)) | 1499 | .p(px(16.)) |
| @@ -1616,6 +1623,7 @@ impl Yumush { | |||
| 1616 | 1623 | ||
| 1617 | if let Some(community_id) = self.chat.selected_community_id.clone() { | 1624 | if let Some(community_id) = self.chat.selected_community_id.clone() { |
| 1618 | self.load_members(window, cx); | 1625 | self.load_members(window, cx); |
| 1626 | + self.chat.messages.clear(); | ||
| 1619 | self.load_messages(None, window, cx); | 1627 | self.load_messages(None, window, cx); |
| 1620 | self.load_voice(window, cx); | 1628 | self.load_voice(window, cx); |
| 1621 | self.load_shares(community_id, cx); | 1629 | self.load_shares(community_id, cx); |
| @@ -1626,12 +1634,8 @@ impl Yumush { | |||
| 1626 | let network = self.network.clone(); | 1634 | let network = self.network.clone(); |
| 1627 | 1635 | ||
| 1628 | cx.spawn_in(window, async move |this, cx| { | 1636 | cx.spawn_in(window, async move |this, cx| { |
| 1629 | - let communities = match network.communities().await { | 1637 | + let Some(communities) = ok_or_notify(network.communities().await, &this, cx) else { |
| 1630 | - Ok(communities) => communities, | 1638 | + return; |
| 1631 | - Err(error) => { | ||
| 1632 | - notify_error(&this, cx, error); | ||
| 1633 | - return; | ||
| 1634 | - } | ||
| 1635 | }; | 1639 | }; |
| 1636 | let unreads = network.unreads().await.unwrap_or_default(); | 1640 | let unreads = network.unreads().await.unwrap_or_default(); |
| 1637 | 1641 | ||
| @@ -1670,12 +1674,12 @@ impl Yumush { | |||
| 1670 | let network = self.network.clone(); | 1674 | let network = self.network.clone(); |
| 1671 | 1675 | ||
| 1672 | cx.spawn_in(window, async move |this, cx| { | 1676 | cx.spawn_in(window, async move |this, cx| { |
| 1673 | - let hits = match network.search_community(community_id.clone(), text).await { | 1677 | + let Some(hits) = ok_or_notify( |
| 1674 | - Ok(hits) => hits, | 1678 | + network.search_community(community_id.clone(), text).await, |
| 1675 | - Err(error) => { | 1679 | + &this, |
| 1676 | - notify_error(&this, cx, error); | 1680 | + cx, |
| 1677 | - return; | 1681 | + ) else { |
| 1678 | - } | 1682 | + return; |
| 1679 | }; | 1683 | }; |
| 1680 | 1684 | ||
| 1681 | let _ = this.update(cx, |yumush, cx| { | 1685 | let _ = this.update(cx, |yumush, cx| { |
| @@ -1695,12 +1699,8 @@ impl Yumush { | |||
| 1695 | let network = self.network.clone(); | 1699 | let network = self.network.clone(); |
| 1696 | 1700 | ||
| 1697 | cx.spawn_in(window, async move |this, cx| { | 1701 | cx.spawn_in(window, async move |this, cx| { |
| 1698 | - let pins = match network.pins(&community_id).await { | 1702 | + let Some(pins) = ok_or_notify(network.pins(&community_id).await, &this, cx) else { |
| 1699 | - Ok(pins) => pins, | 1703 | + return; |
| 1700 | - Err(error) => { | ||
| 1701 | - notify_error(&this, cx, error); | ||
| 1702 | - return; | ||
| 1703 | - } | ||
| 1704 | }; | 1704 | }; |
| 1705 | 1705 | ||
| 1706 | let _ = this.update(cx, |yumush, cx| { | 1706 | let _ = this.update(cx, |yumush, cx| { |
| @@ -1720,12 +1720,9 @@ impl Yumush { | |||
| 1720 | let network = self.network.clone(); | 1720 | let network = self.network.clone(); |
| 1721 | 1721 | ||
| 1722 | cx.spawn_in(window, async move |this, cx| { | 1722 | cx.spawn_in(window, async move |this, cx| { |
| 1723 | - let members = match network.members(&community_id).await { | 1723 | + let Some(members) = ok_or_notify(network.members(&community_id).await, &this, cx) |
| 1724 | - Ok(members) => members, | 1724 | + else { |
| 1725 | - Err(error) => { | 1725 | + return; |
| 1726 | - notify_error(&this, cx, error); | ||
| 1727 | - return; | ||
| 1728 | - } | ||
| 1729 | }; | 1726 | }; |
| 1730 | 1727 | ||
| 1731 | let _ = this.update_in(cx, |yumush, window, cx| { | 1728 | let _ = this.update_in(cx, |yumush, window, cx| { |
| @@ -1776,12 +1773,8 @@ impl Yumush { | |||
| 1776 | let network = self.network.clone(); | 1773 | let network = self.network.clone(); |
| 1777 | 1774 | ||
| 1778 | cx.spawn_in(window, async move |this, cx| { | 1775 | cx.spawn_in(window, async move |this, cx| { |
| 1779 | - let bans = match network.bans(&community_id).await { | 1776 | + let Some(bans) = ok_or_notify(network.bans(&community_id).await, &this, cx) else { |
| 1780 | - Ok(bans) => bans, | 1777 | + return; |
| 1781 | - Err(error) => { | ||
| 1782 | - notify_error(&this, cx, error); | ||
| 1783 | - return; | ||
| 1784 | - } | ||
| 1785 | }; | 1778 | }; |
| 1786 | 1779 | ||
| 1787 | let _ = this.update(cx, |yumush, cx| { | 1780 | let _ = this.update(cx, |yumush, cx| { |
| @@ -1842,15 +1835,14 @@ impl Yumush { | |||
| 1842 | let latest = before.is_none() && window.is_window_active(); | 1835 | let latest = before.is_none() && window.is_window_active(); |
| 1843 | 1836 | ||
| 1844 | cx.spawn_in(window, async move |this, cx| { | 1837 | cx.spawn_in(window, async move |this, cx| { |
| 1845 | - let page = match network | 1838 | + let Some(page) = ok_or_notify( |
| 1846 | - .read_messages(&community_id, before.as_deref()) | 1839 | + network |
| 1847 | - .await | 1840 | + .read_messages(&community_id, before.as_deref()) |
| 1848 | - { | 1841 | + .await, |
| 1849 | - Ok(page) => page, | 1842 | + &this, |
| 1850 | - Err(error) => { | 1843 | + cx, |
| 1851 | - notify_error(&this, cx, error); | 1844 | + ) else { |
| 1852 | - return; | 1845 | + return; |
| 1853 | - } | ||
| 1854 | }; | 1846 | }; |
| 1855 | 1847 | ||
| 1856 | let _ = this.update_in(cx, |yumush, window, cx| { | 1848 | let _ = this.update_in(cx, |yumush, window, cx| { |
| @@ -1909,12 +1901,9 @@ impl Yumush { | |||
| 1909 | let network = self.network.clone(); | 1901 | let network = self.network.clone(); |
| 1910 | let message_id = message_id.to_string(); | 1902 | let message_id = message_id.to_string(); |
| 1911 | 1903 | ||
| 1912 | - cx.spawn_in(window, async move |this, cx| { | 1904 | + spawn_done(window, cx, async move { |
| 1913 | - if let Err(error) = network.delete_message(&message_id).await { | 1905 | + network.delete_message(&message_id).await |
| 1914 | - notify_error(&this, cx, error); | 1906 | + }); |
| 1915 | - } | ||
| 1916 | - }) | ||
| 1917 | - .detach(); | ||
| 1918 | } | 1907 | } |
| 1919 | 1908 | ||
| 1920 | pub(super) fn leave_community( | 1909 | pub(super) fn leave_community( |
| @@ -1947,12 +1936,10 @@ impl Yumush { | |||
| 1947 | let network = self.network.clone(); | 1936 | let network = self.network.clone(); |
| 1948 | 1937 | ||
| 1949 | cx.spawn_in(window, async move |this, cx| { | 1938 | cx.spawn_in(window, async move |this, cx| { |
| 1950 | - let participants = match network.voice_participants(&community_id).await { | 1939 | + let Some(participants) = |
| 1951 | - Ok(participants) => participants, | 1940 | + ok_or_notify(network.voice_participants(&community_id).await, &this, cx) |
| 1952 | - Err(error) => { | 1941 | + else { |
| 1953 | - notify_error(&this, cx, error); | 1942 | + return; |
| 1954 | - return; | ||
| 1955 | - } | ||
| 1956 | }; | 1943 | }; |
| 1957 | 1944 | ||
| 1958 | let _ = this.update(cx, |yumush, cx| { | 1945 | let _ = this.update(cx, |yumush, cx| { |
| @@ -2274,22 +2261,18 @@ impl Yumush { | |||
| 2274 | yumush.toggle_voice(community_id.clone(), window, cx) | 2261 | yumush.toggle_voice(community_id.clone(), window, cx) |
| 2275 | }) | 2262 | }) |
| 2276 | }; | 2263 | }; |
| 2277 | - let button = if in_voice { | ||
| 2278 | - primary_button("voice_button", palette, on_click) | ||
| 2279 | - } else { | ||
| 2280 | - clickable("voice_button", palette, on_click) | ||
| 2281 | - }; | ||
| 2282 | - let button = if direct && in_voice { | ||
| 2283 | - button.bg(palette.danger) | ||
| 2284 | - } else { | ||
| 2285 | - button | ||
| 2286 | - }; | ||
| 2287 | let (icon, tip) = match (direct, in_voice) { | 2264 | let (icon, tip) = match (direct, in_voice) { |
| 2288 | (true, false) => (IconName::Phone, "Call"), | 2265 | (true, false) => (IconName::Phone, "Call"), |
| 2289 | (true, true) => (IconName::PhoneOff, "Hang up"), | 2266 | (true, true) => (IconName::PhoneOff, "Hang up"), |
| 2290 | (false, false) => (IconName::Headphones, "Join voice"), | 2267 | (false, false) => (IconName::Headphones, "Join voice"), |
| 2291 | (false, true) => (IconName::Headphones, "Leave voice"), | 2268 | (false, true) => (IconName::Headphones, "Leave voice"), |
| 2292 | }; | 2269 | }; |
| 2270 | + let button = if in_voice { | ||
| 2271 | + primary_button("voice_button", palette, on_click) | ||
| 2272 | + .when(direct, |button| button.bg(palette.danger)) | ||
| 2273 | + } else { | ||
| 2274 | + clickable("voice_button", palette, on_click).text_color(palette.accent) | ||
| 2275 | + }; | ||
| 2293 | 2276 | ||
| 2294 | Some( | 2277 | Some( |
| 2295 | button | 2278 | button |
| @@ -2299,11 +2282,6 @@ impl Yumush { | |||
| 2299 | .items_center() | 2282 | .items_center() |
| 2300 | .justify_center() | 2283 | .justify_center() |
| 2301 | .rounded(px(6.)) | 2284 | .rounded(px(6.)) |
| 2302 | - .text_color(if in_voice { | ||
| 2303 | - palette.on_accent | ||
| 2304 | - } else { | ||
| 2305 | - palette.accent | ||
| 2306 | - }) | ||
| 2307 | .child(Icon::new(icon).w(px(14.)).h(px(14.))), | 2285 | .child(Icon::new(icon).w(px(14.)).h(px(14.))), |
| 2308 | ) | 2286 | ) |
| 2309 | } | 2287 | } |
| @@ -2441,12 +2419,9 @@ impl Yumush { | |||
| 2441 | cx.notify(); | 2419 | cx.notify(); |
| 2442 | 2420 | ||
| 2443 | let network = self.network.clone(); | 2421 | let network = self.network.clone(); |
| 2444 | - cx.spawn_in(window, async move |this, cx| { | 2422 | + spawn_done(window, cx, async move { |
| 2445 | - if let Err(error) = network.decline_call(&community_id).await { | 2423 | + network.decline_call(&community_id).await |
| 2446 | - notify_error(&this, cx, error); | 2424 | + }); |
| 2447 | - } | ||
| 2448 | - }) | ||
| 2449 | - .detach(); | ||
| 2450 | } | 2425 | } |
| 2451 | 2426 | ||
| 2452 | fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { | 2427 | fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> { |
| @@ -2525,42 +2500,40 @@ impl Yumush { | |||
| 2525 | .flex() | 2500 | .flex() |
| 2526 | .items_center() | 2501 | .items_center() |
| 2527 | .child( | 2502 | .child( |
| 2528 | - clickable("mic_button", palette, move |window, cx| { | 2503 | + icon_button( |
| 2529 | - mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx)) | 2504 | + "mic_button", |
| 2530 | - }) | 2505 | + palette, |
| 2531 | - .tip(match (muted, self.hidden_in_voice()) { | 2506 | + mic_icon, |
| 2532 | - (true, true) => "Speak as ghost", | 2507 | + match (muted, self.hidden_in_voice()) { |
| 2533 | - (true, false) => "Unmute", | 2508 | + (true, true) => "Speak as ghost", |
| 2534 | - (false, _) => "Mute", | 2509 | + (true, false) => "Unmute", |
| 2535 | - }) | 2510 | + (false, _) => "Mute", |
| 2536 | - .size(px(26.)) | 2511 | + }, |
| 2537 | - .flex() | 2512 | + move |window, cx| { |
| 2538 | - .items_center() | 2513 | + mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx)) |
| 2539 | - .justify_center() | 2514 | + }, |
| 2540 | - .rounded(px(6.)) | 2515 | + ) |
| 2541 | .text_color(if muted || deafened { | 2516 | .text_color(if muted || deafened { |
| 2542 | palette.danger | 2517 | palette.danger |
| 2543 | } else { | 2518 | } else { |
| 2544 | palette.muted | 2519 | palette.muted |
| 2545 | - }) | 2520 | + }), |
| 2546 | - .child(Icon::new(mic_icon).w(px(14.)).h(px(14.))), | ||
| 2547 | ) | 2521 | ) |
| 2548 | .child( | 2522 | .child( |
| 2549 | - clickable("deafen_button", palette, move |_, cx| { | 2523 | + icon_button( |
| 2550 | - deafen_entity.update(cx, |yumush, cx| yumush.toggle_deafen(cx)) | 2524 | + "deafen_button", |
| 2551 | - }) | 2525 | + palette, |
| 2552 | - .tip(if deafened { "Undeafen" } else { "Deafen" }) | 2526 | + deafen_icon, |
| 2553 | - .size(px(26.)) | 2527 | + if deafened { "Undeafen" } else { "Deafen" }, |
| 2554 | - .flex() | 2528 | + move |_, cx| { |
| 2555 | - .items_center() | 2529 | + deafen_entity.update(cx, |yumush, cx| yumush.toggle_deafen(cx)) |
| 2556 | - .justify_center() | 2530 | + }, |
| 2557 | - .rounded(px(6.)) | 2531 | + ) |
| 2558 | .text_color(if deafened { | 2532 | .text_color(if deafened { |
| 2559 | palette.danger | 2533 | palette.danger |
| 2560 | } else { | 2534 | } else { |
| 2561 | palette.muted | 2535 | palette.muted |
| 2562 | - }) | 2536 | + }), |
| 2563 | - .child(Icon::new(deafen_icon).w(px(14.)).h(px(14.))), | ||
| 2564 | ) | 2537 | ) |
| 2565 | .children(self.chat.ghost.then(|| { | 2538 | .children(self.chat.ghost.then(|| { |
| 2566 | div() | 2539 | div() |
| @@ -2898,7 +2871,7 @@ fn render_message( | |||
| 2898 | .text_color(palette.body) | 2871 | .text_color(palette.body) |
| 2899 | .child( | 2872 | .child( |
| 2900 | div().min_w_0().child( | 2873 | div().min_w_0().child( |
| 2901 | - gpui_kit::component::text::TextView::markdown( | 2874 | + TextView::markdown( |
| 2902 | format!("message-body-{}", message.id), | 2875 | format!("message-body-{}", message.id), |
| 2903 | hard_breaks(&message.body), | 2876 | hard_breaks(&message.body), |
| 2904 | ) | 2877 | ) |
crates/client/src/gui/community_settings.rsmodified+48 -73
| @@ -1,5 +1,3 @@ | |||
| 1 | -use super::text; | ||
| 2 | -use crate::gui::STAMP; | ||
| 3 | use std::{collections::HashMap, sync::Arc}; | 1 | use std::{collections::HashMap, sync::Arc}; |
| 4 | 2 | ||
| 5 | use common::{ | 3 | use common::{ |
| @@ -22,14 +20,16 @@ use gpui_kit::{ | |||
| 22 | }; | 20 | }; |
| 23 | 21 | ||
| 24 | use super::{ | 22 | use super::{ |
| 25 | - Palette, Yumush, avatar, | 23 | + Palette, STAMP, Yumush, avatar, |
| 26 | - chat::{DeleteStep, View}, | 24 | + chat::View, |
| 27 | clickable, community_icon, entity_action, id_time, notify_error, | 25 | clickable, community_icon, entity_action, id_time, notify_error, |
| 28 | profile::user_link, | 26 | profile::user_link, |
| 29 | settings_page::{ | 27 | settings_page::{ |
| 30 | Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, | 28 | Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row, |
| 31 | - section, text_row, | 29 | + section, small_button, text_row, |
| 32 | }, | 30 | }, |
| 31 | + text, | ||
| 32 | + widget::search_text, | ||
| 33 | }; | 33 | }; |
| 34 | 34 | ||
| 35 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 35 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -225,7 +225,7 @@ impl Yumush { | |||
| 225 | let Some(community_id) = self.chat.selected_community_id.clone() else { | 225 | let Some(community_id) = self.chat.selected_community_id.clone() else { |
| 226 | return; | 226 | return; |
| 227 | }; | 227 | }; |
| 228 | - let name = self.chat.community_name_input.read(cx).text().to_string(); | 228 | + let name = self.chat.community_name_input.read(cx).text().to_string().trim().to_string(); |
| 229 | 229 | ||
| 230 | if let Err(error) = validate_community_name(&name) { | 230 | if let Err(error) = validate_community_name(&name) { |
| 231 | window.push_notification(Notification::error(error.to_string()), cx); | 231 | window.push_notification(Notification::error(error.to_string()), cx); |
| @@ -235,15 +235,8 @@ impl Yumush { | |||
| 235 | let network = self.network.clone(); | 235 | let network = self.network.clone(); |
| 236 | 236 | ||
| 237 | cx.spawn_in(window, async move |this, cx| { | 237 | cx.spawn_in(window, async move |this, cx| { |
| 238 | - match network.update_community(&community_id, &name).await { | 238 | + let result = network.update_community(&community_id, &name).await; |
| 239 | - Ok(community) => { | 239 | + apply_community(&this, cx, result); |
| 240 | - let _ = this.update(cx, |yumush, cx| { | ||
| 241 | - yumush.chat.insert_community(community); | ||
| 242 | - cx.notify(); | ||
| 243 | - }); | ||
| 244 | - } | ||
| 245 | - Err(error) => notify_error(&this, cx, error), | ||
| 246 | - } | ||
| 247 | }) | 240 | }) |
| 248 | .detach(); | 241 | .detach(); |
| 249 | } | 242 | } |
| @@ -286,31 +279,26 @@ impl Yumush { | |||
| 286 | } | 279 | } |
| 287 | 280 | ||
| 288 | pub(super) fn delete_community(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 281 | pub(super) fn delete_community(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 289 | - match self.chat.delete_step { | 282 | + if !self.confirm_delete(cx) { |
| 290 | - DeleteStep::Idle => { | 283 | + return; |
| 291 | - self.chat.delete_step = DeleteStep::Confirm; | ||
| 292 | - cx.notify(); | ||
| 293 | - } | ||
| 294 | - DeleteStep::Confirm => { | ||
| 295 | - let Some(community_id) = self.chat.selected_community_id.clone() else { | ||
| 296 | - return; | ||
| 297 | - }; | ||
| 298 | - let network = self.network.clone(); | ||
| 299 | - | ||
| 300 | - cx.spawn_in(window, async move |this, cx| { | ||
| 301 | - match network.delete_community(&community_id).await { | ||
| 302 | - Ok(()) => { | ||
| 303 | - let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 304 | - yumush.chat.remove_community(&community_id); | ||
| 305 | - yumush.show_view(View::Chat, window, cx); | ||
| 306 | - }); | ||
| 307 | - } | ||
| 308 | - Err(error) => notify_error(&this, cx, error), | ||
| 309 | - } | ||
| 310 | - }) | ||
| 311 | - .detach(); | ||
| 312 | - } | ||
| 313 | } | 284 | } |
| 285 | + let Some(community_id) = self.chat.selected_community_id.clone() else { | ||
| 286 | + return; | ||
| 287 | + }; | ||
| 288 | + let network = self.network.clone(); | ||
| 289 | + | ||
| 290 | + cx.spawn_in(window, async move |this, cx| { | ||
| 291 | + match network.delete_community(&community_id).await { | ||
| 292 | + Ok(()) => { | ||
| 293 | + let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 294 | + yumush.chat.remove_community(&community_id); | ||
| 295 | + yumush.show_view(View::Chat, window, cx); | ||
| 296 | + }); | ||
| 297 | + } | ||
| 298 | + Err(error) => notify_error(&this, cx, error), | ||
| 299 | + } | ||
| 300 | + }) | ||
| 301 | + .detach(); | ||
| 314 | } | 302 | } |
| 315 | 303 | ||
| 316 | pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context<Self>) { | 304 | pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context<Self>) { |
| @@ -454,19 +442,18 @@ fn voice_control( | |||
| 454 | ) -> impl IntoElement { | 442 | ) -> impl IntoElement { |
| 455 | let entity = entity.clone(); | 443 | let entity = entity.clone(); |
| 456 | 444 | ||
| 457 | - clickable("community_voice_button", palette, move |window, cx| { | 445 | + small_button( |
| 458 | - entity.update(cx, |yumush, cx| { | 446 | + "community_voice_button", |
| 459 | - yumush.set_community_voice(community_id.clone(), !enabled, window, cx) | 447 | + palette, |
| 460 | - }); | 448 | + palette.text, |
| 461 | - }) | 449 | + move |window, cx| { |
| 462 | - .h(px(28.)) | 450 | + entity.update(cx, |yumush, cx| { |
| 463 | - .px(px(10.)) | 451 | + yumush.set_community_voice(community_id.clone(), !enabled, window, cx) |
| 464 | - .flex() | 452 | + }); |
| 465 | - .items_center() | 453 | + }, |
| 466 | - .rounded(px(6.)) | 454 | + ) |
| 467 | .border_1() | 455 | .border_1() |
| 468 | .border_color(palette.border) | 456 | .border_color(palette.border) |
| 469 | - .text_size(text(13.)) | ||
| 470 | .child(if enabled { "On" } else { "Off" }) | 457 | .child(if enabled { "On" } else { "Off" }) |
| 471 | } | 458 | } |
| 472 | 459 | ||
| @@ -476,15 +463,9 @@ fn view_control( | |||
| 476 | palette: Palette, | 463 | palette: Palette, |
| 477 | open: fn(&mut Yumush, &mut Window, &mut Context<Yumush>), | 464 | open: fn(&mut Yumush, &mut Window, &mut Context<Yumush>), |
| 478 | ) -> impl IntoElement { | 465 | ) -> impl IntoElement { |
| 479 | - clickable(id, palette, entity_action(entity, open)) | 466 | + small_button(id, palette, palette.text, entity_action(entity, open)) |
| 480 | - .h(px(28.)) | ||
| 481 | - .px(px(10.)) | ||
| 482 | - .flex() | ||
| 483 | - .items_center() | ||
| 484 | - .rounded(px(6.)) | ||
| 485 | .border_1() | 467 | .border_1() |
| 486 | .border_color(palette.border) | 468 | .border_color(palette.border) |
| 487 | - .text_size(text(13.)) | ||
| 488 | .child("View") | 469 | .child("View") |
| 489 | } | 470 | } |
| 490 | 471 | ||
| @@ -552,10 +533,6 @@ fn moderation_body( | |||
| 552 | .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list)) | 533 | .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list)) |
| 553 | } | 534 | } |
| 554 | 535 | ||
| 555 | -pub(super) fn search_text(input: &Entity<InputState>, cx: &App) -> String { | ||
| 556 | - input.read(cx).text().to_string().trim().to_lowercase() | ||
| 557 | -} | ||
| 558 | - | ||
| 559 | fn ban_list<'a>(bans: &'a [Ban], query: &str, sort: BanSort) -> Vec<&'a Ban> { | 536 | fn ban_list<'a>(bans: &'a [Ban], query: &str, sort: BanSort) -> Vec<&'a Ban> { |
| 560 | let mut list: Vec<&Ban> = bans | 537 | let mut list: Vec<&Ban> = bans |
| 561 | .iter() | 538 | .iter() |
| @@ -645,20 +622,18 @@ fn leave_control( | |||
| 645 | ) -> impl IntoElement { | 622 | ) -> impl IntoElement { |
| 646 | let entity = entity.clone(); | 623 | let entity = entity.clone(); |
| 647 | 624 | ||
| 648 | - clickable("leave_community_button", palette, move |window, cx| { | 625 | + small_button( |
| 649 | - entity.update(cx, |yumush, cx| { | 626 | + "leave_community_button", |
| 650 | - yumush.leave_community(community_id.clone(), window, cx) | 627 | + palette, |
| 651 | - }); | 628 | + palette.danger, |
| 652 | - }) | 629 | + move |window, cx| { |
| 653 | - .h(px(28.)) | 630 | + entity.update(cx, |yumush, cx| { |
| 654 | - .px(px(10.)) | 631 | + yumush.leave_community(community_id.clone(), window, cx) |
| 655 | - .flex() | 632 | + }); |
| 656 | - .items_center() | 633 | + }, |
| 657 | - .rounded(px(6.)) | 634 | + ) |
| 658 | .border_1() | 635 | .border_1() |
| 659 | .border_color(palette.danger.opacity(0.5)) | 636 | .border_color(palette.danger.opacity(0.5)) |
| 660 | - .text_size(text(13.)) | ||
| 661 | - .text_color(palette.danger) | ||
| 662 | .child("Leave") | 637 | .child("Leave") |
| 663 | } | 638 | } |
| 664 | 639 | ||
crates/client/src/gui/composer.rsmodified+123 -96
| @@ -1,4 +1,5 @@ | |||
| 1 | use super::text; | 1 | use super::text; |
| 2 | +use super::widget::{compact_field, icon_button, panel, spawn_done}; | ||
| 2 | use std::time::{Duration, Instant}; | 3 | use std::time::{Duration, Instant}; |
| 3 | 4 | ||
| 4 | use common::{ | 5 | use common::{ |
| @@ -6,42 +7,52 @@ use common::{ | |||
| 6 | error::Error, | 7 | error::Error, |
| 7 | model::Attachment, | 8 | model::Attachment, |
| 8 | time::now_ms, | 9 | time::now_ms, |
| 9 | - validate::{validate_message_body, validate_new_message, validate_poll}, | 10 | + validate::{validate_new_message, validate_poll}, |
| 10 | }; | 11 | }; |
| 11 | use gpui_kit::{ | 12 | use gpui_kit::{ |
| 12 | Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, | 13 | Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, |
| 13 | IntoElement, KeyBinding, ParentElement, Styled, Window, actions, | 14 | IntoElement, KeyBinding, ParentElement, Styled, Window, actions, |
| 14 | assets::IconName, | 15 | assets::IconName, |
| 15 | component::{ | 16 | component::{ |
| 16 | - Icon, WindowExt, | 17 | + Icon, WindowExt, checkbox::Checkbox, input::InputState, notification::Notification, |
| 17 | - checkbox::Checkbox, | 18 | + popover::Popover, text::TextView, |
| 18 | - input::{Input, InputState}, | ||
| 19 | - notification::Notification, | ||
| 20 | - popover::Popover, | ||
| 21 | - text::TextView, | ||
| 22 | }, | 19 | }, |
| 23 | div, px, | 20 | div, px, |
| 24 | }; | 21 | }; |
| 25 | 22 | ||
| 26 | use super::{ | 23 | use super::{ |
| 27 | - Palette, Tooltip as _, Trigger, Yumush, | 24 | + Palette, Trigger, Yumush, |
| 28 | chat::{Chat, TYPING_SEND_INTERVAL}, | 25 | chat::{Chat, TYPING_SEND_INTERVAL}, |
| 29 | - clickable, hoverable, new_input, notify_error, pop_in, primary_button, | 26 | + hoverable, new_input, notify_error, pop_in, primary_button, |
| 30 | }; | 27 | }; |
| 31 | 28 | ||
| 32 | actions!(composer, [Bold, Italic, Code, Strike]); | 29 | actions!(composer, [Bold, Italic, Code, Strike]); |
| 33 | 30 | ||
| 34 | const CONTEXT: &str = "MessageComposer"; | 31 | const CONTEXT: &str = "MessageComposer"; |
| 35 | 32 | ||
| 33 | +const MOD: &str = if cfg!(target_os = "macos") { | ||
| 34 | + "Cmd" | ||
| 35 | +} else { | ||
| 36 | + "Ctrl" | ||
| 37 | +}; | ||
| 38 | + | ||
| 36 | const FORMAT_ROWS: [(&str, &str); 6] = [ | 39 | const FORMAT_ROWS: [(&str, &str); 6] = [ |
| 37 | - ("**bold**", "Ctrl+B"), | 40 | + ("**bold**", "B"), |
| 38 | - ("*italic*", "Ctrl+I"), | 41 | + ("*italic*", "I"), |
| 39 | - ("`code`", "Ctrl+E"), | 42 | + ("`code`", "E"), |
| 40 | - ("~~strike~~", "Ctrl+Shift+X"), | 43 | + ("~~strike~~", "Shift+X"), |
| 41 | ("> quote", ""), | 44 | ("> quote", ""), |
| 42 | ("- list", ""), | 45 | ("- list", ""), |
| 43 | ]; | 46 | ]; |
| 44 | 47 | ||
| 48 | +fn shortcut_label(keys: &str) -> String { | ||
| 49 | + if keys.is_empty() { | ||
| 50 | + String::new() | ||
| 51 | + } else { | ||
| 52 | + format!("{MOD}+{keys}") | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 45 | #[derive(Debug, Clone, PartialEq, Eq)] | 56 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 46 | pub enum Composer { | 57 | pub enum Composer { |
| 47 | Compose { reply: Option<String> }, | 58 | Compose { reply: Option<String> }, |
| @@ -164,17 +175,15 @@ fn edit_bar(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { | |||
| 164 | fn cancel_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { | 175 | fn cancel_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { |
| 165 | let entity = entity.clone(); | 176 | let entity = entity.clone(); |
| 166 | 177 | ||
| 167 | - clickable("cancel_composer", palette, move |window, cx| { | 178 | + icon_button( |
| 168 | - entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); | 179 | + "cancel_composer", |
| 169 | - }) | 180 | + palette, |
| 170 | - .tip("Cancel") | 181 | + IconName::Close, |
| 171 | - .size(px(20.)) | 182 | + "Cancel", |
| 172 | - .flex_shrink_0() | 183 | + move |window, cx| { |
| 173 | - .flex() | 184 | + entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); |
| 174 | - .items_center() | 185 | + }, |
| 175 | - .justify_center() | 186 | + ) |
| 176 | - .rounded(px(4.)) | ||
| 177 | - .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))) | ||
| 178 | } | 187 | } |
| 179 | 188 | ||
| 180 | impl Yumush { | 189 | impl Yumush { |
| @@ -270,10 +279,23 @@ impl Yumush { | |||
| 270 | retry_after_seconds, | 279 | retry_after_seconds, |
| 271 | }) => { | 280 | }) => { |
| 272 | let _ = this.update_in(cx, |yumush, window, cx| { | 281 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 273 | - yumush.slow_down(retry_after_seconds, &restore, body, pending, window, cx) | 282 | + yumush.slow_down( |
| 283 | + retry_after_seconds, | ||
| 284 | + &restore, | ||
| 285 | + &community_id, | ||
| 286 | + body, | ||
| 287 | + pending, | ||
| 288 | + window, | ||
| 289 | + cx, | ||
| 290 | + ) | ||
| 291 | + }); | ||
| 292 | + } | ||
| 293 | + Err(error) => { | ||
| 294 | + let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 295 | + yumush.restore_message(&restore, &community_id, body, pending, window, cx) | ||
| 274 | }); | 296 | }); |
| 297 | + notify_error(&this, cx, error); | ||
| 275 | } | 298 | } |
| 276 | - Err(error) => notify_error(&this, cx, error), | ||
| 277 | } | 299 | } |
| 278 | }) | 300 | }) |
| 279 | .detach(); | 301 | .detach(); |
| @@ -283,23 +305,40 @@ impl Yumush { | |||
| 283 | self.chat.composer = Composer::Compose { reply: None }; | 305 | self.chat.composer = Composer::Compose { reply: None }; |
| 284 | } | 306 | } |
| 285 | 307 | ||
| 286 | - fn slow_down( | 308 | + fn restore_message( |
| 287 | &mut self, | 309 | &mut self, |
| 288 | - seconds: u64, | ||
| 289 | input: &Entity<InputState>, | 310 | input: &Entity<InputState>, |
| 311 | + community_id: &str, | ||
| 290 | body: String, | 312 | body: String, |
| 291 | pending: Vec<Attachment>, | 313 | pending: Vec<Attachment>, |
| 292 | window: &mut Window, | 314 | window: &mut Window, |
| 293 | cx: &mut Context<Self>, | 315 | cx: &mut Context<Self>, |
| 294 | ) { | 316 | ) { |
| 317 | + if self.chat.selected_community_id.as_deref() != Some(community_id) { | ||
| 318 | + self.chat.drafts.insert(community_id.to_string(), body); | ||
| 319 | + return; | ||
| 320 | + } | ||
| 295 | if input.read(cx).text().len() == 0 { | 321 | if input.read(cx).text().len() == 0 { |
| 296 | input.update(cx, |state, cx| state.set_value(body, window, cx)); | 322 | input.update(cx, |state, cx| state.set_value(body, window, cx)); |
| 297 | } | 323 | } |
| 298 | if self.chat.media.pending.is_empty() { | 324 | if self.chat.media.pending.is_empty() { |
| 299 | self.chat.media.pending = pending; | 325 | self.chat.media.pending = pending; |
| 300 | } | 326 | } |
| 301 | - self.chat.slowed_until = Some(now_ms() + seconds * 1000); | ||
| 302 | cx.notify(); | 327 | cx.notify(); |
| 328 | + } | ||
| 329 | + | ||
| 330 | + fn slow_down( | ||
| 331 | + &mut self, | ||
| 332 | + seconds: u64, | ||
| 333 | + input: &Entity<InputState>, | ||
| 334 | + community_id: &str, | ||
| 335 | + body: String, | ||
| 336 | + pending: Vec<Attachment>, | ||
| 337 | + window: &mut Window, | ||
| 338 | + cx: &mut Context<Self>, | ||
| 339 | + ) { | ||
| 340 | + self.restore_message(input, community_id, body, pending, window, cx); | ||
| 341 | + self.chat.slowed_until = Some(now_ms() + seconds * 1000); | ||
| 303 | 342 | ||
| 304 | cx.spawn_in(window, async move |this, cx| { | 343 | cx.spawn_in(window, async move |this, cx| { |
| 305 | loop { | 344 | loop { |
| @@ -324,14 +363,22 @@ impl Yumush { | |||
| 324 | window: &mut Window, | 363 | window: &mut Window, |
| 325 | cx: &mut Context<Self>, | 364 | cx: &mut Context<Self>, |
| 326 | ) { | 365 | ) { |
| 327 | - if let Err(error) = validate_message_body(&body, self.max_message_length()) { | 366 | + if let Err(error) = validate_new_message(&body, 0, self.max_message_length()) { |
| 328 | window.push_notification(Notification::error(error.to_string()), cx); | 367 | window.push_notification(Notification::error(error.to_string()), cx); |
| 329 | return; | 368 | return; |
| 330 | } | 369 | } |
| 331 | let network = self.network.clone(); | 370 | let network = self.network.clone(); |
| 371 | + let restore = input.clone(); | ||
| 332 | 372 | ||
| 333 | cx.spawn_in(window, async move |this, cx| { | 373 | cx.spawn_in(window, async move |this, cx| { |
| 334 | if let Err(error) = network.update_message(&message_id, &body).await { | 374 | if let Err(error) = network.update_message(&message_id, &body).await { |
| 375 | + let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 376 | + if restore.read(cx).text().len() == 0 { | ||
| 377 | + restore.update(cx, |state, cx| state.set_value(body, window, cx)); | ||
| 378 | + yumush.chat.composer = Composer::Edit { message_id }; | ||
| 379 | + cx.notify(); | ||
| 380 | + } | ||
| 381 | + }); | ||
| 335 | notify_error(&this, cx, error); | 382 | notify_error(&this, cx, error); |
| 336 | } | 383 | } |
| 337 | }) | 384 | }) |
| @@ -446,10 +493,10 @@ impl Yumush { | |||
| 446 | pub fn bind_keys(cx: &mut App) { | 493 | pub fn bind_keys(cx: &mut App) { |
| 447 | let scope = format!("{CONTEXT} > Input"); | 494 | let scope = format!("{CONTEXT} > Input"); |
| 448 | cx.bind_keys([ | 495 | cx.bind_keys([ |
| 449 | - KeyBinding::new("ctrl-b", Bold, Some(scope.as_str())), | 496 | + KeyBinding::new("secondary-b", Bold, Some(scope.as_str())), |
| 450 | - KeyBinding::new("ctrl-i", Italic, Some(scope.as_str())), | 497 | + KeyBinding::new("secondary-i", Italic, Some(scope.as_str())), |
| 451 | - KeyBinding::new("ctrl-e", Code, Some(scope.as_str())), | 498 | + KeyBinding::new("secondary-e", Code, Some(scope.as_str())), |
| 452 | - KeyBinding::new("ctrl-shift-x", Strike, Some(scope.as_str())), | 499 | + KeyBinding::new("secondary-shift-x", Strike, Some(scope.as_str())), |
| 453 | ]); | 500 | ]); |
| 454 | } | 501 | } |
| 455 | 502 | ||
| @@ -499,16 +546,12 @@ pub fn format_popover(palette: Palette) -> impl IntoElement { | |||
| 499 | .content(move |_, _, _| { | 546 | .content(move |_, _, _| { |
| 500 | pop_in( | 547 | pop_in( |
| 501 | "format_list", | 548 | "format_list", |
| 502 | - div() | 549 | + panel(palette) |
| 503 | .w(px(340.)) | 550 | .w(px(340.)) |
| 504 | .p(px(8.)) | 551 | .p(px(8.)) |
| 505 | .flex() | 552 | .flex() |
| 506 | .flex_col() | 553 | .flex_col() |
| 507 | .gap(px(6.)) | 554 | .gap(px(6.)) |
| 508 | - .rounded(px(8.)) | ||
| 509 | - .border_1() | ||
| 510 | - .border_color(palette.border) | ||
| 511 | - .bg(palette.panel) | ||
| 512 | .text_size(text(12.)) | 555 | .text_size(text(12.)) |
| 513 | .children(FORMAT_ROWS.map(|(syntax, shortcut)| { | 556 | .children(FORMAT_ROWS.map(|(syntax, shortcut)| { |
| 514 | div() | 557 | div() |
| @@ -517,32 +560,17 @@ pub fn format_popover(palette: Palette) -> impl IntoElement { | |||
| 517 | .gap(px(12.)) | 560 | .gap(px(12.)) |
| 518 | .child(div().w(px(100.)).text_color(palette.muted).child(syntax)) | 561 | .child(div().w(px(100.)).text_color(palette.muted).child(syntax)) |
| 519 | .child(div().flex_1().child(TextView::markdown(syntax, syntax))) | 562 | .child(div().flex_1().child(TextView::markdown(syntax, syntax))) |
| 520 | - .child(div().text_color(palette.muted).child(shortcut)) | 563 | + .child( |
| 564 | + div() | ||
| 565 | + .text_color(palette.muted) | ||
| 566 | + .child(shortcut_label(shortcut)), | ||
| 567 | + ) | ||
| 521 | })), | 568 | })), |
| 522 | Anchor::BottomLeft, | 569 | Anchor::BottomLeft, |
| 523 | ) | 570 | ) |
| 524 | }) | 571 | }) |
| 525 | } | 572 | } |
| 526 | 573 | ||
| 527 | -pub(super) fn poll_field(input: &Entity<InputState>, palette: Palette) -> impl IntoElement { | ||
| 528 | - div() | ||
| 529 | - .h(px(30.)) | ||
| 530 | - .px(px(10.)) | ||
| 531 | - .flex() | ||
| 532 | - .items_center() | ||
| 533 | - .rounded(px(8.)) | ||
| 534 | - .border_1() | ||
| 535 | - .border_color(palette.border) | ||
| 536 | - .bg(palette.field) | ||
| 537 | - .child( | ||
| 538 | - Input::new(input) | ||
| 539 | - .appearance(false) | ||
| 540 | - .text_color(palette.text) | ||
| 541 | - .flex_1() | ||
| 542 | - .min_w_0(), | ||
| 543 | - ) | ||
| 544 | -} | ||
| 545 | - | ||
| 546 | pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { | 574 | pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { |
| 547 | let question = chat.poll_question.clone(); | 575 | let question = chat.poll_question.clone(); |
| 548 | let options = chat.poll_options.clone(); | 576 | let options = chat.poll_options.clone(); |
| @@ -565,38 +593,38 @@ pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i | |||
| 565 | let submit = entity.clone(); | 593 | let submit = entity.clone(); |
| 566 | pop_in( | 594 | pop_in( |
| 567 | "poll_form", | 595 | "poll_form", |
| 568 | - div() | 596 | + panel(palette) |
| 569 | .w(px(300.)) | 597 | .w(px(300.)) |
| 570 | .p(px(8.)) | 598 | .p(px(8.)) |
| 571 | .flex() | 599 | .flex() |
| 572 | .flex_col() | 600 | .flex_col() |
| 573 | .gap(px(6.)) | 601 | .gap(px(6.)) |
| 574 | - .rounded(px(8.)) | ||
| 575 | - .border_1() | ||
| 576 | - .border_color(palette.border) | ||
| 577 | - .bg(palette.panel) | ||
| 578 | .text_size(text(12.)) | 602 | .text_size(text(12.)) |
| 579 | - .child(poll_field(&question, palette)) | 603 | + .child(compact_field(palette, &question)) |
| 580 | .children(options.iter().enumerate().map(|(index, option)| { | 604 | .children(options.iter().enumerate().map(|(index, option)| { |
| 581 | let remove = entity.clone(); | 605 | let remove = entity.clone(); |
| 582 | div() | 606 | div() |
| 583 | .flex() | 607 | .flex() |
| 584 | .items_center() | 608 | .items_center() |
| 585 | .gap(px(6.)) | 609 | .gap(px(6.)) |
| 586 | - .child(div().flex_1().min_w_0().child(poll_field(option, palette))) | 610 | + .child( |
| 611 | + div() | ||
| 612 | + .flex_1() | ||
| 613 | + .min_w_0() | ||
| 614 | + .child(compact_field(palette, option)), | ||
| 615 | + ) | ||
| 587 | .children((options.len() > MINIMUM_POLL_OPTIONS).then(|| { | 616 | .children((options.len() > MINIMUM_POLL_OPTIONS).then(|| { |
| 588 | - clickable(format!("poll_remove_{index}"), palette, move |_, cx| { | 617 | + icon_button( |
| 589 | - remove.update(cx, |yumush, cx| { | 618 | + format!("poll_remove_{index}"), |
| 590 | - yumush.remove_poll_option(index, cx) | 619 | + palette, |
| 591 | - }); | 620 | + IconName::Close, |
| 592 | - }) | 621 | + "Remove option", |
| 593 | - .size(px(24.)) | 622 | + move |_, cx| { |
| 594 | - .flex() | 623 | + remove.update(cx, |yumush, cx| { |
| 595 | - .items_center() | 624 | + yumush.remove_poll_option(index, cx) |
| 596 | - .justify_center() | 625 | + }); |
| 597 | - .rounded(px(6.)) | 626 | + }, |
| 598 | - .text_color(palette.muted) | 627 | + ) |
| 599 | - .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))) | ||
| 600 | })) | 628 | })) |
| 601 | })) | 629 | })) |
| 602 | .child( | 630 | .child( |
| @@ -616,16 +644,17 @@ pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i | |||
| 616 | }), | 644 | }), |
| 617 | ) | 645 | ) |
| 618 | .children((options.len() < MAXIMUM_POLL_OPTIONS).then(|| { | 646 | .children((options.len() < MAXIMUM_POLL_OPTIONS).then(|| { |
| 619 | - clickable("poll_add", palette, move |window, cx| { | 647 | + icon_button( |
| 620 | - add.update(cx, |yumush, cx| yumush.add_poll_option(window, cx)); | 648 | + "poll_add", |
| 621 | - }) | 649 | + palette, |
| 622 | - .size(px(24.)) | 650 | + IconName::Plus, |
| 623 | - .flex() | 651 | + "Add option", |
| 624 | - .items_center() | 652 | + move |window, cx| { |
| 625 | - .justify_center() | 653 | + add.update(cx, |yumush, cx| { |
| 626 | - .rounded(px(6.)) | 654 | + yumush.add_poll_option(window, cx) |
| 627 | - .text_color(palette.muted) | 655 | + }); |
| 628 | - .child(Icon::new(IconName::Plus).w(px(14.)).h(px(14.))) | 656 | + }, |
| 657 | + ) | ||
| 629 | })), | 658 | })), |
| 630 | ) | 659 | ) |
| 631 | .child( | 660 | .child( |
| @@ -656,7 +685,9 @@ impl Yumush { | |||
| 656 | } | 685 | } |
| 657 | 686 | ||
| 658 | pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context<Self>) { | 687 | pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context<Self>) { |
| 659 | - if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS { | 688 | + if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS |
| 689 | + && index < self.chat.poll_options.len() | ||
| 690 | + { | ||
| 660 | self.chat.poll_options.remove(index); | 691 | self.chat.poll_options.remove(index); |
| 661 | cx.notify(); | 692 | cx.notify(); |
| 662 | } | 693 | } |
| @@ -680,15 +711,11 @@ impl Yumush { | |||
| 680 | let multiple = self.chat.poll_multiple; | 711 | let multiple = self.chat.poll_multiple; |
| 681 | let network = self.network.clone(); | 712 | let network = self.network.clone(); |
| 682 | 713 | ||
| 683 | - cx.spawn_in(window, async move |this, cx| { | 714 | + spawn_done(window, cx, async move { |
| 684 | - if let Err(error) = network | 715 | + network |
| 685 | .create_poll(&community_id, &question, options, multiple) | 716 | .create_poll(&community_id, &question, options, multiple) |
| 686 | .await | 717 | .await |
| 687 | - { | 718 | + }); |
| 688 | - notify_error(&this, cx, error); | ||
| 689 | - } | ||
| 690 | - }) | ||
| 691 | - .detach(); | ||
| 692 | 719 | ||
| 693 | self.chat | 720 | self.chat |
| 694 | .poll_question | 721 | .poll_question |
crates/client/src/gui/forward.rsmodified+8 -11
| @@ -12,8 +12,9 @@ use gpui_kit::{ | |||
| 12 | 12 | ||
| 13 | use super::{ | 13 | use super::{ |
| 14 | Yumush, clickable, community_name, | 14 | Yumush, clickable, community_name, |
| 15 | - composer::{Composer, poll_field}, | 15 | + composer::Composer, |
| 16 | - notify_error, palette, | 16 | + palette, |
| 17 | + widget::{compact_field, search_text, spawn_done}, | ||
| 17 | }; | 18 | }; |
| 18 | 19 | ||
| 19 | pub struct Forward { | 20 | pub struct Forward { |
| @@ -55,7 +56,7 @@ impl Forward { | |||
| 55 | impl Render for Forward { | 56 | impl Render for Forward { |
| 56 | fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { | 57 | fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 57 | let palette = palette(cx); | 58 | let palette = palette(cx); |
| 58 | - let query = self.filter.read(cx).text().to_string().to_lowercase(); | 59 | + let query = search_text(&self.filter, cx); |
| 59 | let entity = cx.entity(); | 60 | let entity = cx.entity(); |
| 60 | let keep_authors = self.keep_authors; | 61 | let keep_authors = self.keep_authors; |
| 61 | let rows: Vec<_> = { | 62 | let rows: Vec<_> = { |
| @@ -100,7 +101,7 @@ impl Render for Forward { | |||
| 100 | .flex() | 101 | .flex() |
| 101 | .flex_col() | 102 | .flex_col() |
| 102 | .gap(px(10.)) | 103 | .gap(px(10.)) |
| 103 | - .child(poll_field(&self.filter, palette)) | 104 | + .child(compact_field(palette, &self.filter)) |
| 104 | .child( | 105 | .child( |
| 105 | Checkbox::new("keep_authors") | 106 | Checkbox::new("keep_authors") |
| 106 | .label("Keep authors") | 107 | .label("Keep authors") |
| @@ -165,15 +166,11 @@ impl Yumush { | |||
| 165 | .collect(); | 166 | .collect(); |
| 166 | let network = self.network.clone(); | 167 | let network = self.network.clone(); |
| 167 | 168 | ||
| 168 | - cx.spawn_in(window, async move |this, cx| { | 169 | + spawn_done(window, cx, async move { |
| 169 | - if let Err(error) = network | 170 | + network |
| 170 | .forward_messages(ids, &community_id, keep_authors) | 171 | .forward_messages(ids, &community_id, keep_authors) |
| 171 | .await | 172 | .await |
| 172 | - { | 173 | + }); |
| 173 | - notify_error(&this, cx, error); | ||
| 174 | - } | ||
| 175 | - }) | ||
| 176 | - .detach(); | ||
| 177 | cx.notify(); | 174 | cx.notify(); |
| 178 | } | 175 | } |
| 179 | } | 176 | } |
crates/client/src/gui/media_view.rsmodified+1 -1
| @@ -523,7 +523,7 @@ impl Yumush { | |||
| 523 | .. | 523 | .. |
| 524 | }) = self.chat.media.playing.take() | 524 | }) = self.chat.media.playing.take() |
| 525 | { | 525 | { |
| 526 | - cx.drop_image(frame, None); | 526 | + cx.defer(move |cx| cx.drop_image(frame, None)); |
| 527 | } | 527 | } |
| 528 | } | 528 | } |
| 529 | } | 529 | } |
crates/client/src/gui/message_actions.rsmodified+95 -129
| @@ -7,20 +7,23 @@ use gpui_kit::{ | |||
| 7 | Anchor, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, | 7 | Anchor, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, |
| 8 | Stateful, Styled, Window, | 8 | Stateful, Styled, Window, |
| 9 | assets::IconName, | 9 | assets::IconName, |
| 10 | - component::{Icon, input::InputState, popover::Popover}, | 10 | + component::{ |
| 11 | + Icon, | ||
| 12 | + input::InputState, | ||
| 13 | + popover::{Popover, PopoverState}, | ||
| 14 | + }, | ||
| 11 | div, | 15 | div, |
| 12 | prelude::FluentBuilder as _, | 16 | prelude::FluentBuilder as _, |
| 13 | px, | 17 | px, |
| 14 | }; | 18 | }; |
| 15 | 19 | ||
| 16 | use super::{ | 20 | use super::{ |
| 17 | - CLOCK, Palette, Tooltip as _, Yumush, | 21 | + CLOCK, Palette, Yumush, avatar, |
| 18 | - auth::field, | ||
| 19 | - avatar, | ||
| 20 | chat::{Chat, ReportTarget}, | 22 | chat::{Chat, ReportTarget}, |
| 21 | clickable, | 23 | clickable, |
| 22 | composer::trigger_icon, | 24 | composer::trigger_icon, |
| 23 | entity_action, id_time, notify_error, pop_in, primary_button, sidebar, | 25 | entity_action, id_time, notify_error, pop_in, primary_button, sidebar, |
| 26 | + widget::{field, icon_button, panel, spawn_done}, | ||
| 24 | }; | 27 | }; |
| 25 | 28 | ||
| 26 | pub fn reactions( | 29 | pub fn reactions( |
| @@ -96,14 +99,10 @@ pub fn react_popover( | |||
| 96 | let popover = cx.entity(); | 99 | let popover = cx.entity(); |
| 97 | pop_in( | 100 | pop_in( |
| 98 | "react_list", | 101 | "react_list", |
| 99 | - div() | 102 | + panel(palette) |
| 100 | .flex() | 103 | .flex() |
| 101 | .gap(px(2.)) | 104 | .gap(px(2.)) |
| 102 | .p(px(4.)) | 105 | .p(px(4.)) |
| 103 | - .rounded(px(8.)) | ||
| 104 | - .border_1() | ||
| 105 | - .border_color(palette.border) | ||
| 106 | - .bg(palette.panel) | ||
| 107 | .children(REACTIONS.map(|emoji| { | 106 | .children(REACTIONS.map(|emoji| { |
| 108 | let entity = entity.clone(); | 107 | let entity = entity.clone(); |
| 109 | let message_id = message_id.clone(); | 108 | let message_id = message_id.clone(); |
| @@ -211,24 +210,63 @@ pub fn pin_mark(palette: Palette) -> impl IntoElement { | |||
| 211 | .child(Icon::new(IconName::Pin).w(px(12.)).h(px(12.))) | 210 | .child(Icon::new(IconName::Pin).w(px(12.)).h(px(12.))) |
| 212 | } | 211 | } |
| 213 | 212 | ||
| 213 | +struct Hit { | ||
| 214 | + message_id: String, | ||
| 215 | + name: String, | ||
| 216 | + time: Option<String>, | ||
| 217 | + body: String, | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +fn jump_row( | ||
| 221 | + prefix: &str, | ||
| 222 | + hit: &Hit, | ||
| 223 | + entity: &Entity<Yumush>, | ||
| 224 | + popover: &Entity<PopoverState>, | ||
| 225 | + palette: Palette, | ||
| 226 | +) -> Stateful<Div> { | ||
| 227 | + let entity = entity.clone(); | ||
| 228 | + let popover = popover.clone(); | ||
| 229 | + let message_id = hit.message_id.clone(); | ||
| 230 | + | ||
| 231 | + clickable( | ||
| 232 | + format!("{prefix}_{message_id}"), | ||
| 233 | + palette, | ||
| 234 | + move |window, cx| { | ||
| 235 | + popover.update(cx, |state, cx| state.dismiss(window, cx)); | ||
| 236 | + entity.update(cx, |yumush, cx| { | ||
| 237 | + yumush.go_to_message(message_id.clone(), window, cx) | ||
| 238 | + }); | ||
| 239 | + }, | ||
| 240 | + ) | ||
| 241 | + .flex() | ||
| 242 | + .gap(px(6.)) | ||
| 243 | + .px(px(8.)) | ||
| 244 | + .py(px(4.)) | ||
| 245 | + .rounded(px(6.)) | ||
| 246 | + .text_size(text(12.)) | ||
| 247 | + .child( | ||
| 248 | + div() | ||
| 249 | + .flex_shrink_0() | ||
| 250 | + .font_weight(FontWeight::SEMIBOLD) | ||
| 251 | + .child(hit.name.clone()), | ||
| 252 | + ) | ||
| 253 | +} | ||
| 254 | + | ||
| 214 | pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { | 255 | pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { |
| 215 | let entity = entity.clone(); | 256 | let entity = entity.clone(); |
| 216 | let input = chat.community_search.clone(); | 257 | let input = chat.community_search.clone(); |
| 217 | - let hits: Vec<(String, String, String, String)> = chat | 258 | + let hits: Vec<Hit> = chat |
| 218 | .community_hits | 259 | .community_hits |
| 219 | .iter() | 260 | .iter() |
| 220 | - .map(|hit| { | 261 | + .map(|hit| Hit { |
| 221 | - let name = hit | 262 | + message_id: hit.message.id.clone(), |
| 263 | + name: hit | ||
| 222 | .author | 264 | .author |
| 223 | .as_ref() | 265 | .as_ref() |
| 224 | .map(|user| user.username.clone()) | 266 | .map(|user| user.username.clone()) |
| 225 | - .unwrap_or_default(); | 267 | + .unwrap_or_default(), |
| 226 | - ( | 268 | + time: Some(id_time(&hit.message.id, CLOCK)), |
| 227 | - hit.message.id.clone(), | 269 | + body: quote_text(&hit.message.body, hit.message.attachments.len()), |
| 228 | - name, | ||
| 229 | - id_time(&hit.message.id, CLOCK), | ||
| 230 | - quote_text(&hit.message.body, hit.message.attachments.len()), | ||
| 231 | - ) | ||
| 232 | }) | 270 | }) |
| 233 | .collect(); | 271 | .collect(); |
| 234 | 272 | ||
| @@ -245,51 +283,22 @@ pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> | |||
| 245 | let popover = cx.entity(); | 283 | let popover = cx.entity(); |
| 246 | pop_in( | 284 | pop_in( |
| 247 | "search_list", | 285 | "search_list", |
| 248 | - div() | 286 | + panel(palette) |
| 249 | .w(px(320.)) | 287 | .w(px(320.)) |
| 250 | .p(px(4.)) | 288 | .p(px(4.)) |
| 251 | .flex() | 289 | .flex() |
| 252 | .flex_col() | 290 | .flex_col() |
| 253 | .gap(px(4.)) | 291 | .gap(px(4.)) |
| 254 | - .rounded(px(8.)) | ||
| 255 | - .border_1() | ||
| 256 | - .border_color(palette.border) | ||
| 257 | - .bg(palette.panel) | ||
| 258 | .child(sidebar::input_box(&input, palette)) | 292 | .child(sidebar::input_box(&input, palette)) |
| 259 | - .children(hits.iter().map(|(message_id, name, time, body)| { | 293 | + .children(hits.iter().map(|hit| { |
| 260 | - let entity = entity.clone(); | 294 | + jump_row("search_hit", hit, &entity, &popover, palette) |
| 261 | - let popover = popover.clone(); | 295 | + .children(hit.time.as_ref().map(|time| { |
| 262 | - let message_id = message_id.clone(); | 296 | + div() |
| 263 | - clickable( | 297 | + .flex_shrink_0() |
| 264 | - format!("search_hit_{message_id}"), | 298 | + .text_color(palette.muted) |
| 265 | - palette, | 299 | + .child(time.clone()) |
| 266 | - move |window, cx| { | 300 | + })) |
| 267 | - popover.update(cx, |state, cx| state.dismiss(window, cx)); | 301 | + .child(div().flex_1().min_w_0().truncate().child(hit.body.clone())) |
| 268 | - let message_id = message_id.clone(); | ||
| 269 | - entity.update(cx, |yumush, cx| { | ||
| 270 | - yumush.go_to_message(message_id, window, cx) | ||
| 271 | - }); | ||
| 272 | - }, | ||
| 273 | - ) | ||
| 274 | - .flex() | ||
| 275 | - .gap(px(6.)) | ||
| 276 | - .px(px(8.)) | ||
| 277 | - .py(px(4.)) | ||
| 278 | - .rounded(px(6.)) | ||
| 279 | - .text_size(text(12.)) | ||
| 280 | - .child( | ||
| 281 | - div() | ||
| 282 | - .flex_shrink_0() | ||
| 283 | - .font_weight(FontWeight::SEMIBOLD) | ||
| 284 | - .child(name.clone()), | ||
| 285 | - ) | ||
| 286 | - .child( | ||
| 287 | - div() | ||
| 288 | - .flex_shrink_0() | ||
| 289 | - .text_color(palette.muted) | ||
| 290 | - .child(time.clone()), | ||
| 291 | - ) | ||
| 292 | - .child(div().flex_1().min_w_0().truncate().child(body.clone())) | ||
| 293 | })), | 302 | })), |
| 294 | Anchor::TopRight, | 303 | Anchor::TopRight, |
| 295 | ) | 304 | ) |
| @@ -298,19 +307,17 @@ pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> | |||
| 298 | 307 | ||
| 299 | pub fn pins_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { | 308 | pub fn pins_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement { |
| 300 | let entity = entity.clone(); | 309 | let entity = entity.clone(); |
| 301 | - let pins: Vec<(String, String, String)> = chat | 310 | + let pins: Vec<Hit> = chat |
| 302 | .pins | 311 | .pins |
| 303 | .iter() | 312 | .iter() |
| 304 | - .map(|pin| { | 313 | + .map(|pin| Hit { |
| 305 | - let name = chat | 314 | + message_id: pin.id.clone(), |
| 315 | + name: chat | ||
| 306 | .author(&pin.user_id) | 316 | .author(&pin.user_id) |
| 307 | .map(|user| user.username.clone()) | 317 | .map(|user| user.username.clone()) |
| 308 | - .unwrap_or_default(); | 318 | + .unwrap_or_default(), |
| 309 | - ( | 319 | + time: None, |
| 310 | - pin.id.clone(), | 320 | + body: quote_text(&pin.body, pin.attachments.len()), |
| 311 | - name, | ||
| 312 | - quote_text(&pin.body, pin.attachments.len()), | ||
| 313 | - ) | ||
| 314 | }) | 321 | }) |
| 315 | .collect(); | 322 | .collect(); |
| 316 | 323 | ||
| @@ -322,50 +329,20 @@ pub fn pins_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i | |||
| 322 | let popover = cx.entity(); | 329 | let popover = cx.entity(); |
| 323 | pop_in( | 330 | pop_in( |
| 324 | "pins_list", | 331 | "pins_list", |
| 325 | - div() | 332 | + panel(palette) |
| 326 | .w(px(260.)) | 333 | .w(px(260.)) |
| 327 | .p(px(4.)) | 334 | .p(px(4.)) |
| 328 | .flex() | 335 | .flex() |
| 329 | .flex_col() | 336 | .flex_col() |
| 330 | .gap(px(2.)) | 337 | .gap(px(2.)) |
| 331 | - .rounded(px(8.)) | 338 | + .children(pins.iter().map(|hit| { |
| 332 | - .border_1() | 339 | + jump_row("pin_hit", hit, &entity, &popover, palette).child( |
| 333 | - .border_color(palette.border) | ||
| 334 | - .bg(palette.panel) | ||
| 335 | - .children(pins.iter().map(|(message_id, name, body)| { | ||
| 336 | - let entity = entity.clone(); | ||
| 337 | - let popover = popover.clone(); | ||
| 338 | - let message_id = message_id.clone(); | ||
| 339 | - clickable( | ||
| 340 | - format!("pin_hit_{message_id}"), | ||
| 341 | - palette, | ||
| 342 | - move |window, cx| { | ||
| 343 | - popover.update(cx, |state, cx| state.dismiss(window, cx)); | ||
| 344 | - let message_id = message_id.clone(); | ||
| 345 | - entity.update(cx, |yumush, cx| { | ||
| 346 | - yumush.go_to_message(message_id, window, cx) | ||
| 347 | - }); | ||
| 348 | - }, | ||
| 349 | - ) | ||
| 350 | - .flex() | ||
| 351 | - .gap(px(6.)) | ||
| 352 | - .px(px(8.)) | ||
| 353 | - .py(px(4.)) | ||
| 354 | - .rounded(px(6.)) | ||
| 355 | - .text_size(text(12.)) | ||
| 356 | - .child( | ||
| 357 | - div() | ||
| 358 | - .flex_shrink_0() | ||
| 359 | - .font_weight(FontWeight::SEMIBOLD) | ||
| 360 | - .child(name.clone()), | ||
| 361 | - ) | ||
| 362 | - .child( | ||
| 363 | div() | 340 | div() |
| 364 | .flex_1() | 341 | .flex_1() |
| 365 | .min_w_0() | 342 | .min_w_0() |
| 366 | .truncate() | 343 | .truncate() |
| 367 | .text_color(palette.muted) | 344 | .text_color(palette.muted) |
| 368 | - .child(body.clone()), | 345 | + .child(hit.body.clone()), |
| 369 | ) | 346 | ) |
| 370 | })), | 347 | })), |
| 371 | Anchor::TopRight, | 348 | Anchor::TopRight, |
| @@ -389,15 +366,11 @@ pub fn actions( | |||
| 389 | let id = message.id.as_str(); | 366 | let id = message.id.as_str(); |
| 390 | let armed = chat.pending_message_delete.as_deref() == Some(id); | 367 | let armed = chat.pending_message_delete.as_deref() == Some(id); |
| 391 | 368 | ||
| 392 | - div() | 369 | + panel(palette) |
| 393 | .flex() | 370 | .flex() |
| 394 | .items_center() | 371 | .items_center() |
| 395 | .gap(px(2.)) | 372 | .gap(px(2.)) |
| 396 | .p(px(2.)) | 373 | .p(px(2.)) |
| 397 | - .rounded(px(8.)) | ||
| 398 | - .border_1() | ||
| 399 | - .border_color(palette.border) | ||
| 400 | - .bg(palette.panel) | ||
| 401 | .when(!armed, |this| this.invisible()) | 374 | .when(!armed, |this| this.invisible()) |
| 402 | .group_hover(group, |style| style.visible()) | 375 | .group_hover(group, |style| style.visible()) |
| 403 | .child(action( | 376 | .child(action( |
| @@ -514,12 +487,9 @@ impl Yumush { | |||
| 514 | .any(|message| message.id == message_id && message.pinned); | 487 | .any(|message| message.id == message_id && message.pinned); |
| 515 | let network = self.network.clone(); | 488 | let network = self.network.clone(); |
| 516 | 489 | ||
| 517 | - cx.spawn_in(window, async move |this, cx| { | 490 | + spawn_done(window, cx, async move { |
| 518 | - if let Err(error) = network.pin(&message_id, !pinned).await { | 491 | + network.pin(&message_id, !pinned).await |
| 519 | - notify_error(&this, cx, error); | 492 | + }); |
| 520 | - } | ||
| 521 | - }) | ||
| 522 | - .detach(); | ||
| 523 | } | 493 | } |
| 524 | 494 | ||
| 525 | pub(super) fn toggle_reaction( | 495 | pub(super) fn toggle_reaction( |
| @@ -531,12 +501,9 @@ impl Yumush { | |||
| 531 | ) { | 501 | ) { |
| 532 | let network = self.network.clone(); | 502 | let network = self.network.clone(); |
| 533 | 503 | ||
| 534 | - cx.spawn_in(window, async move |this, cx| { | 504 | + spawn_done(window, cx, async move { |
| 535 | - if let Err(error) = network.react(&message_id, &emoji).await { | 505 | + network.react(&message_id, &emoji).await |
| 536 | - notify_error(&this, cx, error); | 506 | + }); |
| 537 | - } | ||
| 538 | - }) | ||
| 539 | - .detach(); | ||
| 540 | } | 507 | } |
| 541 | 508 | ||
| 542 | pub(super) fn start_report( | 509 | pub(super) fn start_report( |
| @@ -600,16 +567,15 @@ fn action( | |||
| 600 | let entity = entity.clone(); | 567 | let entity = entity.clone(); |
| 601 | let message_id = message_id.to_string(); | 568 | let message_id = message_id.to_string(); |
| 602 | 569 | ||
| 603 | - clickable(format!("{tip}_{message_id}"), palette, move |window, cx| { | 570 | + icon_button( |
| 604 | - let message_id = message_id.clone(); | 571 | + format!("{tip}_{message_id}"), |
| 605 | - entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); | 572 | + palette, |
| 606 | - }) | 573 | + icon, |
| 607 | - .tip(tip) | 574 | + tip, |
| 575 | + move |window, cx| { | ||
| 576 | + let message_id = message_id.clone(); | ||
| 577 | + entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); | ||
| 578 | + }, | ||
| 579 | + ) | ||
| 608 | .size(px(24.)) | 580 | .size(px(24.)) |
| 609 | - .flex() | ||
| 610 | - .items_center() | ||
| 611 | - .justify_center() | ||
| 612 | - .rounded(px(6.)) | ||
| 613 | - .text_color(palette.muted) | ||
| 614 | - .child(Icon::new(icon).w(px(14.)).h(px(14.))) | ||
| 615 | } | 581 | } |
crates/client/src/gui/poll.rsmodified+25 -32
| @@ -6,7 +6,12 @@ use gpui_kit::{ | |||
| 6 | Window, assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, | 6 | Window, assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, |
| 7 | }; | 7 | }; |
| 8 | 8 | ||
| 9 | -use super::{Palette, Tooltip as _, Yumush, chat::Chat, clickable, notify_error, text}; | 9 | +use super::{ |
| 10 | + Palette, Yumush, | ||
| 11 | + chat::Chat, | ||
| 12 | + clickable, text, | ||
| 13 | + widget::{icon_button, spawn_done}, | ||
| 14 | +}; | ||
| 10 | 15 | ||
| 11 | pub fn voter_count(poll: &Poll) -> usize { | 16 | pub fn voter_count(poll: &Poll) -> usize { |
| 12 | poll.options | 17 | poll.options |
| @@ -160,21 +165,16 @@ pub fn poll_card( | |||
| 160 | .children(poll.closed.then_some("Closed")) | 165 | .children(poll.closed.then_some("Closed")) |
| 161 | .children(close_id.map(|close_id| { | 166 | .children(close_id.map(|close_id| { |
| 162 | let close_entity = entity.clone(); | 167 | let close_entity = entity.clone(); |
| 163 | - clickable( | 168 | + icon_button( |
| 164 | format!("poll_close_{close_id}"), | 169 | format!("poll_close_{close_id}"), |
| 165 | palette, | 170 | palette, |
| 171 | + IconName::CircleStop, | ||
| 172 | + "End poll", | ||
| 166 | move |window, cx| { | 173 | move |window, cx| { |
| 167 | let close_id = close_id.clone(); | 174 | let close_id = close_id.clone(); |
| 168 | close_entity.update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); | 175 | close_entity.update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); |
| 169 | }, | 176 | }, |
| 170 | ) | 177 | ) |
| 171 | - .tip("End poll") | ||
| 172 | - .size(px(22.)) | ||
| 173 | - .flex() | ||
| 174 | - .items_center() | ||
| 175 | - .justify_center() | ||
| 176 | - .rounded(px(6.)) | ||
| 177 | - .child(Icon::new(IconName::CircleStop).w(px(13.)).h(px(13.))) | ||
| 178 | })); | 178 | })); |
| 179 | 179 | ||
| 180 | div() | 180 | div() |
| @@ -282,21 +282,18 @@ impl Yumush { | |||
| 282 | ), | 282 | ), |
| 283 | ), | 283 | ), |
| 284 | ) | 284 | ) |
| 285 | - .child( | 285 | + .child(icon_button( |
| 286 | - clickable("poll_banner_jump", palette, move |window, cx| { | 286 | + "poll_banner_jump", |
| 287 | + palette, | ||
| 288 | + IconName::ArrowUpRight, | ||
| 289 | + "Jump to message", | ||
| 290 | + move |window, cx| { | ||
| 287 | let message_id = message_id.clone(); | 291 | let message_id = message_id.clone(); |
| 288 | jump.update(cx, |yumush, cx| { | 292 | jump.update(cx, |yumush, cx| { |
| 289 | yumush.go_to_message(message_id, window, cx) | 293 | yumush.go_to_message(message_id, window, cx) |
| 290 | }); | 294 | }); |
| 291 | - }) | 295 | + }, |
| 292 | - .size(px(24.)) | 296 | + )), |
| 293 | - .flex() | ||
| 294 | - .items_center() | ||
| 295 | - .justify_center() | ||
| 296 | - .rounded(px(6.)) | ||
| 297 | - .text_color(palette.muted) | ||
| 298 | - .child(Icon::new(IconName::ArrowUpRight).w(px(14.)).h(px(14.))), | ||
| 299 | - ), | ||
| 300 | ) | 297 | ) |
| 301 | .children(expanded.then(|| { | 298 | .children(expanded.then(|| { |
| 302 | poll_card( | 299 | poll_card( |
| @@ -320,12 +317,9 @@ impl Yumush { | |||
| 320 | ) { | 317 | ) { |
| 321 | let network = self.network.clone(); | 318 | let network = self.network.clone(); |
| 322 | 319 | ||
| 323 | - cx.spawn_in(window, async move |this, cx| { | 320 | + spawn_done(window, cx, async move { |
| 324 | - if let Err(error) = network.vote(&message_id, positions).await { | 321 | + network.vote(&message_id, positions).await |
| 325 | - notify_error(&this, cx, error); | 322 | + }); |
| 326 | - } | ||
| 327 | - }) | ||
| 328 | - .detach(); | ||
| 329 | } | 323 | } |
| 330 | 324 | ||
| 331 | pub(super) fn close_poll( | 325 | pub(super) fn close_poll( |
| @@ -336,11 +330,10 @@ impl Yumush { | |||
| 336 | ) { | 330 | ) { |
| 337 | let network = self.network.clone(); | 331 | let network = self.network.clone(); |
| 338 | 332 | ||
| 339 | - cx.spawn_in(window, async move |this, cx| { | 333 | + spawn_done( |
| 340 | - if let Err(error) = network.close_poll(&message_id).await { | 334 | + window, |
| 341 | - notify_error(&this, cx, error); | 335 | + cx, |
| 342 | - } | 336 | + async move { network.close_poll(&message_id).await }, |
| 343 | - }) | 337 | + ); |
| 344 | - .detach(); | ||
| 345 | } | 338 | } |
| 346 | } | 339 | } |
crates/client/src/gui/profile.rsmodified+16 -24
| @@ -1,5 +1,3 @@ | |||
| 1 | -use super::text; | ||
| 2 | -use crate::gui::DAY_YEAR; | ||
| 3 | use std::{collections::HashMap, sync::Arc}; | 1 | use std::{collections::HashMap, sync::Arc}; |
| 4 | 2 | ||
| 5 | use common::{ | 3 | use common::{ |
| @@ -23,9 +21,10 @@ use gpui_kit::{ | |||
| 23 | use super::chat::{CardMenu, ReportTarget, View}; | 21 | use super::chat::{CardMenu, ReportTarget, View}; |
| 24 | use super::message_actions::report_bar; | 22 | use super::message_actions::report_bar; |
| 25 | use super::social::Relation; | 23 | use super::social::Relation; |
| 24 | +use super::widget::{panel, spawn_done}; | ||
| 26 | use super::{ | 25 | use super::{ |
| 27 | - Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, palette, | 26 | + DAY_YEAR, Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, |
| 28 | - pop_in, presence_color, rank_tag, swap_in, | 27 | + notify_error, palette, pop_in, presence_color, rank_tag, swap_in, text, |
| 29 | }; | 28 | }; |
| 30 | 29 | ||
| 31 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -81,6 +80,7 @@ pub(super) fn profile_popover( | |||
| 81 | .on_open_change(move |_, _, cx| { | 80 | .on_open_change(move |_, _, cx| { |
| 82 | notify_entity.update(cx, |yumush, cx| { | 81 | notify_entity.update(cx, |yumush, cx| { |
| 83 | yumush.chat.card_menu = CardMenu::Main; | 82 | yumush.chat.card_menu = CardMenu::Main; |
| 83 | + yumush.chat.pending_user_delete = None; | ||
| 84 | yumush.open_user_volume(&volume_user_id, cx); | 84 | yumush.open_user_volume(&volume_user_id, cx); |
| 85 | cx.notify() | 85 | cx.notify() |
| 86 | }) | 86 | }) |
| @@ -220,16 +220,12 @@ impl Card { | |||
| 220 | }; | 220 | }; |
| 221 | let divider = (!rows.is_empty()).then(|| div().h(px(1.)).my(px(4.)).bg(palette.border)); | 221 | let divider = (!rows.is_empty()).then(|| div().h(px(1.)).my(px(4.)).bg(palette.border)); |
| 222 | 222 | ||
| 223 | - div() | 223 | + panel(palette) |
| 224 | .w(px(260.)) | 224 | .w(px(260.)) |
| 225 | .p(px(16.)) | 225 | .p(px(16.)) |
| 226 | .flex() | 226 | .flex() |
| 227 | .flex_col() | 227 | .flex_col() |
| 228 | .gap(px(10.)) | 228 | .gap(px(10.)) |
| 229 | - .rounded(px(8.)) | ||
| 230 | - .border_1() | ||
| 231 | - .border_color(palette.border) | ||
| 232 | - .bg(palette.panel) | ||
| 233 | .child(avatar(palette, &self.user, px(48.), text(18.), avatars)) | 229 | .child(avatar(palette, &self.user, px(48.), text(18.), avatars)) |
| 234 | .child( | 230 | .child( |
| 235 | div() | 231 | div() |
| @@ -655,10 +651,12 @@ impl Yumush { | |||
| 655 | Ok(()) => { | 651 | Ok(()) => { |
| 656 | let _ = this.update_in(cx, |yumush, window, cx| { | 652 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 657 | window.close_dialog(cx); | 653 | window.close_dialog(cx); |
| 658 | - yumush.load_bans(window, cx); | 654 | + if removal == Removal::Ban { |
| 655 | + yumush.load_bans(window, cx); | ||
| 656 | + } | ||
| 659 | }); | 657 | }); |
| 660 | } | 658 | } |
| 661 | - Err(error) => super::notify_error(&this, cx, error), | 659 | + Err(error) => notify_error(&this, cx, error), |
| 662 | } | 660 | } |
| 663 | }) | 661 | }) |
| 664 | .detach(); | 662 | .detach(); |
| @@ -677,12 +675,9 @@ impl Yumush { | |||
| 677 | let network = self.network.clone(); | 675 | let network = self.network.clone(); |
| 678 | let user_id = user_id.to_string(); | 676 | let user_id = user_id.to_string(); |
| 679 | 677 | ||
| 680 | - cx.spawn_in(window, async move |this, cx| { | 678 | + spawn_done(window, cx, async move { |
| 681 | - if let Err(error) = network.set_rank(&community_id, &user_id, rank).await { | 679 | + network.set_rank(&community_id, &user_id, rank).await |
| 682 | - super::notify_error(&this, cx, error); | 680 | + }); |
| 683 | - } | ||
| 684 | - }) | ||
| 685 | - .detach(); | ||
| 686 | } | 681 | } |
| 687 | 682 | ||
| 688 | pub(super) fn set_presence( | 683 | pub(super) fn set_presence( |
| @@ -699,12 +694,9 @@ impl Yumush { | |||
| 699 | 694 | ||
| 700 | let network = self.network.clone(); | 695 | let network = self.network.clone(); |
| 701 | 696 | ||
| 702 | - cx.spawn_in(window, async move |this, cx| { | 697 | + spawn_done(window, cx, async move { |
| 703 | - if let Err(error) = network.update_presence(presence).await { | 698 | + network.update_presence(presence).await |
| 704 | - super::notify_error(&this, cx, error); | 699 | + }); |
| 705 | - } | ||
| 706 | - }) | ||
| 707 | - .detach(); | ||
| 708 | } | 700 | } |
| 709 | 701 | ||
| 710 | pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context<Self>) { | 702 | pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context<Self>) { |
| @@ -730,7 +722,7 @@ impl Yumush { | |||
| 730 | cx.notify(); | 722 | cx.notify(); |
| 731 | }); | 723 | }); |
| 732 | } | 724 | } |
| 733 | - Err(error) => super::notify_error(&this, cx, error), | 725 | + Err(error) => notify_error(&this, cx, error), |
| 734 | } | 726 | } |
| 735 | }) | 727 | }) |
| 736 | .detach(); | 728 | .detach(); |
crates/client/src/gui/settings_page.rsmodified+44 -48
| @@ -1,5 +1,4 @@ | |||
| 1 | -use super::text; | 1 | +use std::future::Future; |
| 2 | -use std::{future::Future, path::Path}; | ||
| 3 | 2 | ||
| 4 | use common::{error::Error, model::User}; | 3 | use common::{error::Error, model::User}; |
| 5 | use gpui_kit::{ | 4 | use gpui_kit::{ |
| @@ -7,15 +6,18 @@ use gpui_kit::{ | |||
| 7 | InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, | 6 | InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, |
| 8 | StatefulInteractiveElement, Styled, WeakEntity, Window, | 7 | StatefulInteractiveElement, Styled, WeakEntity, Window, |
| 9 | assets::IconName, | 8 | assets::IconName, |
| 10 | - component::{Icon, input::InputState, switch::Switch}, | 9 | + component::{input::InputState, switch::Switch}, |
| 11 | div, | 10 | div, |
| 12 | prelude::FluentBuilder as _, | 11 | prelude::FluentBuilder as _, |
| 13 | px, transparent_black, | 12 | px, transparent_black, |
| 14 | }; | 13 | }; |
| 15 | 14 | ||
| 16 | use super::{ | 15 | use super::{ |
| 17 | - Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable, | 16 | + Palette, Tooltip as _, Yumush, avatar, |
| 18 | - notify_error, primary_button, | 17 | + chat::DeleteStep, |
| 18 | + chat::View, | ||
| 19 | + clickable, notify_error, primary_button, text, | ||
| 20 | + widget::{field, icon_button}, | ||
| 19 | }; | 21 | }; |
| 20 | use crate::settings::{self, FontSize, ThemeChoice}; | 22 | use crate::settings::{self, FontSize, ThemeChoice}; |
| 21 | 23 | ||
| @@ -203,31 +205,35 @@ impl Yumush { | |||
| 203 | .detach(); | 205 | .detach(); |
| 204 | } | 206 | } |
| 205 | 207 | ||
| 208 | + pub(super) fn confirm_delete(&mut self, cx: &mut Context<Self>) -> bool { | ||
| 209 | + if self.chat.delete_step == DeleteStep::Idle { | ||
| 210 | + self.chat.delete_step = DeleteStep::Confirm; | ||
| 211 | + cx.notify(); | ||
| 212 | + return false; | ||
| 213 | + } | ||
| 214 | + true | ||
| 215 | + } | ||
| 216 | + | ||
| 206 | pub(super) fn delete_account(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 217 | pub(super) fn delete_account(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 207 | - match self.chat.delete_step { | 218 | + if !self.confirm_delete(cx) { |
| 208 | - DeleteStep::Idle => { | 219 | + return; |
| 209 | - self.chat.delete_step = DeleteStep::Confirm; | ||
| 210 | - cx.notify(); | ||
| 211 | - } | ||
| 212 | - DeleteStep::Confirm => { | ||
| 213 | - let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { | ||
| 214 | - return; | ||
| 215 | - }; | ||
| 216 | - let network = self.network.clone(); | ||
| 217 | - | ||
| 218 | - cx.spawn_in(window, async move |this, cx| { | ||
| 219 | - match network.delete_user(&user_id).await { | ||
| 220 | - Ok(()) => { | ||
| 221 | - let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 222 | - yumush.end_session(window, cx); | ||
| 223 | - }); | ||
| 224 | - } | ||
| 225 | - Err(error) => notify_error(&this, cx, error), | ||
| 226 | - } | ||
| 227 | - }) | ||
| 228 | - .detach(); | ||
| 229 | - } | ||
| 230 | } | 220 | } |
| 221 | + let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { | ||
| 222 | + return; | ||
| 223 | + }; | ||
| 224 | + let network = self.network.clone(); | ||
| 225 | + | ||
| 226 | + cx.spawn_in(window, async move |this, cx| { | ||
| 227 | + match network.delete_user(&user_id).await { | ||
| 228 | + Ok(()) => { | ||
| 229 | + let _ = this.update_in(cx, |yumush, window, cx| { | ||
| 230 | + yumush.end_session(window, cx); | ||
| 231 | + }); | ||
| 232 | + } | ||
| 233 | + Err(error) => notify_error(&this, cx, error), | ||
| 234 | + } | ||
| 235 | + }) | ||
| 236 | + .detach(); | ||
| 231 | } | 237 | } |
| 232 | 238 | ||
| 233 | pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context<Self>) { | 239 | pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context<Self>) { |
| @@ -277,7 +283,7 @@ pub(super) fn picked_avatar( | |||
| 277 | let path = paths.into_iter().next()?; | 283 | let path = paths.into_iter().next()?; |
| 278 | Some( | 284 | Some( |
| 279 | executor | 285 | executor |
| 280 | - .spawn(async move { read_avatar_file(&path, maximum) }) | 286 | + .spawn(async move { crate::avatar::prepare(&std::fs::read(&path)?, maximum) }) |
| 281 | .await, | 287 | .await, |
| 282 | ) | 288 | ) |
| 283 | } | 289 | } |
| @@ -298,19 +304,15 @@ pub(super) fn header( | |||
| 298 | .gap(px(8.)) | 304 | .gap(px(8.)) |
| 299 | .border_b_1() | 305 | .border_b_1() |
| 300 | .border_color(palette.border) | 306 | .border_color(palette.border) |
| 301 | - .child( | 307 | + .child(icon_button( |
| 302 | - clickable("settings_back_button", palette, move |window, cx| { | 308 | + "settings_back_button", |
| 309 | + palette, | ||
| 310 | + IconName::ArrowLeft, | ||
| 311 | + "Back", | ||
| 312 | + move |window, cx| { | ||
| 303 | entity.update(cx, |yumush, cx| yumush.show_view(View::Chat, window, cx)); | 313 | entity.update(cx, |yumush, cx| yumush.show_view(View::Chat, window, cx)); |
| 304 | - }) | 314 | + }, |
| 305 | - .tip("Back") | 315 | + )) |
| 306 | - .size(px(26.)) | ||
| 307 | - .flex() | ||
| 308 | - .items_center() | ||
| 309 | - .justify_center() | ||
| 310 | - .rounded(px(6.)) | ||
| 311 | - .text_color(palette.muted) | ||
| 312 | - .child(Icon::new(IconName::ArrowLeft).w(px(14.)).h(px(14.))), | ||
| 313 | - ) | ||
| 314 | .child(div().font_weight(FontWeight::SEMIBOLD).child(title)) | 316 | .child(div().font_weight(FontWeight::SEMIBOLD).child(title)) |
| 315 | } | 317 | } |
| 316 | 318 | ||
| @@ -530,7 +532,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity<Yumush>, palette: P | |||
| 530 | })) | 532 | })) |
| 531 | } | 533 | } |
| 532 | 534 | ||
| 533 | -fn small_button( | 535 | +pub(super) fn small_button( |
| 534 | id: &'static str, | 536 | id: &'static str, |
| 535 | palette: Palette, | 537 | palette: Palette, |
| 536 | color: Hsla, | 538 | color: Hsla, |
| @@ -567,12 +569,6 @@ pub(super) fn delete_control( | |||
| 567 | .child(if confirming { "Confirm" } else { "Delete" }) | 569 | .child(if confirming { "Confirm" } else { "Delete" }) |
| 568 | } | 570 | } |
| 569 | 571 | ||
| 570 | -fn read_avatar_file(path: &Path, maximum: u64) -> Result<Vec<u8>, Error> { | ||
| 571 | - let bytes = std::fs::read(path)?; | ||
| 572 | - | ||
| 573 | - crate::avatar::prepare(&bytes, maximum) | ||
| 574 | -} | ||
| 575 | - | ||
| 576 | pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div { | 572 | pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div { |
| 577 | div() | 573 | div() |
| 578 | .min_h(px(48.)) | 574 | .min_h(px(48.)) |
crates/client/src/gui/share_view.rsmodified+43 -46
| @@ -16,9 +16,15 @@ use gpui_kit::{ | |||
| 16 | }; | 16 | }; |
| 17 | 17 | ||
| 18 | use super::{ | 18 | use super::{ |
| 19 | - Palette, Tooltip as _, Trigger, Yumush, camera_view, chat::View, clickable, entity_action, | 19 | + Palette, Tooltip as _, Trigger, Yumush, camera_view, |
| 20 | - media_view::to_render_image, notify_error, pop_in, settings_page::segmented, | 20 | + chat::View, |
| 21 | - sidebar::icon_button, text, wave::wave, | 21 | + clickable, entity_action, |
| 22 | + media_view::to_render_image, | ||
| 23 | + notify_error, pop_in, | ||
| 24 | + settings_page::segmented, | ||
| 25 | + text, | ||
| 26 | + wave::wave, | ||
| 27 | + widget::{icon_button, spawn_warn}, | ||
| 22 | }; | 28 | }; |
| 23 | use crate::{ | 29 | use crate::{ |
| 24 | settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings}, | 30 | settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings}, |
| @@ -68,14 +74,6 @@ impl AudioMode { | |||
| 68 | ShareAudio::Source(_) => Self::App, | 74 | ShareAudio::Source(_) => Self::App, |
| 69 | } | 75 | } |
| 70 | } | 76 | } |
| 71 | - | ||
| 72 | - fn audio(self, first: String) -> ShareAudio { | ||
| 73 | - match self { | ||
| 74 | - Self::Off => ShareAudio::Off, | ||
| 75 | - Self::Everything => ShareAudio::Everything, | ||
| 76 | - Self::App => ShareAudio::Source(first), | ||
| 77 | - } | ||
| 78 | - } | ||
| 79 | } | 77 | } |
| 80 | 78 | ||
| 81 | pub(super) struct Viewer { | 79 | pub(super) struct Viewer { |
| @@ -125,12 +123,11 @@ impl Yumush { | |||
| 125 | settings::save(&self.settings); | 123 | settings::save(&self.settings); |
| 126 | if self.network.set_share_settings(self.settings.share.clone()) { | 124 | if self.network.set_share_settings(self.settings.share.clone()) { |
| 127 | let network = self.network.clone(); | 125 | let network = self.network.clone(); |
| 128 | - cx.spawn(async move |_, _| { | 126 | + spawn_warn( |
| 129 | - if let Err(error) = network.update_share().await { | 127 | + cx, |
| 130 | - tracing::warn!("share update failed: {error}"); | 128 | + "share update", |
| 131 | - } | 129 | + async move { network.update_share().await }, |
| 132 | - }) | 130 | + ); |
| 133 | - .detach(); | ||
| 134 | } | 131 | } |
| 135 | cx.notify(); | 132 | cx.notify(); |
| 136 | } | 133 | } |
| @@ -164,13 +161,14 @@ impl Yumush { | |||
| 164 | } | 161 | } |
| 165 | 162 | ||
| 166 | pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context<Self>) { | 163 | pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context<Self>) { |
| 167 | - let first = self | ||
| 168 | - .share_apps | ||
| 169 | - .first() | ||
| 170 | - .map(|app| app.node.clone()) | ||
| 171 | - .unwrap_or_default(); | ||
| 172 | - self.update_share(cx, |settings| settings.audio = mode.audio(first)); | ||
| 173 | self.refresh_share_apps(cx); | 164 | self.refresh_share_apps(cx); |
| 165 | + let audio = match (mode, self.share_apps.first()) { | ||
| 166 | + (AudioMode::Off, _) => ShareAudio::Off, | ||
| 167 | + (AudioMode::Everything, _) => ShareAudio::Everything, | ||
| 168 | + (AudioMode::App, Some(app)) => ShareAudio::Source(app.node.clone()), | ||
| 169 | + (AudioMode::App, None) => return, | ||
| 170 | + }; | ||
| 171 | + self.update_share(cx, |settings| settings.audio = audio); | ||
| 174 | } | 172 | } |
| 175 | 173 | ||
| 176 | pub(super) fn set_share_source(&mut self, node: String, cx: &mut Context<Self>) { | 174 | pub(super) fn set_share_source(&mut self, node: String, cx: &mut Context<Self>) { |
| @@ -266,6 +264,11 @@ impl Yumush { | |||
| 266 | } else { | 264 | } else { |
| 267 | cx.spawn_in(window, async move |this, cx| { | 265 | cx.spawn_in(window, async move |this, cx| { |
| 268 | if let Err(error) = network.watch_share(&user_id, kind, watch).await { | 266 | if let Err(error) = network.watch_share(&user_id, kind, watch).await { |
| 267 | + let _ = this.update(cx, |yumush, cx| { | ||
| 268 | + if yumush.is_watching(&user_id, kind) { | ||
| 269 | + yumush.close_viewer(cx); | ||
| 270 | + } | ||
| 271 | + }); | ||
| 269 | notify_error(&this, cx, error); | 272 | notify_error(&this, cx, error); |
| 270 | } | 273 | } |
| 271 | }) | 274 | }) |
| @@ -279,7 +282,7 @@ impl Yumush { | |||
| 279 | return; | 282 | return; |
| 280 | }; | 283 | }; |
| 281 | if let Some(frame) = viewer.frame { | 284 | if let Some(frame) = viewer.frame { |
| 282 | - cx.drop_image(frame, None); | 285 | + cx.defer(move |cx| cx.drop_image(frame, None)); |
| 283 | } | 286 | } |
| 284 | let network = self.network.clone(); | 287 | let network = self.network.clone(); |
| 285 | if viewer.kind == Kind::Camera && self.chat.cameras.contains_key(&viewer.user_id) { | 288 | if viewer.kind == Kind::Camera && self.chat.cameras.contains_key(&viewer.user_id) { |
| @@ -340,29 +343,24 @@ impl Yumush { | |||
| 340 | palette, | 343 | palette, |
| 341 | )) | 344 | )) |
| 342 | .child( | 345 | .child( |
| 343 | - clickable("share_toggle", palette, move |window, cx| { | 346 | + icon_button( |
| 344 | - toggle.update(cx, |yumush, cx| yumush.toggle_share(window, cx)); | 347 | + "share_toggle", |
| 345 | - }) | 348 | + palette, |
| 346 | - .tip(if sharing { | 349 | + if sharing { |
| 347 | - "Stop sharing" | ||
| 348 | - } else { | ||
| 349 | - "Share screen" | ||
| 350 | - }) | ||
| 351 | - .size(px(26.)) | ||
| 352 | - .flex() | ||
| 353 | - .items_center() | ||
| 354 | - .justify_center() | ||
| 355 | - .rounded(px(6.)) | ||
| 356 | - .text_color(if sharing { palette.ok } else { palette.muted }) | ||
| 357 | - .child( | ||
| 358 | - Icon::new(if sharing { | ||
| 359 | IconName::ScreenShareOff | 350 | IconName::ScreenShareOff |
| 360 | } else { | 351 | } else { |
| 361 | IconName::ScreenShare | 352 | IconName::ScreenShare |
| 362 | - }) | 353 | + }, |
| 363 | - .w(px(14.)) | 354 | + if sharing { |
| 364 | - .h(px(14.)), | 355 | + "Stop sharing" |
| 365 | - ), | 356 | + } else { |
| 357 | + "Share screen" | ||
| 358 | + }, | ||
| 359 | + move |window, cx| { | ||
| 360 | + toggle.update(cx, |yumush, cx| yumush.toggle_share(window, cx)); | ||
| 361 | + }, | ||
| 362 | + ) | ||
| 363 | + .text_color(if sharing { palette.ok } else { palette.muted }), | ||
| 366 | ) | 364 | ) |
| 367 | .child( | 365 | .child( |
| 368 | Popover::new("share_settings") | 366 | Popover::new("share_settings") |
| @@ -418,8 +416,7 @@ impl Yumush { | |||
| 418 | 416 | ||
| 419 | fn share_top(&self, user_id: &str, kind: Kind) -> Quality { | 417 | fn share_top(&self, user_id: &str, kind: Kind) -> Quality { |
| 420 | self.chat | 418 | self.chat |
| 421 | - .selected_community_id | 419 | + .voice_community() |
| 422 | - .as_ref() | ||
| 423 | .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) | 420 | .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) |
| 424 | .map_or(SHARE_QUALITY, |share| share.source.top) | 421 | .map_or(SHARE_QUALITY, |share| share.source.top) |
| 425 | } | 422 | } |
crates/client/src/gui/sidebar.rsmodified+99 -109
| @@ -29,6 +29,7 @@ use super::{ | |||
| 29 | social::Relation, | 29 | social::Relation, |
| 30 | voice_stats, | 30 | voice_stats, |
| 31 | wave::wave, | 31 | wave::wave, |
| 32 | + widget::{bare_input, compact_frame, icon_button}, | ||
| 32 | }; | 33 | }; |
| 33 | 34 | ||
| 34 | const SIDEBAR_WIDTH: f32 = 232.; | 35 | const SIDEBAR_WIDTH: f32 = 232.; |
| @@ -341,7 +342,7 @@ impl Yumush { | |||
| 341 | }; | 342 | }; |
| 342 | 343 | ||
| 343 | icon_button( | 344 | icon_button( |
| 344 | - "sidebar_collapse".to_string(), | 345 | + "sidebar_collapse", |
| 345 | palette, | 346 | palette, |
| 346 | icon, | 347 | icon, |
| 347 | tip, | 348 | tip, |
| @@ -350,6 +351,7 @@ impl Yumush { | |||
| 350 | cx.notify(); | 351 | cx.notify(); |
| 351 | }), | 352 | }), |
| 352 | ) | 353 | ) |
| 354 | + .into_any_element() | ||
| 353 | } | 355 | } |
| 354 | 356 | ||
| 355 | fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement { | 357 | fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement { |
| @@ -602,15 +604,12 @@ impl Yumush { | |||
| 602 | }) | 604 | }) |
| 603 | }) | 605 | }) |
| 604 | .context_menu(move |menu, _, _| { | 606 | .context_menu(move |menu, _, _| { |
| 605 | - let remove = remove.clone(); | 607 | + menu_action( |
| 606 | - let remove_id = remove_id.clone(); | 608 | + menu, |
| 607 | - | 609 | + "Remove friend", |
| 608 | - menu.item( | 610 | + &remove, |
| 609 | - PopupMenuItem::new("Remove friend").on_click(move |_, window, cx| { | 611 | + remove_id.clone(), |
| 610 | - remove.update(cx, |yumush, cx| { | 612 | + |yumush, id, window, cx| yumush.remove_friend(id, window, cx), |
| 611 | - yumush.remove_friend(remove_id.clone(), window, cx) | ||
| 612 | - }) | ||
| 613 | - }), | ||
| 614 | ) | 613 | ) |
| 615 | }) | 614 | }) |
| 616 | .into_any_element() | 615 | .into_any_element() |
| @@ -623,15 +622,14 @@ impl Yumush { | |||
| 623 | let mut trailing = Vec::new(); | 622 | let mut trailing = Vec::new(); |
| 624 | 623 | ||
| 625 | if relation != Relation::Myself { | 624 | if relation != Relation::Myself { |
| 626 | - let user_id = user.id.clone(); | 625 | + trailing.push(row_button( |
| 627 | - trailing.push(icon_button( | 626 | + entity, |
| 628 | - format!("message_{}", user.id), | 627 | + "message", |
| 628 | + &user.id, | ||
| 629 | palette, | 629 | palette, |
| 630 | IconName::MessageSquare, | 630 | IconName::MessageSquare, |
| 631 | "Message", | 631 | "Message", |
| 632 | - entity_action(entity, move |yumush, window, cx| { | 632 | + |yumush, id, window, cx| yumush.open_direct(id, window, cx), |
| 633 | - yumush.open_direct(user_id.clone(), window, cx) | ||
| 634 | - }), | ||
| 635 | )); | 633 | )); |
| 636 | } | 634 | } |
| 637 | let action = match relation { | 635 | let action = match relation { |
| @@ -639,15 +637,14 @@ impl Yumush { | |||
| 639 | _ => None, | 637 | _ => None, |
| 640 | }; | 638 | }; |
| 641 | if let Some((label, icon)) = action { | 639 | if let Some((label, icon)) = action { |
| 642 | - let user_id = user.id.clone(); | 640 | + trailing.push(row_button( |
| 643 | - trailing.push(icon_button( | 641 | + entity, |
| 644 | - format!("friend_action_{}", user.id), | 642 | + "friend_action", |
| 643 | + &user.id, | ||
| 645 | palette, | 644 | palette, |
| 646 | icon, | 645 | icon, |
| 647 | label, | 646 | label, |
| 648 | - entity_action(entity, move |yumush, window, cx| { | 647 | + move |yumush, id, window, cx| yumush.friend_action(relation, id, window, cx), |
| 649 | - yumush.friend_action(relation, user_id.clone(), window, cx) | ||
| 650 | - }), | ||
| 651 | )); | 648 | )); |
| 652 | } | 649 | } |
| 653 | 650 | ||
| @@ -675,30 +672,27 @@ impl Yumush { | |||
| 675 | } | 672 | } |
| 676 | 673 | ||
| 677 | fn incoming_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement { | 674 | fn incoming_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement { |
| 678 | - let accept_id = user.id.clone(); | ||
| 679 | - let decline_id = user.id.clone(); | ||
| 680 | - | ||
| 681 | self.user_row( | 675 | self.user_row( |
| 682 | palette, | 676 | palette, |
| 683 | user, | 677 | user, |
| 684 | [ | 678 | [ |
| 685 | - icon_button( | 679 | + row_button( |
| 686 | - format!("accept_friend_{}", user.id), | 680 | + entity, |
| 681 | + "accept_friend", | ||
| 682 | + &user.id, | ||
| 687 | palette, | 683 | palette, |
| 688 | IconName::Check, | 684 | IconName::Check, |
| 689 | "Accept", | 685 | "Accept", |
| 690 | - entity_action(entity, move |yumush, window, cx| { | 686 | + |yumush, id, window, cx| yumush.accept_friend(id, window, cx), |
| 691 | - yumush.accept_friend(accept_id.clone(), window, cx) | ||
| 692 | - }), | ||
| 693 | ), | 687 | ), |
| 694 | - icon_button( | 688 | + row_button( |
| 695 | - format!("decline_friend_{}", user.id), | 689 | + entity, |
| 690 | + "decline_friend", | ||
| 691 | + &user.id, | ||
| 696 | palette, | 692 | palette, |
| 697 | IconName::X, | 693 | IconName::X, |
| 698 | "Decline", | 694 | "Decline", |
| 699 | - entity_action(entity, move |yumush, window, cx| { | 695 | + |yumush, id, window, cx| yumush.remove_friend(id, window, cx), |
| 700 | - yumush.remove_friend(decline_id.clone(), window, cx) | ||
| 701 | - }), | ||
| 702 | ), | 696 | ), |
| 703 | ], | 697 | ], |
| 704 | ) | 698 | ) |
| @@ -706,19 +700,17 @@ impl Yumush { | |||
| 706 | } | 700 | } |
| 707 | 701 | ||
| 708 | fn outgoing_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement { | 702 | fn outgoing_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement { |
| 709 | - let cancel_id = user.id.clone(); | ||
| 710 | - | ||
| 711 | self.user_row( | 703 | self.user_row( |
| 712 | palette, | 704 | palette, |
| 713 | user, | 705 | user, |
| 714 | - [icon_button( | 706 | + [row_button( |
| 715 | - format!("cancel_friend_{}", user.id), | 707 | + entity, |
| 708 | + "cancel_friend", | ||
| 709 | + &user.id, | ||
| 716 | palette, | 710 | palette, |
| 717 | IconName::X, | 711 | IconName::X, |
| 718 | "Cancel", | 712 | "Cancel", |
| 719 | - entity_action(entity, move |yumush, window, cx| { | 713 | + |yumush, id, window, cx| yumush.remove_friend(id, window, cx), |
| 720 | - yumush.remove_friend(cancel_id.clone(), window, cx) | ||
| 721 | - }), | ||
| 722 | )], | 714 | )], |
| 723 | ) | 715 | ) |
| 724 | .into_any_element() | 716 | .into_any_element() |
| @@ -731,8 +723,6 @@ impl Yumush { | |||
| 731 | palette: Palette, | 723 | palette: Palette, |
| 732 | ) -> AnyElement { | 724 | ) -> AnyElement { |
| 733 | let community = &invitation.community; | 725 | let community = &invitation.community; |
| 734 | - let accept_id = community.id.clone(); | ||
| 735 | - let decline_id = community.id.clone(); | ||
| 736 | let label = div().flex().flex_col().child(community.name.clone()).child( | 726 | let label = div().flex().flex_col().child(community.name.clone()).child( |
| 737 | div() | 727 | div() |
| 738 | .text_size(text(11.)) | 728 | .text_size(text(11.)) |
| @@ -746,23 +736,23 @@ impl Yumush { | |||
| 746 | community_icon(palette, community, px(16.), text(10.), &self.chat.avatars), | 736 | community_icon(palette, community, px(16.), text(10.), &self.chat.avatars), |
| 747 | label, | 737 | label, |
| 748 | [ | 738 | [ |
| 749 | - icon_button( | 739 | + row_button( |
| 750 | - format!("accept_invitation_{}", community.id), | 740 | + entity, |
| 741 | + "accept_invitation", | ||
| 742 | + &community.id, | ||
| 751 | palette, | 743 | palette, |
| 752 | IconName::Check, | 744 | IconName::Check, |
| 753 | "Accept", | 745 | "Accept", |
| 754 | - entity_action(entity, move |yumush, window, cx| { | 746 | + |yumush, id, window, cx| yumush.accept_invitation(id, window, cx), |
| 755 | - yumush.accept_invitation(accept_id.clone(), window, cx) | ||
| 756 | - }), | ||
| 757 | ), | 747 | ), |
| 758 | - icon_button( | 748 | + row_button( |
| 759 | - format!("decline_invitation_{}", community.id), | 749 | + entity, |
| 750 | + "decline_invitation", | ||
| 751 | + &community.id, | ||
| 760 | palette, | 752 | palette, |
| 761 | IconName::X, | 753 | IconName::X, |
| 762 | "Decline", | 754 | "Decline", |
| 763 | - entity_action(entity, move |yumush, window, cx| { | 755 | + |yumush, id, window, cx| yumush.decline_invitation(id, window, cx), |
| 764 | - yumush.decline_invitation(decline_id.clone(), window, cx) | ||
| 765 | - }), | ||
| 766 | ), | 756 | ), |
| 767 | ], | 757 | ], |
| 768 | ) | 758 | ) |
| @@ -940,37 +930,33 @@ fn community_menu( | |||
| 940 | let entity = entity.clone(); | 930 | let entity = entity.clone(); |
| 941 | 931 | ||
| 942 | move |menu, _, _| { | 932 | move |menu, _, _| { |
| 943 | - let invite = entity.clone(); | 933 | + let menu = menu_action( |
| 944 | - let invite_id = community_id.clone(); | 934 | + menu, |
| 945 | - let settings = entity.clone(); | 935 | + "Invite", |
| 946 | - let settings_id = community_id.clone(); | 936 | + &entity, |
| 947 | - let leave = entity.clone(); | 937 | + community_id.clone(), |
| 948 | - let leave_id = community_id.clone(); | 938 | + |yumush, id, window, cx| yumush.open_invite(id, window, cx), |
| 949 | - | 939 | + ); |
| 950 | - let menu = menu | 940 | + let menu = menu_action( |
| 951 | - .item(PopupMenuItem::new("Invite").on_click(move |_, window, cx| { | 941 | + menu, |
| 952 | - invite.update(cx, |yumush, cx| { | 942 | + "Settings", |
| 953 | - yumush.open_invite(invite_id.clone(), window, cx) | 943 | + &entity, |
| 954 | - }) | 944 | + community_id.clone(), |
| 955 | - })) | 945 | + |yumush, id, window, cx| yumush.open_community_settings(id, window, cx), |
| 956 | - .item( | 946 | + ); |
| 957 | - PopupMenuItem::new("Settings").on_click(move |_, window, cx| { | ||
| 958 | - settings.update(cx, |yumush, cx| { | ||
| 959 | - yumush.open_community_settings(settings_id.clone(), window, cx) | ||
| 960 | - }) | ||
| 961 | - }), | ||
| 962 | - ); | ||
| 963 | let menu = mute_item(menu, &entity, community_id.clone(), muted); | 947 | let menu = mute_item(menu, &entity, community_id.clone(), muted); |
| 964 | 948 | ||
| 965 | if !can_leave { | 949 | if !can_leave { |
| 966 | return menu; | 950 | return menu; |
| 967 | } | 951 | } |
| 968 | 952 | ||
| 969 | - menu.item(PopupMenuItem::new("Leave").on_click(move |_, window, cx| { | 953 | + menu_action( |
| 970 | - leave.update(cx, |yumush, cx| { | 954 | + menu, |
| 971 | - yumush.leave_community(leave_id.clone(), window, cx) | 955 | + "Leave", |
| 972 | - }) | 956 | + &entity, |
| 973 | - })) | 957 | + community_id.clone(), |
| 958 | + |yumush, id, window, cx| yumush.leave_community(id, window, cx), | ||
| 959 | + ) | ||
| 974 | } | 960 | } |
| 975 | } | 961 | } |
| 976 | 962 | ||
| @@ -996,6 +982,7 @@ fn new_community_menu( | |||
| 996 | window, | 982 | window, |
| 997 | cx, | 983 | cx, |
| 998 | |this, name, window, cx| { | 984 | |this, name, window, cx| { |
| 985 | + let name = name.trim().to_string(); | ||
| 999 | if validate_community_name(&name).is_ok() { | 986 | if validate_community_name(&name).is_ok() { |
| 1000 | create_community(this, name, window, cx); | 987 | create_community(this, name, window, cx); |
| 1001 | } | 988 | } |
| @@ -1008,25 +995,11 @@ fn new_community_menu( | |||
| 1008 | } | 995 | } |
| 1009 | 996 | ||
| 1010 | pub(super) fn input_box(input: &Entity<InputState>, palette: Palette) -> Div { | 997 | pub(super) fn input_box(input: &Entity<InputState>, palette: Palette) -> Div { |
| 1011 | - div() | 998 | + compact_frame(palette) |
| 1012 | - .h(px(30.)) | ||
| 1013 | - .px(px(10.)) | ||
| 1014 | - .flex() | ||
| 1015 | - .items_center() | ||
| 1016 | .gap(px(8.)) | 999 | .gap(px(8.)) |
| 1017 | - .rounded(px(8.)) | ||
| 1018 | - .border_1() | ||
| 1019 | - .border_color(palette.border) | ||
| 1020 | - .bg(palette.field) | ||
| 1021 | .text_color(palette.muted) | 1000 | .text_color(palette.muted) |
| 1022 | .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))) | 1001 | .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))) |
| 1023 | - .child( | 1002 | + .child(bare_input(palette, Input::new(input))) |
| 1024 | - Input::new(input) | ||
| 1025 | - .appearance(false) | ||
| 1026 | - .text_color(palette.text) | ||
| 1027 | - .flex_1() | ||
| 1028 | - .min_w_0(), | ||
| 1029 | - ) | ||
| 1030 | } | 1003 | } |
| 1031 | 1004 | ||
| 1032 | fn group(title: &'static str, palette: Palette, rows: Vec<AnyElement>) -> Option<Div> { | 1005 | fn group(title: &'static str, palette: Palette, rows: Vec<AnyElement>) -> Option<Div> { |
| @@ -1067,22 +1040,39 @@ fn entry( | |||
| 1067 | .children(trailing) | 1040 | .children(trailing) |
| 1068 | } | 1041 | } |
| 1069 | 1042 | ||
| 1070 | -pub(super) fn icon_button( | 1043 | +fn row_button( |
| 1071 | - id: String, | 1044 | + entity: &Entity<Yumush>, |
| 1045 | + key: &str, | ||
| 1046 | + id: &str, | ||
| 1072 | palette: Palette, | 1047 | palette: Palette, |
| 1073 | icon: IconName, | 1048 | icon: IconName, |
| 1074 | tip: &'static str, | 1049 | tip: &'static str, |
| 1075 | - on_click: impl Fn(&mut Window, &mut App) + 'static, | 1050 | + run: impl Fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>) + 'static, |
| 1076 | ) -> AnyElement { | 1051 | ) -> AnyElement { |
| 1077 | - clickable(id, palette, on_click) | 1052 | + let id = id.to_string(); |
| 1078 | - .tip(tip) | 1053 | + |
| 1079 | - .size(px(26.)) | 1054 | + icon_button( |
| 1080 | - .flex_shrink_0() | 1055 | + format!("{key}_{id}"), |
| 1081 | - .flex() | 1056 | + palette, |
| 1082 | - .items_center() | 1057 | + icon, |
| 1083 | - .justify_center() | 1058 | + tip, |
| 1084 | - .rounded(px(6.)) | 1059 | + entity_action(entity, move |yumush, window, cx| { |
| 1085 | - .text_color(palette.muted) | 1060 | + run(yumush, id.clone(), window, cx) |
| 1086 | - .child(Icon::new(icon).w(px(14.)).h(px(14.))) | 1061 | + }), |
| 1087 | - .into_any_element() | 1062 | + ) |
| 1063 | + .into_any_element() | ||
| 1064 | +} | ||
| 1065 | + | ||
| 1066 | +fn menu_action( | ||
| 1067 | + menu: PopupMenu, | ||
| 1068 | + label: &'static str, | ||
| 1069 | + entity: &Entity<Yumush>, | ||
| 1070 | + id: String, | ||
| 1071 | + run: impl Fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>) + 'static, | ||
| 1072 | +) -> PopupMenu { | ||
| 1073 | + let entity = entity.clone(); | ||
| 1074 | + | ||
| 1075 | + menu.item(PopupMenuItem::new(label).on_click(move |_, window, cx| { | ||
| 1076 | + entity.update(cx, |yumush, cx| run(yumush, id.clone(), window, cx)) | ||
| 1077 | + })) | ||
| 1088 | } | 1078 | } |
crates/client/src/gui/snippet.rsmodified+7 -8
| @@ -6,7 +6,10 @@ use gpui_kit::{ | |||
| 6 | relative, | 6 | relative, |
| 7 | }; | 7 | }; |
| 8 | 8 | ||
| 9 | -use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link}; | 9 | +use super::{ |
| 10 | + Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link, | ||
| 11 | + widget::panel, | ||
| 12 | +}; | ||
| 10 | 13 | ||
| 11 | pub fn snippet_card( | 14 | pub fn snippet_card( |
| 12 | message: &Message, | 15 | message: &Message, |
| @@ -21,15 +24,11 @@ pub fn snippet_card( | |||
| 21 | }; | 24 | }; |
| 22 | 25 | ||
| 23 | Some( | 26 | Some( |
| 24 | - div() | 27 | + panel(palette) |
| 25 | .flex() | 28 | .flex() |
| 26 | .flex_col() | 29 | .flex_col() |
| 27 | .gap(px(10.)) | 30 | .gap(px(10.)) |
| 28 | .p(px(10.)) | 31 | .p(px(10.)) |
| 29 | - .rounded(px(8.)) | ||
| 30 | - .border_1() | ||
| 31 | - .border_color(palette.border) | ||
| 32 | - .bg(palette.panel) | ||
| 33 | .child( | 32 | .child( |
| 34 | div() | 33 | div() |
| 35 | .text_size(text(12.)) | 34 | .text_size(text(12.)) |
| @@ -51,13 +50,13 @@ fn snippet_row( | |||
| 51 | entity: &Entity<Yumush>, | 50 | entity: &Entity<Yumush>, |
| 52 | palette: Palette, | 51 | palette: Palette, |
| 53 | ) -> impl IntoElement { | 52 | ) -> impl IntoElement { |
| 54 | - let user = User { | 53 | + let user = chat.author(&item.user_id).cloned().unwrap_or_else(|| User { |
| 55 | id: item.user_id.clone(), | 54 | id: item.user_id.clone(), |
| 56 | username: item.username.clone(), | 55 | username: item.username.clone(), |
| 57 | role: Role::User, | 56 | role: Role::User, |
| 58 | status: String::new(), | 57 | status: String::new(), |
| 59 | avatar_id: item.avatar_id.clone(), | 58 | avatar_id: item.avatar_id.clone(), |
| 60 | - }; | 59 | + }); |
| 61 | 60 | ||
| 62 | div() | 61 | div() |
| 63 | .flex() | 62 | .flex() |
crates/client/src/gui/social.rsmodified+14 -35
| @@ -1,12 +1,11 @@ | |||
| 1 | -use super::text; | ||
| 2 | use std::{fmt::Display, future::Future}; | 1 | use std::{fmt::Display, future::Future}; |
| 3 | 2 | ||
| 4 | use common::{ | 3 | use common::{ |
| 5 | - model::{Community, CommunityKind, Rank}, | 4 | + model::{Community, CommunityKind, Rank, User}, |
| 6 | validate::validate_username, | 5 | validate::validate_username, |
| 7 | }; | 6 | }; |
| 8 | use gpui_kit::{ | 7 | use gpui_kit::{ |
| 9 | - Context, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, | 8 | + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, |
| 10 | assets::IconName, | 9 | assets::IconName, |
| 11 | component::{ | 10 | component::{ |
| 12 | WindowExt, | 11 | WindowExt, |
| @@ -15,14 +14,17 @@ use gpui_kit::{ | |||
| 15 | div, px, | 14 | div, px, |
| 16 | }; | 15 | }; |
| 17 | 16 | ||
| 18 | -use super::{Palette, Yumush, avatar, new_input, notify_error, primary_button}; | 17 | +use super::{ |
| 18 | + Palette, Yumush, avatar, new_input, notify_error, primary_button, text, | ||
| 19 | + widget::{search_text, spawn_done}, | ||
| 20 | +}; | ||
| 19 | 21 | ||
| 20 | #[derive(Debug, Clone, Default)] | 22 | #[derive(Debug, Clone, Default)] |
| 21 | pub enum InviteLookup { | 23 | pub enum InviteLookup { |
| 22 | #[default] | 24 | #[default] |
| 23 | Idle, | 25 | Idle, |
| 24 | - Found(common::model::User), | 26 | + Found(User), |
| 25 | - Member(common::model::User), | 27 | + Member(User), |
| 26 | Missing, | 28 | Missing, |
| 27 | } | 29 | } |
| 28 | 30 | ||
| @@ -47,19 +49,6 @@ impl Relation { | |||
| 47 | } | 49 | } |
| 48 | } | 50 | } |
| 49 | 51 | ||
| 50 | -fn spawn_done<E: Display + 'static>( | ||
| 51 | - window: &mut Window, | ||
| 52 | - cx: &mut Context<Yumush>, | ||
| 53 | - call: impl Future<Output = Result<(), E>> + 'static, | ||
| 54 | -) { | ||
| 55 | - cx.spawn_in(window, async move |this, cx| { | ||
| 56 | - if let Err(error) = call.await { | ||
| 57 | - notify_error(&this, cx, error); | ||
| 58 | - } | ||
| 59 | - }) | ||
| 60 | - .detach(); | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | fn spawn_community<E: Display + 'static>( | 52 | fn spawn_community<E: Display + 'static>( |
| 64 | window: &mut Window, | 53 | window: &mut Window, |
| 65 | cx: &mut Context<Yumush>, | 54 | cx: &mut Context<Yumush>, |
| @@ -155,20 +144,10 @@ impl Yumush { | |||
| 155 | .detach(); | 144 | .detach(); |
| 156 | } | 145 | } |
| 157 | 146 | ||
| 158 | - pub(super) fn search_query(&self, cx: &Context<Self>) -> String { | ||
| 159 | - self.chat | ||
| 160 | - .search_input | ||
| 161 | - .read(cx) | ||
| 162 | - .text() | ||
| 163 | - .to_string() | ||
| 164 | - .trim() | ||
| 165 | - .to_lowercase() | ||
| 166 | - } | ||
| 167 | - | ||
| 168 | pub(super) fn search_user(&mut self, window: &mut Window, cx: &mut Context<Self>) { | 147 | pub(super) fn search_user(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 169 | self.chat.found = None; | 148 | self.chat.found = None; |
| 170 | cx.notify(); | 149 | cx.notify(); |
| 171 | - let username = self.search_query(cx); | 150 | + let username = search_text(&self.chat.search_input, cx); |
| 172 | if validate_username(&username).is_err() { | 151 | if validate_username(&username).is_err() { |
| 173 | return; | 152 | return; |
| 174 | } | 153 | } |
| @@ -177,7 +156,7 @@ impl Yumush { | |||
| 177 | cx.spawn_in(window, async move |this, cx| { | 156 | cx.spawn_in(window, async move |this, cx| { |
| 178 | let found = network.find_user(&username).await.ok(); | 157 | let found = network.find_user(&username).await.ok(); |
| 179 | let _ = this.update(cx, |yumush, cx| { | 158 | let _ = this.update(cx, |yumush, cx| { |
| 180 | - if yumush.search_query(cx) != username { | 159 | + if search_text(&yumush.chat.search_input, cx) != username { |
| 181 | return; | 160 | return; |
| 182 | } | 161 | } |
| 183 | if let Some(user) = &found { | 162 | if let Some(user) = &found { |
| @@ -349,7 +328,7 @@ impl Yumush { | |||
| 349 | window: &mut Window, | 328 | window: &mut Window, |
| 350 | cx: &mut Context<Self>, | 329 | cx: &mut Context<Self>, |
| 351 | ) { | 330 | ) { |
| 352 | - let username = input.read(cx).text().to_string().trim().to_string(); | 331 | + let username = search_text(input, cx); |
| 353 | self.chat.invite = InviteLookup::Idle; | 332 | self.chat.invite = InviteLookup::Idle; |
| 354 | window.refresh(); | 333 | window.refresh(); |
| 355 | if validate_username(&username).is_err() { | 334 | if validate_username(&username).is_err() { |
| @@ -371,7 +350,7 @@ impl Yumush { | |||
| 371 | Err(_) => InviteLookup::Missing, | 350 | Err(_) => InviteLookup::Missing, |
| 372 | }; | 351 | }; |
| 373 | let _ = this.update_in(cx, |yumush, window, cx| { | 352 | let _ = this.update_in(cx, |yumush, window, cx| { |
| 374 | - if input.read(cx).text().to_string().trim() != username { | 353 | + if search_text(&input, cx) != username { |
| 375 | return; | 354 | return; |
| 376 | } | 355 | } |
| 377 | if let InviteLookup::Found(user) | InviteLookup::Member(user) = &lookup { | 356 | if let InviteLookup::Found(user) | InviteLookup::Member(user) = &lookup { |
| @@ -409,7 +388,7 @@ fn invite_result( | |||
| 409 | entity: &Entity<Yumush>, | 388 | entity: &Entity<Yumush>, |
| 410 | yumush: &Yumush, | 389 | yumush: &Yumush, |
| 411 | palette: Palette, | 390 | palette: Palette, |
| 412 | -) -> Option<gpui_kit::AnyElement> { | 391 | +) -> Option<AnyElement> { |
| 413 | match lookup { | 392 | match lookup { |
| 414 | InviteLookup::Idle => None, | 393 | InviteLookup::Idle => None, |
| 415 | InviteLookup::Missing => Some( | 394 | InviteLookup::Missing => Some( |
| @@ -454,7 +433,7 @@ fn invite_result( | |||
| 454 | } | 433 | } |
| 455 | } | 434 | } |
| 456 | 435 | ||
| 457 | -fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gpui_kit::Div { | 436 | +fn user_row(user: &User, yumush: &Yumush, palette: Palette) -> Div { |
| 458 | div() | 437 | div() |
| 459 | .flex() | 438 | .flex() |
| 460 | .items_center() | 439 | .items_center() |
crates/client/src/gui/voice_note.rsmodified+21 -13
| @@ -20,6 +20,7 @@ use super::{ | |||
| 20 | clickable, | 20 | clickable, |
| 21 | media_view::{time_text, upload_file}, | 21 | media_view::{time_text, upload_file}, |
| 22 | notify_error, primary_button, text, | 22 | notify_error, primary_button, text, |
| 23 | + widget::ok_or_notify, | ||
| 23 | }; | 24 | }; |
| 24 | use crate::{ | 25 | use crate::{ |
| 25 | media::voice_note::{self, BARS}, | 26 | media::voice_note::{self, BARS}, |
| @@ -31,6 +32,8 @@ use crate::{ | |||
| 31 | 32 | ||
| 32 | const TICK: Duration = Duration::from_millis(100); | 33 | const TICK: Duration = Duration::from_millis(100); |
| 33 | const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize; | 34 | const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize; |
| 35 | +const MAX_SECONDS: usize = 300; | ||
| 36 | +const MAX_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * MAX_SECONDS; | ||
| 34 | const SLOT_WIDTH: f32 = 5.; | 37 | const SLOT_WIDTH: f32 = 5.; |
| 35 | const BAR_WIDTH: f32 = 3.; | 38 | const BAR_WIDTH: f32 = 3.; |
| 36 | const BAR_MIN: f32 = 2.; | 39 | const BAR_MIN: f32 = 2.; |
| @@ -51,7 +54,9 @@ pub enum VoiceNote { | |||
| 51 | } | 54 | } |
| 52 | 55 | ||
| 53 | fn drain(consumer: &mut Consumer<f32>, samples: &mut Vec<f32>) { | 56 | fn drain(consumer: &mut Consumer<f32>, samples: &mut Vec<f32>) { |
| 54 | - while let Ok(sample) = consumer.pop() { | 57 | + while samples.len() < MAX_SAMPLES |
| 58 | + && let Ok(sample) = consumer.pop() | ||
| 59 | + { | ||
| 55 | samples.push(sample); | 60 | samples.push(sample); |
| 56 | } | 61 | } |
| 57 | } | 62 | } |
| @@ -148,7 +153,7 @@ pub fn recording_row( | |||
| 148 | .text_size(text(13.)) | 153 | .text_size(text(13.)) |
| 149 | .text_color(palette.text) | 154 | .text_color(palette.text) |
| 150 | .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.))) | 155 | .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.))) |
| 151 | - .child(time_text(started.elapsed())) | 156 | + .child(time_text(started.elapsed().min(Duration::from_secs(MAX_SECONDS as u64)))) |
| 152 | .child(bars(levels, 1., palette, |_, _, _| {})), | 157 | .child(bars(levels, 1., palette, |_, _, _| {})), |
| 153 | ) | 158 | ) |
| 154 | .child( | 159 | .child( |
| @@ -265,17 +270,20 @@ impl Yumush { | |||
| 265 | else { | 270 | else { |
| 266 | return; | 271 | return; |
| 267 | }; | 272 | }; |
| 268 | - let attachment = | 273 | + let uploaded = |
| 269 | - match upload_file(&this, &network, &community_id, path, maximum, cx).await { | 274 | + upload_file(&this, &network, &community_id, path.clone(), maximum, cx).await; |
| 270 | - Ok(attachment) => attachment, | 275 | + let _ = std::fs::remove_file(&path); |
| 271 | - Err(error) => return notify_error(&this, cx, error), | 276 | + let attachment = match uploaded { |
| 272 | - }; | 277 | + Ok(attachment) => attachment, |
| 273 | - if let Err(error) = network | 278 | + Err(error) => return notify_error(&this, cx, error), |
| 274 | - .create_message(&community_id, "", vec![attachment.id], None) | 279 | + }; |
| 275 | - .await | 280 | + ok_or_notify( |
| 276 | - { | 281 | + network |
| 277 | - notify_error(&this, cx, error); | 282 | + .create_message(&community_id, "", vec![attachment.id], None) |
| 278 | - } | 283 | + .await, |
| 284 | + &this, | ||
| 285 | + cx, | ||
| 286 | + ); | ||
| 279 | }) | 287 | }) |
| 280 | .detach(); | 288 | .detach(); |
| 281 | } | 289 | } |
crates/client/src/gui/widget.rsadded+116 -0
| @@ -0,0 +1,116 @@ | |||
| 1 | +use std::{fmt::Display, future::Future}; | ||
| 2 | + | ||
| 3 | +use gpui_kit::{ | ||
| 4 | + App, AsyncWindowContext, Context, Div, ElementId, Entity, ParentElement, Stateful, Styled, | ||
| 5 | + WeakEntity, Window, | ||
| 6 | + assets::IconName, | ||
| 7 | + component::{Icon, input::Input, input::InputState}, | ||
| 8 | + div, px, | ||
| 9 | +}; | ||
| 10 | + | ||
| 11 | +use super::{Palette, Tooltip as _, Yumush, clickable, notify_error}; | ||
| 12 | + | ||
| 13 | +pub(super) fn icon_button( | ||
| 14 | + id: impl Into<ElementId>, | ||
| 15 | + palette: Palette, | ||
| 16 | + icon: IconName, | ||
| 17 | + tip: &'static str, | ||
| 18 | + on_click: impl Fn(&mut Window, &mut App) + 'static, | ||
| 19 | +) -> Stateful<Div> { | ||
| 20 | + clickable(id, palette, on_click) | ||
| 21 | + .tip(tip) | ||
| 22 | + .size(px(26.)) | ||
| 23 | + .flex_shrink_0() | ||
| 24 | + .flex() | ||
| 25 | + .items_center() | ||
| 26 | + .justify_center() | ||
| 27 | + .rounded(px(6.)) | ||
| 28 | + .text_color(palette.muted) | ||
| 29 | + .child(Icon::new(icon).w(px(14.)).h(px(14.))) | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +pub(super) fn panel(palette: Palette) -> Div { | ||
| 33 | + div() | ||
| 34 | + .rounded(px(8.)) | ||
| 35 | + .border_1() | ||
| 36 | + .border_color(palette.border) | ||
| 37 | + .bg(palette.panel) | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div { | ||
| 41 | + frame(palette, Input::new(input)) | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +pub(super) fn compact_frame(palette: Palette) -> Div { | ||
| 45 | + div() | ||
| 46 | + .h(px(30.)) | ||
| 47 | + .px(px(10.)) | ||
| 48 | + .flex() | ||
| 49 | + .items_center() | ||
| 50 | + .rounded(px(8.)) | ||
| 51 | + .border_1() | ||
| 52 | + .border_color(palette.border) | ||
| 53 | + .bg(palette.field) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +pub(super) fn compact_field(palette: Palette, input: &Entity<InputState>) -> Div { | ||
| 57 | + compact_frame(palette).child(bare_input(palette, Input::new(input))) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +pub(super) fn frame(palette: Palette, input: Input) -> Div { | ||
| 61 | + div() | ||
| 62 | + .h(px(32.)) | ||
| 63 | + .flex() | ||
| 64 | + .items_center() | ||
| 65 | + .rounded(px(8.)) | ||
| 66 | + .border_1() | ||
| 67 | + .border_color(palette.border) | ||
| 68 | + .bg(palette.field) | ||
| 69 | + .child(bare_input(palette, input)) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +pub(super) fn bare_input(palette: Palette, input: Input) -> Input { | ||
| 73 | + input | ||
| 74 | + .appearance(false) | ||
| 75 | + .text_color(palette.text) | ||
| 76 | + .flex_1() | ||
| 77 | + .min_w_0() | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +pub(super) fn search_text(input: &Entity<InputState>, cx: &App) -> String { | ||
| 81 | + input.read(cx).text().to_string().trim().to_lowercase() | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +pub(super) fn ok_or_notify<T: 'static, V, E: Display>( | ||
| 85 | + result: Result<V, E>, | ||
| 86 | + this: &WeakEntity<T>, | ||
| 87 | + cx: &mut AsyncWindowContext, | ||
| 88 | +) -> Option<V> { | ||
| 89 | + result.map_err(|error| notify_error(this, cx, error)).ok() | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +pub(super) fn spawn_done<T, E: Display + 'static>( | ||
| 93 | + window: &mut Window, | ||
| 94 | + cx: &mut Context<Yumush>, | ||
| 95 | + call: impl Future<Output = Result<T, E>> + 'static, | ||
| 96 | +) { | ||
| 97 | + cx.spawn_in(window, async move |this, cx| { | ||
| 98 | + if let Err(error) = call.await { | ||
| 99 | + notify_error(&this, cx, error); | ||
| 100 | + } | ||
| 101 | + }) | ||
| 102 | + .detach(); | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +pub(super) fn spawn_warn<T, E: Display + 'static>( | ||
| 106 | + cx: &mut Context<Yumush>, | ||
| 107 | + label: &'static str, | ||
| 108 | + call: impl Future<Output = Result<T, E>> + 'static, | ||
| 109 | +) { | ||
| 110 | + cx.spawn(async move |_, _| { | ||
| 111 | + if let Err(error) = call.await { | ||
| 112 | + tracing::warn!("{label} failed: {error}"); | ||
| 113 | + } | ||
| 114 | + }) | ||
| 115 | + .detach(); | ||
| 116 | +} | ||
crates/client/src/lib.rsmodified+27 -2
| @@ -1,6 +1,7 @@ | |||
| 1 | -use std::path::PathBuf; | 1 | +use std::{fs, io::Write, path::PathBuf}; |
| 2 | 2 | ||
| 3 | use common::config::Config; | 3 | use common::config::Config; |
| 4 | +use tracing::warn; | ||
| 4 | 5 | ||
| 5 | pub mod accounts; | 6 | pub mod accounts; |
| 6 | pub mod avatar; | 7 | pub mod avatar; |
| @@ -16,13 +17,37 @@ pub mod voice; | |||
| 16 | 17 | ||
| 17 | pub const NAME: &str = "Yumush"; | 18 | pub const NAME: &str = "Yumush"; |
| 18 | 19 | ||
| 19 | -pub fn config_file(name: &str) -> Option<PathBuf> { | 20 | +fn config_file(name: &str) -> Option<PathBuf> { |
| 20 | std::env::var_os("YUMUSH_CONFIG_DIR") | 21 | std::env::var_os("YUMUSH_CONFIG_DIR") |
| 21 | .map(PathBuf::from) | 22 | .map(PathBuf::from) |
| 22 | .or_else(|| dirs::config_dir().map(|dir| dir.join("yumush"))) | 23 | .or_else(|| dirs::config_dir().map(|dir| dir.join("yumush"))) |
| 23 | .map(|dir| dir.join(name)) | 24 | .map(|dir| dir.join(name)) |
| 24 | } | 25 | } |
| 25 | 26 | ||
| 27 | +pub fn read_config(name: &str) -> Option<String> { | ||
| 28 | + fs::read_to_string(config_file(name)?).ok() | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +pub fn write_config(name: &str, content: &str) { | ||
| 32 | + let Some(path) = config_file(name) else { | ||
| 33 | + return; | ||
| 34 | + }; | ||
| 35 | + let result = path | ||
| 36 | + .parent() | ||
| 37 | + .map_or(Ok(()), fs::create_dir_all) | ||
| 38 | + .and_then(|()| { | ||
| 39 | + let mut options = fs::OpenOptions::new(); | ||
| 40 | + options.write(true).create(true).truncate(true); | ||
| 41 | + #[cfg(unix)] | ||
| 42 | + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); | ||
| 43 | + options.open(&path)?.write_all(content.as_bytes()) | ||
| 44 | + }); | ||
| 45 | + | ||
| 46 | + if let Err(error) = result { | ||
| 47 | + warn!("save {name} failed: {error}"); | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 26 | const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( | 51 | const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( |
| 27 | env!("CARGO_MANIFEST_DIR"), | 52 | env!("CARGO_MANIFEST_DIR"), |
| 28 | "/../../configs/client_config.toml" | 53 | "/../../configs/client_config.toml" |
crates/client/src/main.rsmodified+5 -1
| @@ -1,3 +1,5 @@ | |||
| 1 | +#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] | ||
| 2 | + | ||
| 1 | use client::{ | 3 | use client::{ |
| 2 | ClientConfig, NAME, | 4 | ClientConfig, NAME, |
| 3 | gui::{self, Yumush}, | 5 | gui::{self, Yumush}, |
| @@ -101,7 +103,9 @@ fn open_window( | |||
| 101 | view.update(cx, |yumush, cx| yumush.attach_window(window, cx)); | 103 | view.update(cx, |yumush, cx| yumush.attach_window(window, cx)); |
| 102 | let closing = view.clone(); | 104 | let closing = view.clone(); |
| 103 | window.on_window_should_close(cx, move |_, cx| { | 105 | window.on_window_should_close(cx, move |_, cx| { |
| 104 | - if !closing.update(cx, |yumush, _| yumush.detach_window()) { | 106 | + let detached = |
| 107 | + tray::AVAILABLE && closing.update(cx, |yumush, _| yumush.detach_window()); | ||
| 108 | + if !detached { | ||
| 105 | cx.quit(); | 109 | cx.quit(); |
| 106 | } | 110 | } |
| 107 | true | 111 | true |
crates/client/src/media/decode.rsmodified+60 -52
| @@ -248,25 +248,8 @@ impl VideoDecoder { | |||
| 248 | else { | 248 | else { |
| 249 | return Vec::new(); | 249 | return Vec::new(); |
| 250 | }; | 250 | }; |
| 251 | - match decoder.decode(&packet.data) { | 251 | + skipped(decoder.decode(&packet.data)) |
| 252 | - Ok(Some(picture)) => vec![( | 252 | + .map_or_else(Vec::new, |picture| vec![(pts, vp8_picture(picture))]) |
| 253 | - pts, | ||
| 254 | - Picture::Planes(Planes { | ||
| 255 | - y: picture.y, | ||
| 256 | - y_stride: picture.stride, | ||
| 257 | - u: picture.u, | ||
| 258 | - v: picture.v, | ||
| 259 | - uv_stride: picture.uv_stride, | ||
| 260 | - width: u32::from(picture.width), | ||
| 261 | - height: u32::from(picture.height), | ||
| 262 | - }), | ||
| 263 | - )], | ||
| 264 | - Ok(None) => Vec::new(), | ||
| 265 | - Err(error) => { | ||
| 266 | - warn!("video packet skipped: {error}"); | ||
| 267 | - Vec::new() | ||
| 268 | - } | ||
| 269 | - } | ||
| 270 | } | 253 | } |
| 271 | VideoDecoder::H265(decoder) => { | 254 | VideoDecoder::H265(decoder) => { |
| 272 | if let Err(error) = decoder.decode_annex_b(&packet.data) { | 255 | if let Err(error) = decoder.decode_annex_b(&packet.data) { |
| @@ -276,14 +259,8 @@ impl VideoDecoder { | |||
| 276 | decoder.end_picture(); | 259 | decoder.end_picture(); |
| 277 | drain_h265(decoder, seconds) | 260 | drain_h265(decoder, seconds) |
| 278 | } | 261 | } |
| 279 | - VideoDecoder::Vp9(decoder) => match decoder.decode(&packet.data) { | 262 | + VideoDecoder::Vp9(decoder) => skipped(decoder.decode(&packet.data)) |
| 280 | - Ok(Some(picture)) => vec![(seconds, vp9_picture(picture))], | 263 | + .map_or_else(Vec::new, |picture| vec![(seconds, vp9_picture(picture))]), |
| 281 | - Ok(None) => Vec::new(), | ||
| 282 | - Err(error) => { | ||
| 283 | - warn!("video packet skipped: {error}"); | ||
| 284 | - Vec::new() | ||
| 285 | - } | ||
| 286 | - }, | ||
| 287 | VideoDecoder::Av1(decoder) => match decoder.decode_temporal_unit(&packet.data) { | 264 | VideoDecoder::Av1(decoder) => match decoder.decode_temporal_unit(&packet.data) { |
| 288 | Ok(pictures) => pictures | 265 | Ok(pictures) => pictures |
| 289 | .into_iter() | 266 | .into_iter() |
| @@ -426,6 +403,25 @@ fn h265_picture(picture: &ec_h265::decode::DecodedPicture) -> Picture { | |||
| 426 | }) | 403 | }) |
| 427 | } | 404 | } |
| 428 | 405 | ||
| 406 | +fn skipped<T: Default, E: std::fmt::Display>(result: Result<T, E>) -> T { | ||
| 407 | + result.unwrap_or_else(|error| { | ||
| 408 | + warn!("video packet skipped: {error}"); | ||
| 409 | + T::default() | ||
| 410 | + }) | ||
| 411 | +} | ||
| 412 | + | ||
| 413 | +fn vp8_picture(picture: ec_vp8::decode::Picture) -> Picture { | ||
| 414 | + Picture::Planes(Planes { | ||
| 415 | + y: picture.y, | ||
| 416 | + y_stride: picture.stride, | ||
| 417 | + u: picture.u, | ||
| 418 | + v: picture.v, | ||
| 419 | + uv_stride: picture.uv_stride, | ||
| 420 | + width: u32::from(picture.width), | ||
| 421 | + height: u32::from(picture.height), | ||
| 422 | + }) | ||
| 423 | +} | ||
| 424 | + | ||
| 429 | fn vp9_picture(picture: ec_vp9::decode::Picture) -> Picture { | 425 | fn vp9_picture(picture: ec_vp9::decode::Picture) -> Picture { |
| 430 | let shift = u32::from(picture.bit_depth.saturating_sub(8)); | 426 | let shift = u32::from(picture.bit_depth.saturating_sub(8)); |
| 431 | Picture::Planes(Planes { | 427 | Picture::Planes(Planes { |
| @@ -467,11 +463,9 @@ pub struct Worker { | |||
| 467 | reader: Reader, | 463 | reader: Reader, |
| 468 | playback: Playback, | 464 | playback: Playback, |
| 469 | producer: Option<Producer<f32>>, | 465 | producer: Option<Producer<f32>>, |
| 470 | - video_index: Option<u32>, | 466 | + video: Option<(u32, VideoDecoder)>, |
| 471 | - video: Option<VideoDecoder>, | ||
| 472 | backlog: VecDeque<Queued>, | 467 | backlog: VecDeque<Queued>, |
| 473 | - audio_index: Option<u32>, | 468 | + audio: Option<(u32, AudioDecoder)>, |
| 474 | - audio: Option<AudioDecoder>, | ||
| 475 | pending: VecDeque<Stereo>, | 469 | pending: VecDeque<Stereo>, |
| 476 | resampler: Resampler, | 470 | resampler: Resampler, |
| 477 | align: Option<f64>, | 471 | align: Option<f64>, |
| @@ -495,11 +489,9 @@ impl Worker { | |||
| 495 | reader, | 489 | reader, |
| 496 | playback, | 490 | playback, |
| 497 | producer, | 491 | producer, |
| 498 | - video_index: tracks.video.as_ref().map(|(index, _, _)| *index), | 492 | + video: tracks.video.map(|(index, _, decoder)| (index, decoder)), |
| 499 | - video: tracks.video.map(|(_, _, decoder)| decoder), | ||
| 500 | backlog: VecDeque::new(), | 493 | backlog: VecDeque::new(), |
| 501 | - audio_index: tracks.audio.as_ref().map(|(index, _)| *index), | 494 | + audio: tracks.audio, |
| 502 | - audio: tracks.audio.map(|(_, decoder)| decoder), | ||
| 503 | pending: VecDeque::new(), | 495 | pending: VecDeque::new(), |
| 504 | resampler: Resampler::default(), | 496 | resampler: Resampler::default(), |
| 505 | align: Some(0.0), | 497 | align: Some(0.0), |
| @@ -534,14 +526,13 @@ impl Worker { | |||
| 534 | 526 | ||
| 535 | fn play_step(&mut self) { | 527 | fn play_step(&mut self) { |
| 536 | self.feed(); | 528 | self.feed(); |
| 537 | - self.decode_backlog(); | 529 | + let decoded = self.decode_backlog(); |
| 538 | if self.eof { | 530 | if self.eof { |
| 539 | self.finish(); | 531 | self.finish(); |
| 540 | } | 532 | } |
| 541 | - if self.eof || self.buffered() { | 533 | + let read = !self.eof && !self.buffered() && self.fill(); |
| 534 | + if !decoded && !read { | ||
| 542 | wait(); | 535 | wait(); |
| 543 | - } else { | ||
| 544 | - self.fill(); | ||
| 545 | } | 536 | } |
| 546 | } | 537 | } |
| 547 | 538 | ||
| @@ -549,14 +540,17 @@ impl Worker { | |||
| 549 | self.pending.len() >= RING_FRAMES | 540 | self.pending.len() >= RING_FRAMES |
| 550 | } | 541 | } |
| 551 | 542 | ||
| 552 | - fn fill(&mut self) { | 543 | + fn fill(&mut self) -> bool { |
| 544 | + let mut read = false; | ||
| 553 | while !self.eof | 545 | while !self.eof |
| 554 | && !self.buffered() | 546 | && !self.buffered() |
| 555 | && self.backlog.len() < BACKLOG_LIMIT | 547 | && self.backlog.len() < BACKLOG_LIMIT |
| 556 | && (self.producer.is_some() || self.backlog.is_empty()) | 548 | && (self.producer.is_some() || self.backlog.is_empty()) |
| 557 | { | 549 | { |
| 558 | self.step(); | 550 | self.step(); |
| 551 | + read = true; | ||
| 559 | } | 552 | } |
| 553 | + read | ||
| 560 | } | 554 | } |
| 561 | 555 | ||
| 562 | fn primed(&self) -> bool { | 556 | fn primed(&self) -> bool { |
| @@ -628,24 +622,32 @@ impl Worker { | |||
| 628 | } | 622 | } |
| 629 | 623 | ||
| 630 | fn packet(&mut self, packet: Packet) { | 624 | fn packet(&mut self, packet: Packet) { |
| 631 | - if Some(packet.stream) == self.video_index && self.video.is_some() { | 625 | + if self |
| 626 | + .video | ||
| 627 | + .as_ref() | ||
| 628 | + .is_some_and(|(index, _)| *index == packet.stream) | ||
| 629 | + { | ||
| 632 | self.backlog.push_back(Queued::Packet(packet)); | 630 | self.backlog.push_back(Queued::Packet(packet)); |
| 633 | - } else if Some(packet.stream) == self.audio_index { | 631 | + } else if self |
| 632 | + .audio | ||
| 633 | + .as_ref() | ||
| 634 | + .is_some_and(|(index, _)| *index == packet.stream) | ||
| 635 | + { | ||
| 634 | self.audio_packet(&packet); | 636 | self.audio_packet(&packet); |
| 635 | } | 637 | } |
| 636 | } | 638 | } |
| 637 | 639 | ||
| 638 | - fn decode_backlog(&mut self) { | 640 | + fn decode_backlog(&mut self) -> bool { |
| 639 | - let Some(video) = self.video.as_mut() else { | 641 | + let Some((_, video)) = self.video.as_mut() else { |
| 640 | - return; | 642 | + return false; |
| 641 | }; | 643 | }; |
| 642 | if lock(&self.shared.video).queue.len() >= QUEUE_LIMIT { | 644 | if lock(&self.shared.video).queue.len() >= QUEUE_LIMIT { |
| 643 | - return; | 645 | + return false; |
| 644 | } | 646 | } |
| 645 | let pictures = match self.backlog.pop_front() { | 647 | let pictures = match self.backlog.pop_front() { |
| 646 | Some(Queued::Packet(packet)) => video.send(&packet), | 648 | Some(Queued::Packet(packet)) => video.send(&packet), |
| 647 | Some(Queued::Flush) => video.flush(), | 649 | Some(Queued::Flush) => video.flush(), |
| 648 | - None => return, | 650 | + None => return false, |
| 649 | }; | 651 | }; |
| 650 | let position = position(&self.shared, &self.playback); | 652 | let position = position(&self.shared, &self.playback); |
| 651 | for (pts, picture) in pictures { | 653 | for (pts, picture) in pictures { |
| @@ -653,13 +655,14 @@ impl Worker { | |||
| 653 | show(&self.shared, pts, picture); | 655 | show(&self.shared, pts, picture); |
| 654 | } | 656 | } |
| 655 | } | 657 | } |
| 658 | + true | ||
| 656 | } | 659 | } |
| 657 | 660 | ||
| 658 | fn audio_packet(&mut self, packet: &Packet) { | 661 | fn audio_packet(&mut self, packet: &Packet) { |
| 659 | if self.producer.is_none() { | 662 | if self.producer.is_none() { |
| 660 | return; | 663 | return; |
| 661 | } | 664 | } |
| 662 | - let Some(audio) = self.audio.as_mut() else { | 665 | + let Some((_, audio)) = self.audio.as_mut() else { |
| 663 | return; | 666 | return; |
| 664 | }; | 667 | }; |
| 665 | let mut samples = std::mem::take(&mut self.scratch); | 668 | let mut samples = std::mem::take(&mut self.scratch); |
| @@ -708,7 +711,7 @@ impl Worker { | |||
| 708 | } | 711 | } |
| 709 | if self.producer.is_some() { | 712 | if self.producer.is_some() { |
| 710 | let mut samples = std::mem::take(&mut self.scratch); | 713 | let mut samples = std::mem::take(&mut self.scratch); |
| 711 | - let params = self.audio.as_mut().and_then(|audio| { | 714 | + let params = self.audio.as_mut().and_then(|(_, audio)| { |
| 712 | audio | 715 | audio |
| 713 | .flush(&mut samples) | 716 | .flush(&mut samples) |
| 714 | .ok() | 717 | .ok() |
| @@ -729,10 +732,10 @@ impl Worker { | |||
| 729 | self.skip = 0; | 732 | self.skip = 0; |
| 730 | self.eof = false; | 733 | self.eof = false; |
| 731 | self.backlog.clear(); | 734 | self.backlog.clear(); |
| 732 | - if let Some(video) = self.video.as_mut() { | 735 | + if let Some((_, video)) = self.video.as_mut() { |
| 733 | video.reset(); | 736 | video.reset(); |
| 734 | } | 737 | } |
| 735 | - if let Some(audio) = self.audio.as_mut() { | 738 | + if let Some((_, audio)) = self.audio.as_mut() { |
| 736 | audio.reset(); | 739 | audio.reset(); |
| 737 | } | 740 | } |
| 738 | lock(&self.shared.video).queue.clear(); | 741 | lock(&self.shared.video).queue.clear(); |
| @@ -744,7 +747,12 @@ impl Worker { | |||
| 744 | lock(&self.shared.stash).clear(); | 747 | lock(&self.shared.stash).clear(); |
| 745 | clock.rebase(to); | 748 | clock.rebase(to); |
| 746 | } | 749 | } |
| 747 | - if let Some(stream) = self.video_index.or(self.audio_index) { | 750 | + let stream = self |
| 751 | + .video | ||
| 752 | + .as_ref() | ||
| 753 | + .map(|(index, _)| *index) | ||
| 754 | + .or(self.audio.as_ref().map(|(index, _)| *index)); | ||
| 755 | + if let Some(stream) = stream { | ||
| 748 | let at = Timestamp::new((to * 1_000_000.0) as i64, TimeBase::MICROS); | 756 | let at = Timestamp::new((to * 1_000_000.0) as i64, TimeBase::MICROS); |
| 749 | if self.reader.seek(stream, at, SeekMode::SyncBefore).is_err() { | 757 | if self.reader.seek(stream, at, SeekMode::SyncBefore).is_err() { |
| 750 | self.restart(); | 758 | self.restart(); |
crates/client/src/media/meter.rsmodified+8 -9
| @@ -1,9 +1,12 @@ | |||
| 1 | use std::collections::VecDeque; | 1 | use std::collections::VecDeque; |
| 2 | -use std::sync::{Arc, Mutex, OnceLock, PoisonError}; | 2 | +use std::sync::{Arc, Mutex, OnceLock}; |
| 3 | 3 | ||
| 4 | use common::constant::VOICE_SAMPLE_RATE; | 4 | use common::constant::VOICE_SAMPLE_RATE; |
| 5 | use spectrum::{Analyzer, WINDOW}; | 5 | use spectrum::{Analyzer, WINDOW}; |
| 6 | 6 | ||
| 7 | +use super::decode::lock; | ||
| 8 | +use super::resample::mean; | ||
| 9 | + | ||
| 7 | pub fn rms(samples: &[f32]) -> f32 { | 10 | pub fn rms(samples: &[f32]) -> f32 { |
| 8 | if samples.is_empty() { | 11 | if samples.is_empty() { |
| 9 | return 0.0; | 12 | return 0.0; |
| @@ -24,12 +27,11 @@ pub struct Spectrum { | |||
| 24 | 27 | ||
| 25 | impl Spectrum { | 28 | impl Spectrum { |
| 26 | pub fn record(&mut self, samples: &[f32], channels: usize) { | 29 | pub fn record(&mut self, samples: &[f32], channels: usize) { |
| 27 | - for frame in samples.chunks(channels) { | 30 | + for frame in samples.chunks(channels.max(1)) { |
| 28 | if self.samples.len() >= WINDOW { | 31 | if self.samples.len() >= WINDOW { |
| 29 | self.samples.pop_front(); | 32 | self.samples.pop_front(); |
| 30 | } | 33 | } |
| 31 | - self.samples | 34 | + self.samples.push_back(mean(frame)); |
| 32 | - .push_back(frame.iter().sum::<f32>() / frame.len() as f32); | ||
| 33 | } | 35 | } |
| 34 | self.fresh = true; | 36 | self.fresh = true; |
| 35 | } | 37 | } |
| @@ -55,13 +57,10 @@ pub struct Meter(Arc<Mutex<Spectrum>>); | |||
| 55 | 57 | ||
| 56 | impl Meter { | 58 | impl Meter { |
| 57 | pub fn record(&self, samples: &[f32], channels: usize) { | 59 | pub fn record(&self, samples: &[f32], channels: usize) { |
| 58 | - self.0 | 60 | + lock(&self.0).record(samples, channels); |
| 59 | - .lock() | ||
| 60 | - .unwrap_or_else(PoisonError::into_inner) | ||
| 61 | - .record(samples, channels); | ||
| 62 | } | 61 | } |
| 63 | 62 | ||
| 64 | pub fn take(&self) -> Vec<f32> { | 63 | pub fn take(&self) -> Vec<f32> { |
| 65 | - self.0.lock().unwrap_or_else(PoisonError::into_inner).take() | 64 | + lock(&self.0).take() |
| 66 | } | 65 | } |
| 67 | } | 66 | } |
crates/client/src/media/mod.rsmodified+7 -5
| @@ -15,6 +15,7 @@ use std::{ | |||
| 15 | use ec_core::registry::MediaType; | 15 | use ec_core::registry::MediaType; |
| 16 | use ec_probe::{Reader, decoder::AudioDecoder}; | 16 | use ec_probe::{Reader, decoder::AudioDecoder}; |
| 17 | use rtrb::RingBuffer; | 17 | use rtrb::RingBuffer; |
| 18 | +use tracing::warn; | ||
| 18 | 19 | ||
| 19 | use crate::voice::{ | 20 | use crate::voice::{ |
| 20 | Playback, | 21 | Playback, |
| @@ -190,6 +191,7 @@ impl Player { | |||
| 190 | .name("media-decode".to_string()) | 191 | .name("media-decode".to_string()) |
| 191 | .spawn(move || { | 192 | .spawn(move || { |
| 192 | let Ok((reader, tracks, _)) = open_tracks(&worker_path) else { | 193 | let Ok((reader, tracks, _)) = open_tracks(&worker_path) else { |
| 194 | + warn!("media reopen failed: {}", worker_path.display()); | ||
| 193 | return; | 195 | return; |
| 194 | }; | 196 | }; |
| 195 | Worker::new( | 197 | Worker::new( |
| @@ -212,7 +214,7 @@ impl Player { | |||
| 212 | } | 214 | } |
| 213 | 215 | ||
| 214 | pub fn play(&self) { | 216 | pub fn play(&self) { |
| 215 | - if self.finished() { | 217 | + if lock(&self.shared.clock).state == State::Finished { |
| 216 | *lock(&self.shared.seek) = Some(0.0); | 218 | *lock(&self.shared.seek) = Some(0.0); |
| 217 | } | 219 | } |
| 218 | let mut clock = lock(&self.shared.clock); | 220 | let mut clock = lock(&self.shared.clock); |
| @@ -247,16 +249,16 @@ impl Player { | |||
| 247 | 249 | ||
| 248 | pub fn seek(&self, to: Duration) { | 250 | pub fn seek(&self, to: Duration) { |
| 249 | *lock(&self.shared.seek) = Some(to.as_secs_f64()); | 251 | *lock(&self.shared.seek) = Some(to.as_secs_f64()); |
| 252 | + let mut clock = lock(&self.shared.clock); | ||
| 253 | + if clock.state == State::Finished { | ||
| 254 | + clock.set(State::Paused); | ||
| 255 | + } | ||
| 250 | } | 256 | } |
| 251 | 257 | ||
| 252 | pub fn playing(&self) -> bool { | 258 | pub fn playing(&self) -> bool { |
| 253 | lock(&self.shared.clock).state == State::Playing | 259 | lock(&self.shared.clock).state == State::Playing |
| 254 | } | 260 | } |
| 255 | 261 | ||
| 256 | - pub fn finished(&self) -> bool { | ||
| 257 | - lock(&self.shared.clock).state == State::Finished | ||
| 258 | - } | ||
| 259 | - | ||
| 260 | pub fn position(&self) -> Duration { | 262 | pub fn position(&self) -> Duration { |
| 261 | Duration::from_secs_f64(decode::position(&self.shared, &self.playback)) | 263 | Duration::from_secs_f64(decode::position(&self.shared, &self.playback)) |
| 262 | } | 264 | } |
crates/client/src/media/resample.rsmodified+6 -5
| @@ -2,22 +2,23 @@ use common::constant::VOICE_SAMPLE_RATE; | |||
| 2 | 2 | ||
| 3 | pub type Stereo = [f32; 2]; | 3 | pub type Stereo = [f32; 2]; |
| 4 | 4 | ||
| 5 | +pub fn mean(frame: &[f32]) -> f32 { | ||
| 6 | + frame.iter().sum::<f32>() / frame.len() as f32 | ||
| 7 | +} | ||
| 8 | + | ||
| 5 | pub fn stereo(interleaved: &[f32], channels: usize) -> Vec<Stereo> { | 9 | pub fn stereo(interleaved: &[f32], channels: usize) -> Vec<Stereo> { |
| 6 | interleaved | 10 | interleaved |
| 7 | .chunks(channels.max(1)) | 11 | .chunks(channels.max(1)) |
| 8 | .map(|frame| match frame { | 12 | .map(|frame| match frame { |
| 9 | [mono] => [*mono; 2], | 13 | [mono] => [*mono; 2], |
| 10 | [left, right] => [*left, *right], | 14 | [left, right] => [*left, *right], |
| 11 | - _ => [frame.iter().sum::<f32>() / frame.len() as f32; 2], | 15 | + _ => [mean(frame); 2], |
| 12 | }) | 16 | }) |
| 13 | .collect() | 17 | .collect() |
| 14 | } | 18 | } |
| 15 | 19 | ||
| 16 | pub fn downmix(interleaved: &[f32], channels: usize) -> Vec<f32> { | 20 | pub fn downmix(interleaved: &[f32], channels: usize) -> Vec<f32> { |
| 17 | - interleaved | 21 | + interleaved.chunks(channels.max(1)).map(mean).collect() |
| 18 | - .chunks(channels.max(1)) | ||
| 19 | - .map(|frame| frame.iter().sum::<f32>() / frame.len() as f32) | ||
| 20 | - .collect() | ||
| 21 | } | 22 | } |
| 22 | 23 | ||
| 23 | #[derive(Debug, Default)] | 24 | #[derive(Debug, Default)] |
crates/client/src/media/voice_note.rsmodified+3 -7
| @@ -13,7 +13,7 @@ use ec_ogg::OggMuxer; | |||
| 13 | use ec_opus::{Application, Encoder, ogg::opus_head}; | 13 | use ec_opus::{Application, Encoder, ogg::opus_head}; |
| 14 | use ec_probe::{Reader, decoder::AudioDecoder}; | 14 | use ec_probe::{Reader, decoder::AudioDecoder}; |
| 15 | 15 | ||
| 16 | -use super::resample; | 16 | +use super::{meter::rms, resample}; |
| 17 | 17 | ||
| 18 | pub const BARS: usize = 40; | 18 | pub const BARS: usize = 40; |
| 19 | const BITRATE: u32 = 32_000; | 19 | const BITRATE: u32 = 32_000; |
| @@ -26,11 +26,7 @@ pub struct Waveform { | |||
| 26 | } | 26 | } |
| 27 | 27 | ||
| 28 | pub fn level(samples: &[f32]) -> f32 { | 28 | pub fn level(samples: &[f32]) -> f32 { |
| 29 | - if samples.is_empty() { | 29 | + let db = 20. * rms(samples).max(f32::MIN_POSITIVE).log10(); |
| 30 | - return 0.; | ||
| 31 | - } | ||
| 32 | - let mean = samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32; | ||
| 33 | - let db = 10. * mean.max(f32::MIN_POSITIVE).log10(); | ||
| 34 | ((db + RANGE_DB) / RANGE_DB).clamp(0., 1.) | 30 | ((db + RANGE_DB) / RANGE_DB).clamp(0., 1.) |
| 35 | } | 31 | } |
| 36 | 32 | ||
| @@ -62,7 +58,7 @@ pub fn waveform(path: &Path) -> Option<Waveform> { | |||
| 62 | } | 58 | } |
| 63 | let mono = resample::downmix(&interleaved, decoder.channels()); | 59 | let mono = resample::downmix(&interleaved, decoder.channels()); |
| 64 | Some(Waveform { | 60 | Some(Waveform { |
| 65 | - duration: Duration::from_secs_f32(mono.len() as f32 / VOICE_SAMPLE_RATE as f32), | 61 | + duration: Duration::from_secs_f32(mono.len() as f32 / decoder.sample_rate() as f32), |
| 66 | peaks: peaks(&mono), | 62 | peaks: peaks(&mono), |
| 67 | }) | 63 | }) |
| 68 | } | 64 | } |
crates/client/src/mutes.rsmodified+5 -19
| @@ -1,15 +1,13 @@ | |||
| 1 | -use std::{collections::HashSet, fs, path::Path}; | 1 | +use std::collections::HashSet; |
| 2 | 2 | ||
| 3 | -use tracing::warn; | 3 | +use crate::{read_config, write_config}; |
| 4 | - | ||
| 5 | -use crate::config_file; | ||
| 6 | 4 | ||
| 7 | fn prefix(account_user_id: &str) -> String { | 5 | fn prefix(account_user_id: &str) -> String { |
| 8 | format!("{account_user_id}\t") | 6 | format!("{account_user_id}\t") |
| 9 | } | 7 | } |
| 10 | 8 | ||
| 11 | pub fn load(account_user_id: &str) -> HashSet<String> { | 9 | pub fn load(account_user_id: &str) -> HashSet<String> { |
| 12 | - let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok()) else { | 10 | + let Some(content) = read_config("mutes") else { |
| 13 | return HashSet::new(); | 11 | return HashSet::new(); |
| 14 | }; | 12 | }; |
| 15 | let prefix = prefix(account_user_id); | 13 | let prefix = prefix(account_user_id); |
| @@ -22,11 +20,8 @@ pub fn load(account_user_id: &str) -> HashSet<String> { | |||
| 22 | } | 20 | } |
| 23 | 21 | ||
| 24 | pub fn save(account_user_id: &str, muted: &HashSet<String>) { | 22 | pub fn save(account_user_id: &str, muted: &HashSet<String>) { |
| 25 | - let Some(path) = config_file("mutes") else { | ||
| 26 | - return; | ||
| 27 | - }; | ||
| 28 | let prefix = prefix(account_user_id); | 23 | let prefix = prefix(account_user_id); |
| 29 | - let mut content: String = fs::read_to_string(&path) | 24 | + let mut content: String = read_config("mutes") |
| 30 | .unwrap_or_default() | 25 | .unwrap_or_default() |
| 31 | .lines() | 26 | .lines() |
| 32 | .filter(|line| !line.starts_with(&prefix)) | 27 | .filter(|line| !line.starts_with(&prefix)) |
| @@ -38,14 +33,5 @@ pub fn save(account_user_id: &str, muted: &HashSet<String>) { | |||
| 38 | .map(|community_id| format!("{prefix}{community_id}\n")), | 33 | .map(|community_id| format!("{prefix}{community_id}\n")), |
| 39 | ); | 34 | ); |
| 40 | 35 | ||
| 41 | - if let Err(error) = write(&path, &content) { | 36 | + write_config("mutes", &content); |
| 42 | - warn!("save mutes failed: {error}"); | ||
| 43 | - } | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -fn write(path: &Path, content: &str) -> std::io::Result<()> { | ||
| 47 | - if let Some(parent) = path.parent() { | ||
| 48 | - fs::create_dir_all(parent)?; | ||
| 49 | - } | ||
| 50 | - fs::write(path, content) | ||
| 51 | } | 37 | } |
crates/client/src/network.rsmodified+378 -504
| @@ -1,5 +1,6 @@ | |||
| 1 | use std::{ | 1 | use std::{ |
| 2 | collections::HashMap, | 2 | collections::HashMap, |
| 3 | + future::Future, | ||
| 3 | path::{Path, PathBuf}, | 4 | path::{Path, PathBuf}, |
| 4 | sync::{Arc, Mutex}, | 5 | sync::{Arc, Mutex}, |
| 5 | time::Duration, | 6 | time::Duration, |
| @@ -28,9 +29,9 @@ use common::{ | |||
| 28 | share::{Fps, Kind, Quality, Resolution, Source}, | 29 | share::{Fps, Kind, Quality, Resolution, Source}, |
| 29 | validate::{ | 30 | validate::{ |
| 30 | validate_attachment_name, validate_attachment_size, validate_avatar_size, | 31 | validate_attachment_name, validate_attachment_size, validate_avatar_size, |
| 31 | - validate_community_name, validate_forward, validate_message_body, validate_new_message, | 32 | + validate_community_name, validate_forward, validate_new_message, validate_password, |
| 32 | - validate_password, validate_poll, validate_reason, validate_server_settings, | 33 | + validate_poll, validate_reason, validate_server_settings, validate_status, |
| 33 | - validate_status, validate_username, | 34 | + validate_username, |
| 34 | }, | 35 | }, |
| 35 | }; | 36 | }; |
| 36 | use quinn::Endpoint; | 37 | use quinn::Endpoint; |
| @@ -48,7 +49,7 @@ use tracing::{info, warn}; | |||
| 48 | 49 | ||
| 49 | use crate::{ | 50 | use crate::{ |
| 50 | ClientConfig, | 51 | ClientConfig, |
| 51 | - settings::{SHARE_QUALITY, ShareSettings, VoiceSettings}, | 52 | + settings::{ShareSettings, VoiceSettings}, |
| 52 | share::{ | 53 | share::{ |
| 53 | audio::AudioApp, | 54 | audio::AudioApp, |
| 54 | audio_capture, | 55 | audio_capture, |
| @@ -83,6 +84,20 @@ type SharedSettings = Arc<Mutex<VoiceSettings>>; | |||
| 83 | type SharedShare = Arc<Mutex<Share>>; | 84 | type SharedShare = Arc<Mutex<Share>>; |
| 84 | type SharedShareSettings = Arc<Mutex<ShareSettings>>; | 85 | type SharedShareSettings = Arc<Mutex<ShareSettings>>; |
| 85 | 86 | ||
| 87 | +#[derive(Clone, Default)] | ||
| 88 | +struct Shared { | ||
| 89 | + voice: SharedVoice, | ||
| 90 | + mic_test: SharedVoice, | ||
| 91 | + voice_settings: SharedSettings, | ||
| 92 | + share: SharedShare, | ||
| 93 | + share_settings: SharedShareSettings, | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +fn hang_up(shared: &Shared) { | ||
| 97 | + shared.voice.lock().unwrap().take(); | ||
| 98 | + *shared.share.lock().unwrap() = Share::default(); | ||
| 99 | +} | ||
| 100 | + | ||
| 86 | #[derive(Default)] | 101 | #[derive(Default)] |
| 87 | pub struct Levels { | 102 | pub struct Levels { |
| 88 | pub voice: Vec<(String, Vec<f32>)>, | 103 | pub voice: Vec<(String, Vec<f32>)>, |
| @@ -98,10 +113,6 @@ struct Share { | |||
| 98 | } | 113 | } |
| 99 | 114 | ||
| 100 | impl Share { | 115 | impl Share { |
| 101 | - fn clear(shared: &SharedShare) { | ||
| 102 | - *shared.lock().unwrap() = Share::default(); | ||
| 103 | - } | ||
| 104 | - | ||
| 105 | fn event(&mut self, event: &Event) { | 116 | fn event(&mut self, event: &Event) { |
| 106 | match event { | 117 | match event { |
| 107 | Event::ShareLayers { kind, layers } => { | 118 | Event::ShareLayers { kind, layers } => { |
| @@ -196,11 +207,16 @@ enum Command { | |||
| 196 | #[derive(Clone)] | 207 | #[derive(Clone)] |
| 197 | pub struct NetworkHandle { | 208 | pub struct NetworkHandle { |
| 198 | command_sender: mpsc::Sender<Command>, | 209 | command_sender: mpsc::Sender<Command>, |
| 199 | - voice: SharedVoice, | 210 | + shared: Shared, |
| 200 | - mic_test: SharedVoice, | 211 | +} |
| 201 | - voice_settings: SharedSettings, | 212 | + |
| 202 | - share: SharedShare, | 213 | +macro_rules! expect { |
| 203 | - share_settings: SharedShareSettings, | 214 | + ($response:expr, $variant:path) => { |
| 215 | + match $response { | ||
| 216 | + $variant(value) => Ok(value), | ||
| 217 | + _ => Err(Error::Server), | ||
| 218 | + } | ||
| 219 | + }; | ||
| 204 | } | 220 | } |
| 205 | 221 | ||
| 206 | impl NetworkHandle { | 222 | impl NetworkHandle { |
| @@ -219,7 +235,7 @@ impl NetworkHandle { | |||
| 219 | } | 235 | } |
| 220 | 236 | ||
| 221 | fn with_voice<T>(&self, f: impl FnOnce(&Voice) -> T) -> Option<T> { | 237 | fn with_voice<T>(&self, f: impl FnOnce(&Voice) -> T) -> Option<T> { |
| 222 | - self.voice.lock().unwrap().as_ref().map(f) | 238 | + self.shared.voice.lock().unwrap().as_ref().map(f) |
| 223 | } | 239 | } |
| 224 | 240 | ||
| 225 | async fn request(&self, request: Request) -> Result<Response, Error> { | 241 | async fn request(&self, request: Request) -> Result<Response, Error> { |
| @@ -247,15 +263,13 @@ impl NetworkHandle { | |||
| 247 | } | 263 | } |
| 248 | 264 | ||
| 249 | pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Error> { | 265 | pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Error> { |
| 250 | - match self | 266 | + expect!( |
| 251 | - .request(Request::Sessions { | 267 | + self.request(Request::Sessions { |
| 252 | user_id: user_id.to_string(), | 268 | user_id: user_id.to_string(), |
| 253 | }) | 269 | }) |
| 254 | - .await? | 270 | + .await?, |
| 255 | - { | 271 | + Response::Sessions |
| 256 | - Response::Sessions(sessions) => Ok(sessions), | 272 | + ) |
| 257 | - _ => Err(Error::Server), | ||
| 258 | - } | ||
| 259 | } | 273 | } |
| 260 | 274 | ||
| 261 | pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Error> { | 275 | pub async fn revoke_session(&self, user_id: &str, session_id: &str) -> Result<(), Error> { |
| @@ -269,16 +283,14 @@ impl NetworkHandle { | |||
| 269 | pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Error> { | 283 | pub async fn rename_user(&self, user_id: &str, username: &str) -> Result<User, Error> { |
| 270 | validate_username(username)?; | 284 | validate_username(username)?; |
| 271 | 285 | ||
| 272 | - match self | 286 | + expect!( |
| 273 | - .request(Request::RenameUser { | 287 | + self.request(Request::RenameUser { |
| 274 | user_id: user_id.to_string(), | 288 | user_id: user_id.to_string(), |
| 275 | username: username.to_string(), | 289 | username: username.to_string(), |
| 276 | }) | 290 | }) |
| 277 | - .await? | 291 | + .await?, |
| 278 | - { | 292 | + Response::User |
| 279 | - Response::User(user) => Ok(user), | 293 | + ) |
| 280 | - _ => Err(Error::Server), | ||
| 281 | - } | ||
| 282 | } | 294 | } |
| 283 | 295 | ||
| 284 | pub async fn resume(&self, token: &str) -> Result<(User, String), Error> { | 296 | pub async fn resume(&self, token: &str) -> Result<(User, String), Error> { |
| @@ -310,7 +322,6 @@ impl NetworkHandle { | |||
| 310 | } | 322 | } |
| 311 | 323 | ||
| 312 | pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Error> { | 324 | pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Error> { |
| 313 | - validate_username(username)?; | ||
| 314 | validate_password(password)?; | 325 | validate_password(password)?; |
| 315 | 326 | ||
| 316 | self.sign_in(Request::Login { | 327 | self.sign_in(Request::Login { |
| @@ -327,34 +338,28 @@ impl NetworkHandle { | |||
| 327 | pub async fn update_user(&self, username: &str) -> Result<User, Error> { | 338 | pub async fn update_user(&self, username: &str) -> Result<User, Error> { |
| 328 | validate_username(username)?; | 339 | validate_username(username)?; |
| 329 | 340 | ||
| 330 | - match self | 341 | + expect!( |
| 331 | - .request(Request::UpdateUser { | 342 | + self.request(Request::UpdateUser { |
| 332 | username: username.to_string(), | 343 | username: username.to_string(), |
| 333 | }) | 344 | }) |
| 334 | - .await? | 345 | + .await?, |
| 335 | - { | 346 | + Response::User |
| 336 | - Response::User(user) => Ok(user), | 347 | + ) |
| 337 | - _ => Err(Error::Server), | ||
| 338 | - } | ||
| 339 | } | 348 | } |
| 340 | 349 | ||
| 341 | pub async fn delete_user(&self, user_id: &str) -> Result<(), Error> { | 350 | pub async fn delete_user(&self, user_id: &str) -> Result<(), Error> { |
| 342 | - match self | 351 | + expect!( |
| 343 | - .request(Request::DeleteUser { | 352 | + self.request(Request::DeleteUser { |
| 344 | user_id: user_id.to_string(), | 353 | user_id: user_id.to_string(), |
| 345 | }) | 354 | }) |
| 346 | - .await? | 355 | + .await?, |
| 347 | - { | 356 | + Response::User |
| 348 | - Response::User(_) => Ok(()), | 357 | + ) |
| 349 | - _ => Err(Error::Server), | 358 | + .map(|_| ()) |
| 350 | - } | ||
| 351 | } | 359 | } |
| 352 | 360 | ||
| 353 | pub async fn users(&self) -> Result<Vec<Account>, Error> { | 361 | pub async fn users(&self) -> Result<Vec<Account>, Error> { |
| 354 | - match self.request(Request::Users).await? { | 362 | + expect!(self.request(Request::Users).await?, Response::Users) |
| 355 | - Response::Users(accounts) => Ok(accounts), | ||
| 356 | - _ => Err(Error::Server), | ||
| 357 | - } | ||
| 358 | } | 363 | } |
| 359 | 364 | ||
| 360 | pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Error> { | 365 | pub async fn suspend_user(&self, user_id: &str, suspended: bool) -> Result<(), Error> { |
| @@ -390,10 +395,10 @@ impl NetworkHandle { | |||
| 390 | } | 395 | } |
| 391 | 396 | ||
| 392 | pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Error> { | 397 | pub async fn server_bans(&self) -> Result<Vec<ServerBan>, Error> { |
| 393 | - match self.request(Request::ServerBans).await? { | 398 | + expect!( |
| 394 | - Response::ServerBans(bans) => Ok(bans), | 399 | + self.request(Request::ServerBans).await?, |
| 395 | - _ => Err(Error::Server), | 400 | + Response::ServerBans |
| 396 | - } | 401 | + ) |
| 397 | } | 402 | } |
| 398 | 403 | ||
| 399 | pub async fn remove_server_ban(&self, id: &str) -> Result<(), Error> { | 404 | pub async fn remove_server_ban(&self, id: &str) -> Result<(), Error> { |
| @@ -406,20 +411,18 @@ impl NetworkHandle { | |||
| 406 | uses: u32, | 411 | uses: u32, |
| 407 | hours: Option<u32>, | 412 | hours: Option<u32>, |
| 408 | ) -> Result<InviteCode, Error> { | 413 | ) -> Result<InviteCode, Error> { |
| 409 | - match self | 414 | + expect!( |
| 410 | - .request(Request::CreateInviteCode { uses, hours }) | 415 | + self.request(Request::CreateInviteCode { uses, hours }) |
| 411 | - .await? | 416 | + .await?, |
| 412 | - { | 417 | + Response::InviteCode |
| 413 | - Response::InviteCode(code) => Ok(code), | 418 | + ) |
| 414 | - _ => Err(Error::Server), | ||
| 415 | - } | ||
| 416 | } | 419 | } |
| 417 | 420 | ||
| 418 | pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Error> { | 421 | pub async fn invite_codes(&self) -> Result<Vec<InviteCode>, Error> { |
| 419 | - match self.request(Request::InviteCodes).await? { | 422 | + expect!( |
| 420 | - Response::InviteCodes(codes) => Ok(codes), | 423 | + self.request(Request::InviteCodes).await?, |
| 421 | - _ => Err(Error::Server), | 424 | + Response::InviteCodes |
| 422 | - } | 425 | + ) |
| 423 | } | 426 | } |
| 424 | 427 | ||
| 425 | pub async fn delete_invite_code(&self, code: &str) -> Result<(), Error> { | 428 | pub async fn delete_invite_code(&self, code: &str) -> Result<(), Error> { |
| @@ -447,28 +450,24 @@ impl NetworkHandle { | |||
| 447 | } | 450 | } |
| 448 | 451 | ||
| 449 | pub async fn clear_profile(&self, user_id: &str) -> Result<User, Error> { | 452 | pub async fn clear_profile(&self, user_id: &str) -> Result<User, Error> { |
| 450 | - match self | 453 | + expect!( |
| 451 | - .request(Request::ClearProfile { | 454 | + self.request(Request::ClearProfile { |
| 452 | user_id: user_id.to_string(), | 455 | user_id: user_id.to_string(), |
| 453 | }) | 456 | }) |
| 454 | - .await? | 457 | + .await?, |
| 455 | - { | 458 | + Response::User |
| 456 | - Response::User(user) => Ok(user), | 459 | + ) |
| 457 | - _ => Err(Error::Server), | ||
| 458 | - } | ||
| 459 | } | 460 | } |
| 460 | 461 | ||
| 461 | pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Error> { | 462 | pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Error> { |
| 462 | - match self | 463 | + expect!( |
| 463 | - .request(Request::SetRole { | 464 | + self.request(Request::SetRole { |
| 464 | user_id: user_id.to_string(), | 465 | user_id: user_id.to_string(), |
| 465 | role, | 466 | role, |
| 466 | }) | 467 | }) |
| 467 | - .await? | 468 | + .await?, |
| 468 | - { | 469 | + Response::User |
| 469 | - Response::User(user) => Ok(user), | 470 | + ) |
| 470 | - _ => Err(Error::Server), | ||
| 471 | - } | ||
| 472 | } | 471 | } |
| 473 | 472 | ||
| 474 | pub async fn admin_logs( | 473 | pub async fn admin_logs( |
| @@ -486,24 +485,21 @@ impl NetworkHandle { | |||
| 486 | after_ms, | 485 | after_ms, |
| 487 | before_ms, | 486 | before_ms, |
| 488 | }; | 487 | }; |
| 489 | - match self.request(request).await? { | 488 | + expect!(self.request(request).await?, Response::AdminLogs) |
| 490 | - Response::AdminLogs(entries) => Ok(entries), | ||
| 491 | - _ => Err(Error::Server), | ||
| 492 | - } | ||
| 493 | } | 489 | } |
| 494 | 490 | ||
| 495 | pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Error> { | 491 | pub async fn daily_stats(&self, days: u32) -> Result<Vec<DayStat>, Error> { |
| 496 | - match self.request(Request::DailyStats { days }).await? { | 492 | + expect!( |
| 497 | - Response::DailyStats(stats) => Ok(stats), | 493 | + self.request(Request::DailyStats { days }).await?, |
| 498 | - _ => Err(Error::Server), | 494 | + Response::DailyStats |
| 499 | - } | 495 | + ) |
| 500 | } | 496 | } |
| 501 | 497 | ||
| 502 | pub async fn server_settings(&self) -> Result<ServerSettings, Error> { | 498 | pub async fn server_settings(&self) -> Result<ServerSettings, Error> { |
| 503 | - match self.request(Request::ServerSettings).await? { | 499 | + expect!( |
| 504 | - Response::ServerSettings(settings) => Ok(settings), | 500 | + self.request(Request::ServerSettings).await?, |
| 505 | - _ => Err(Error::Server), | 501 | + Response::ServerSettings |
| 506 | - } | 502 | + ) |
| 507 | } | 503 | } |
| 508 | 504 | ||
| 509 | pub async fn update_server_settings( | 505 | pub async fn update_server_settings( |
| @@ -512,43 +508,36 @@ impl NetworkHandle { | |||
| 512 | ) -> Result<ServerSettings, Error> { | 508 | ) -> Result<ServerSettings, Error> { |
| 513 | validate_server_settings(&settings)?; | 509 | validate_server_settings(&settings)?; |
| 514 | 510 | ||
| 515 | - match self | 511 | + expect!( |
| 516 | - .request(Request::UpdateServerSettings { settings }) | 512 | + self.request(Request::UpdateServerSettings { settings }) |
| 517 | - .await? | 513 | + .await?, |
| 518 | - { | 514 | + Response::ServerSettings |
| 519 | - Response::ServerSettings(settings) => Ok(settings), | 515 | + ) |
| 520 | - _ => Err(Error::Server), | ||
| 521 | - } | ||
| 522 | } | 516 | } |
| 523 | 517 | ||
| 524 | pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Error> { | 518 | pub async fn create_user(&self, username: &str, password: &str) -> Result<User, Error> { |
| 525 | validate_username(username)?; | 519 | validate_username(username)?; |
| 526 | validate_password(password)?; | 520 | validate_password(password)?; |
| 527 | 521 | ||
| 528 | - match self | 522 | + expect!( |
| 529 | - .request(Request::CreateUser { | 523 | + self.request(Request::CreateUser { |
| 530 | username: username.to_string(), | 524 | username: username.to_string(), |
| 531 | password: password.to_string(), | 525 | password: password.to_string(), |
| 532 | }) | 526 | }) |
| 533 | - .await? | 527 | + .await?, |
| 534 | - { | 528 | + Response::User |
| 535 | - Response::User(user) => Ok(user), | 529 | + ) |
| 536 | - _ => Err(Error::Server), | ||
| 537 | - } | ||
| 538 | } | 530 | } |
| 539 | 531 | ||
| 540 | pub async fn overview(&self) -> Result<Overview, Error> { | 532 | pub async fn overview(&self) -> Result<Overview, Error> { |
| 541 | - match self.request(Request::Overview).await? { | 533 | + expect!(self.request(Request::Overview).await?, Response::Overview) |
| 542 | - Response::Overview(overview) => Ok(overview), | ||
| 543 | - _ => Err(Error::Server), | ||
| 544 | - } | ||
| 545 | } | 534 | } |
| 546 | 535 | ||
| 547 | pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Error> { | 536 | pub async fn all_communities(&self) -> Result<Vec<CommunitySummary>, Error> { |
| 548 | - match self.request(Request::AllCommunities).await? { | 537 | + expect!( |
| 549 | - Response::AllCommunities(summaries) => Ok(summaries), | 538 | + self.request(Request::AllCommunities).await?, |
| 550 | - _ => Err(Error::Server), | 539 | + Response::AllCommunities |
| 551 | - } | 540 | + ) |
| 552 | } | 541 | } |
| 553 | 542 | ||
| 554 | pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Error> { | 543 | pub async fn transfer_ownership(&self, community_id: &str, user_id: &str) -> Result<(), Error> { |
| @@ -560,29 +549,25 @@ impl NetworkHandle { | |||
| 560 | } | 549 | } |
| 561 | 550 | ||
| 562 | pub async fn read_user(&self, user_id: &str) -> Result<User, Error> { | 551 | pub async fn read_user(&self, user_id: &str) -> Result<User, Error> { |
| 563 | - match self | 552 | + expect!( |
| 564 | - .request(Request::ReadUser { | 553 | + self.request(Request::ReadUser { |
| 565 | user_id: user_id.to_string(), | 554 | user_id: user_id.to_string(), |
| 566 | }) | 555 | }) |
| 567 | - .await? | 556 | + .await?, |
| 568 | - { | 557 | + Response::User |
| 569 | - Response::User(user) => Ok(user), | 558 | + ) |
| 570 | - _ => Err(Error::Server), | ||
| 571 | - } | ||
| 572 | } | 559 | } |
| 573 | 560 | ||
| 574 | pub async fn create_community(&self, name: &str) -> Result<Community, Error> { | 561 | pub async fn create_community(&self, name: &str) -> Result<Community, Error> { |
| 575 | validate_community_name(name)?; | 562 | validate_community_name(name)?; |
| 576 | 563 | ||
| 577 | - match self | 564 | + expect!( |
| 578 | - .request(Request::CreateCommunity { | 565 | + self.request(Request::CreateCommunity { |
| 579 | name: name.to_string(), | 566 | name: name.to_string(), |
| 580 | }) | 567 | }) |
| 581 | - .await? | 568 | + .await?, |
| 582 | - { | 569 | + Response::Community |
| 583 | - Response::Community(community) => Ok(community), | 570 | + ) |
| 584 | - _ => Err(Error::Server), | ||
| 585 | - } | ||
| 586 | } | 571 | } |
| 587 | 572 | ||
| 588 | pub async fn update_community( | 573 | pub async fn update_community( |
| @@ -592,28 +577,25 @@ impl NetworkHandle { | |||
| 592 | ) -> Result<Community, Error> { | 577 | ) -> Result<Community, Error> { |
| 593 | validate_community_name(name)?; | 578 | validate_community_name(name)?; |
| 594 | 579 | ||
| 595 | - match self | 580 | + expect!( |
| 596 | - .request(Request::UpdateCommunity { | 581 | + self.request(Request::UpdateCommunity { |
| 597 | community_id: community_id.to_string(), | 582 | community_id: community_id.to_string(), |
| 598 | name: name.to_string(), | 583 | name: name.to_string(), |
| 599 | }) | 584 | }) |
| 600 | - .await? | 585 | + .await?, |
| 601 | - { | 586 | + Response::Community |
| 602 | - Response::Community(community) => Ok(community), | 587 | + ) |
| 603 | - _ => Err(Error::Server), | ||
| 604 | - } | ||
| 605 | } | 588 | } |
| 606 | 589 | ||
| 607 | pub async fn delete_community(&self, community_id: &str) -> Result<(), Error> { | 590 | pub async fn delete_community(&self, community_id: &str) -> Result<(), Error> { |
| 608 | - match self | 591 | + expect!( |
| 609 | - .request(Request::DeleteCommunity { | 592 | + self.request(Request::DeleteCommunity { |
| 610 | community_id: community_id.to_string(), | 593 | community_id: community_id.to_string(), |
| 611 | }) | 594 | }) |
| 612 | - .await? | 595 | + .await?, |
| 613 | - { | 596 | + Response::Community |
| 614 | - Response::Community(_) => Ok(()), | 597 | + ) |
| 615 | - _ => Err(Error::Server), | 598 | + .map(|_| ()) |
| 616 | - } | ||
| 617 | } | 599 | } |
| 618 | 600 | ||
| 619 | pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { | 601 | pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> { |
| @@ -624,22 +606,20 @@ impl NetworkHandle { | |||
| 624 | } | 606 | } |
| 625 | 607 | ||
| 626 | pub async fn communities(&self) -> Result<Vec<Community>, Error> { | 608 | pub async fn communities(&self) -> Result<Vec<Community>, Error> { |
| 627 | - match self.request(Request::Communities).await? { | 609 | + expect!( |
| 628 | - Response::Communities(communities) => Ok(communities), | 610 | + self.request(Request::Communities).await?, |
| 629 | - _ => Err(Error::Server), | 611 | + Response::Communities |
| 630 | - } | 612 | + ) |
| 631 | } | 613 | } |
| 632 | 614 | ||
| 633 | pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Error> { | 615 | pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Error> { |
| 634 | - match self | 616 | + expect!( |
| 635 | - .request(Request::Members { | 617 | + self.request(Request::Members { |
| 636 | community_id: community_id.to_string(), | 618 | community_id: community_id.to_string(), |
| 637 | }) | 619 | }) |
| 638 | - .await? | 620 | + .await?, |
| 639 | - { | 621 | + Response::Members |
| 640 | - Response::Members(members) => Ok(members), | 622 | + ) |
| 641 | - _ => Err(Error::Server), | ||
| 642 | - } | ||
| 643 | } | 623 | } |
| 644 | 624 | ||
| 645 | pub async fn kick( | 625 | pub async fn kick( |
| @@ -681,27 +661,23 @@ impl NetworkHandle { | |||
| 681 | } | 661 | } |
| 682 | 662 | ||
| 683 | pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Error> { | 663 | pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Error> { |
| 684 | - match self | 664 | + expect!( |
| 685 | - .request(Request::Bans { | 665 | + self.request(Request::Bans { |
| 686 | community_id: community_id.to_string(), | 666 | community_id: community_id.to_string(), |
| 687 | }) | 667 | }) |
| 688 | - .await? | 668 | + .await?, |
| 689 | - { | 669 | + Response::Bans |
| 690 | - Response::Bans(users) => Ok(users), | 670 | + ) |
| 691 | - _ => Err(Error::Server), | ||
| 692 | - } | ||
| 693 | } | 671 | } |
| 694 | 672 | ||
| 695 | pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Error> { | 673 | pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Error> { |
| 696 | - match self | 674 | + expect!( |
| 697 | - .request(Request::Logs { | 675 | + self.request(Request::Logs { |
| 698 | community_id: community_id.to_string(), | 676 | community_id: community_id.to_string(), |
| 699 | }) | 677 | }) |
| 700 | - .await? | 678 | + .await?, |
| 701 | - { | 679 | + Response::Logs |
| 702 | - Response::Logs(entries) => Ok(entries), | 680 | + ) |
| 703 | - _ => Err(Error::Server), | ||
| 704 | - } | ||
| 705 | } | 681 | } |
| 706 | 682 | ||
| 707 | pub async fn set_rank( | 683 | pub async fn set_rank( |
| @@ -719,15 +695,14 @@ impl NetworkHandle { | |||
| 719 | } | 695 | } |
| 720 | 696 | ||
| 721 | pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> { | 697 | pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> { |
| 722 | - match self | 698 | + expect!( |
| 723 | - .request(Request::DeleteMessage { | 699 | + self.request(Request::DeleteMessage { |
| 724 | message_id: message_id.to_string(), | 700 | message_id: message_id.to_string(), |
| 725 | }) | 701 | }) |
| 726 | - .await? | 702 | + .await?, |
| 727 | - { | 703 | + Response::Message |
| 728 | - Response::Message(_) => Ok(()), | 704 | + ) |
| 729 | - _ => Err(Error::Server), | 705 | + .map(|_| ()) |
| 730 | - } | ||
| 731 | } | 706 | } |
| 732 | 707 | ||
| 733 | pub async fn create_message( | 708 | pub async fn create_message( |
| @@ -739,33 +714,29 @@ impl NetworkHandle { | |||
| 739 | ) -> Result<Message, Error> { | 714 | ) -> Result<Message, Error> { |
| 740 | validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; | 715 | validate_new_message(body, attachments.len(), MAXIMUM_MESSAGE_LENGTH)?; |
| 741 | 716 | ||
| 742 | - match self | 717 | + expect!( |
| 743 | - .request(Request::CreateMessage { | 718 | + self.request(Request::CreateMessage { |
| 744 | community_id: community_id.to_string(), | 719 | community_id: community_id.to_string(), |
| 745 | body: body.to_string(), | 720 | body: body.to_string(), |
| 746 | attachments, | 721 | attachments, |
| 747 | reply_to, | 722 | reply_to, |
| 748 | }) | 723 | }) |
| 749 | - .await? | 724 | + .await?, |
| 750 | - { | 725 | + Response::Message |
| 751 | - Response::Message(message) => Ok(message), | 726 | + ) |
| 752 | - _ => Err(Error::Server), | ||
| 753 | - } | ||
| 754 | } | 727 | } |
| 755 | 728 | ||
| 756 | pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Error> { | 729 | pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Error> { |
| 757 | - validate_message_body(body, MAXIMUM_MESSAGE_LENGTH)?; | 730 | + validate_new_message(body, 0, MAXIMUM_MESSAGE_LENGTH)?; |
| 758 | 731 | ||
| 759 | - match self | 732 | + expect!( |
| 760 | - .request(Request::UpdateMessage { | 733 | + self.request(Request::UpdateMessage { |
| 761 | message_id: message_id.to_string(), | 734 | message_id: message_id.to_string(), |
| 762 | body: body.to_string(), | 735 | body: body.to_string(), |
| 763 | }) | 736 | }) |
| 764 | - .await? | 737 | + .await?, |
| 765 | - { | 738 | + Response::Message |
| 766 | - Response::Message(message) => Ok(message), | 739 | + ) |
| 767 | - _ => Err(Error::Server), | ||
| 768 | - } | ||
| 769 | } | 740 | } |
| 770 | 741 | ||
| 771 | pub async fn forward_messages( | 742 | pub async fn forward_messages( |
| @@ -776,64 +747,50 @@ impl NetworkHandle { | |||
| 776 | ) -> Result<Vec<Message>, Error> { | 747 | ) -> Result<Vec<Message>, Error> { |
| 777 | validate_forward(message_ids.len())?; | 748 | validate_forward(message_ids.len())?; |
| 778 | 749 | ||
| 779 | - match self | 750 | + expect!( |
| 780 | - .request(Request::ForwardMessages { | 751 | + self.request(Request::ForwardMessages { |
| 781 | message_ids, | 752 | message_ids, |
| 782 | community_id: community_id.to_string(), | 753 | community_id: community_id.to_string(), |
| 783 | snippet, | 754 | snippet, |
| 784 | }) | 755 | }) |
| 785 | - .await? | 756 | + .await?, |
| 786 | - { | 757 | + Response::Messages |
| 787 | - Response::Messages(messages) => Ok(messages), | 758 | + ) |
| 788 | - _ => Err(Error::Server), | ||
| 789 | - } | ||
| 790 | } | 759 | } |
| 791 | 760 | ||
| 792 | pub async fn find_user(&self, username: &str) -> Result<User, Error> { | 761 | pub async fn find_user(&self, username: &str) -> Result<User, Error> { |
| 793 | - validate_username(username)?; | 762 | + expect!( |
| 794 | - | 763 | + self.request(Request::FindUser { |
| 795 | - match self | ||
| 796 | - .request(Request::FindUser { | ||
| 797 | username: username.to_string(), | 764 | username: username.to_string(), |
| 798 | }) | 765 | }) |
| 799 | - .await? | 766 | + .await?, |
| 800 | - { | 767 | + Response::User |
| 801 | - Response::User(user) => Ok(user), | 768 | + ) |
| 802 | - _ => Err(Error::Server), | ||
| 803 | - } | ||
| 804 | } | 769 | } |
| 805 | 770 | ||
| 806 | pub async fn open_notes(&self) -> Result<Community, Error> { | 771 | pub async fn open_notes(&self) -> Result<Community, Error> { |
| 807 | - match self.request(Request::OpenNotes).await? { | 772 | + expect!(self.request(Request::OpenNotes).await?, Response::Community) |
| 808 | - Response::Community(community) => Ok(community), | ||
| 809 | - _ => Err(Error::Server), | ||
| 810 | - } | ||
| 811 | } | 773 | } |
| 812 | 774 | ||
| 813 | pub async fn open_direct(&self, user_id: &str) -> Result<Community, Error> { | 775 | pub async fn open_direct(&self, user_id: &str) -> Result<Community, Error> { |
| 814 | - match self | 776 | + expect!( |
| 815 | - .request(Request::OpenDirect { | 777 | + self.request(Request::OpenDirect { |
| 816 | user_id: user_id.to_string(), | 778 | user_id: user_id.to_string(), |
| 817 | }) | 779 | }) |
| 818 | - .await? | 780 | + .await?, |
| 819 | - { | 781 | + Response::Community |
| 820 | - Response::Community(community) => Ok(community), | 782 | + ) |
| 821 | - _ => Err(Error::Server), | ||
| 822 | - } | ||
| 823 | } | 783 | } |
| 824 | 784 | ||
| 825 | pub async fn friends(&self) -> Result<Friends, Error> { | 785 | pub async fn friends(&self) -> Result<Friends, Error> { |
| 826 | - match self.request(Request::Friends).await? { | 786 | + expect!(self.request(Request::Friends).await?, Response::Friends) |
| 827 | - Response::Friends(friends) => Ok(friends), | ||
| 828 | - _ => Err(Error::Server), | ||
| 829 | - } | ||
| 830 | } | 787 | } |
| 831 | 788 | ||
| 832 | pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Error> { | 789 | pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Error> { |
| 833 | - match self.request(Request::ReadPresences).await? { | 790 | + expect!( |
| 834 | - Response::Presences(presences) => Ok(presences), | 791 | + self.request(Request::ReadPresences).await?, |
| 835 | - _ => Err(Error::Server), | 792 | + Response::Presences |
| 836 | - } | 793 | + ) |
| 837 | } | 794 | } |
| 838 | 795 | ||
| 839 | pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> { | 796 | pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> { |
| @@ -870,22 +827,20 @@ impl NetworkHandle { | |||
| 870 | } | 827 | } |
| 871 | 828 | ||
| 872 | pub async fn invitations(&self) -> Result<Vec<Invitation>, Error> { | 829 | pub async fn invitations(&self) -> Result<Vec<Invitation>, Error> { |
| 873 | - match self.request(Request::Invitations).await? { | 830 | + expect!( |
| 874 | - Response::Invitations(invitations) => Ok(invitations), | 831 | + self.request(Request::Invitations).await?, |
| 875 | - _ => Err(Error::Server), | 832 | + Response::Invitations |
| 876 | - } | 833 | + ) |
| 877 | } | 834 | } |
| 878 | 835 | ||
| 879 | pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Error> { | 836 | pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Error> { |
| 880 | - match self | 837 | + expect!( |
| 881 | - .request(Request::AcceptInvitation { | 838 | + self.request(Request::AcceptInvitation { |
| 882 | community_id: community_id.to_string(), | 839 | community_id: community_id.to_string(), |
| 883 | }) | 840 | }) |
| 884 | - .await? | 841 | + .await?, |
| 885 | - { | 842 | + Response::Community |
| 886 | - Response::Community(community) => Ok(community), | 843 | + ) |
| 887 | - _ => Err(Error::Server), | ||
| 888 | - } | ||
| 889 | } | 844 | } |
| 890 | 845 | ||
| 891 | pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Error> { | 846 | pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Error> { |
| @@ -919,15 +874,13 @@ impl NetworkHandle { | |||
| 919 | } | 874 | } |
| 920 | 875 | ||
| 921 | pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Error> { | 876 | pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Error> { |
| 922 | - match self | 877 | + expect!( |
| 923 | - .request(Request::Pins { | 878 | + self.request(Request::Pins { |
| 924 | community_id: community_id.to_string(), | 879 | community_id: community_id.to_string(), |
| 925 | }) | 880 | }) |
| 926 | - .await? | 881 | + .await?, |
| 927 | - { | 882 | + Response::Messages |
| 928 | - Response::Messages(messages) => Ok(messages), | 883 | + ) |
| 929 | - _ => Err(Error::Server), | ||
| 930 | - } | ||
| 931 | } | 884 | } |
| 932 | 885 | ||
| 933 | pub async fn create_poll( | 886 | pub async fn create_poll( |
| @@ -939,18 +892,16 @@ impl NetworkHandle { | |||
| 939 | ) -> Result<Message, Error> { | 892 | ) -> Result<Message, Error> { |
| 940 | validate_poll(question, &options)?; | 893 | validate_poll(question, &options)?; |
| 941 | 894 | ||
| 942 | - match self | 895 | + expect!( |
| 943 | - .request(Request::CreatePoll { | 896 | + self.request(Request::CreatePoll { |
| 944 | community_id: community_id.to_string(), | 897 | community_id: community_id.to_string(), |
| 945 | question: question.to_string(), | 898 | question: question.to_string(), |
| 946 | options, | 899 | options, |
| 947 | multiple, | 900 | multiple, |
| 948 | }) | 901 | }) |
| 949 | - .await? | 902 | + .await?, |
| 950 | - { | 903 | + Response::Message |
| 951 | - Response::Message(message) => Ok(message), | 904 | + ) |
| 952 | - _ => Err(Error::Server), | ||
| 953 | - } | ||
| 954 | } | 905 | } |
| 955 | 906 | ||
| 956 | pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Error> { | 907 | pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Error> { |
| @@ -989,10 +940,10 @@ impl NetworkHandle { | |||
| 989 | } | 940 | } |
| 990 | 941 | ||
| 991 | pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Error> { | 942 | pub async fn reports(&self, status: Option<ReportStatus>) -> Result<Vec<Report>, Error> { |
| 992 | - match self.request(Request::Reports { status }).await? { | 943 | + expect!( |
| 993 | - Response::Reports(reports) => Ok(reports), | 944 | + self.request(Request::Reports { status }).await?, |
| 994 | - _ => Err(Error::Server), | 945 | + Response::Reports |
| 995 | - } | 946 | + ) |
| 996 | } | 947 | } |
| 997 | 948 | ||
| 998 | pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Error> { | 949 | pub async fn handle_report(&self, report_id: &str, status: ReportStatus) -> Result<(), Error> { |
| @@ -1011,19 +962,17 @@ impl NetworkHandle { | |||
| 1011 | after_ms: Option<u64>, | 962 | after_ms: Option<u64>, |
| 1012 | before_ms: Option<u64>, | 963 | before_ms: Option<u64>, |
| 1013 | ) -> Result<Vec<MessageHit>, Error> { | 964 | ) -> Result<Vec<MessageHit>, Error> { |
| 1014 | - match self | 965 | + expect!( |
| 1015 | - .request(Request::SearchMessages { | 966 | + self.request(Request::SearchMessages { |
| 1016 | text, | 967 | text, |
| 1017 | user_id, | 968 | user_id, |
| 1018 | community_id, | 969 | community_id, |
| 1019 | after_ms, | 970 | after_ms, |
| 1020 | before_ms, | 971 | before_ms, |
| 1021 | }) | 972 | }) |
| 1022 | - .await? | 973 | + .await?, |
| 1023 | - { | 974 | + Response::MessageHits |
| 1024 | - Response::MessageHits(hits) => Ok(hits), | 975 | + ) |
| 1025 | - _ => Err(Error::Server), | ||
| 1026 | - } | ||
| 1027 | } | 976 | } |
| 1028 | 977 | ||
| 1029 | pub async fn search_community( | 978 | pub async fn search_community( |
| @@ -1031,13 +980,11 @@ impl NetworkHandle { | |||
| 1031 | community_id: String, | 980 | community_id: String, |
| 1032 | text: String, | 981 | text: String, |
| 1033 | ) -> Result<Vec<MessageHit>, Error> { | 982 | ) -> Result<Vec<MessageHit>, Error> { |
| 1034 | - match self | 983 | + expect!( |
| 1035 | - .request(Request::SearchCommunity { community_id, text }) | 984 | + self.request(Request::SearchCommunity { community_id, text }) |
| 1036 | - .await? | 985 | + .await?, |
| 1037 | - { | 986 | + Response::MessageHits |
| 1038 | - Response::MessageHits(hits) => Ok(hits), | 987 | + ) |
| 1039 | - _ => Err(Error::Server), | ||
| 1040 | - } | ||
| 1041 | } | 988 | } |
| 1042 | 989 | ||
| 1043 | pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Error> { | 990 | pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Error> { |
| @@ -1048,17 +995,11 @@ impl NetworkHandle { | |||
| 1048 | } | 995 | } |
| 1049 | 996 | ||
| 1050 | pub async fn create_backup(&self) -> Result<BackupInfo, Error> { | 997 | pub async fn create_backup(&self) -> Result<BackupInfo, Error> { |
| 1051 | - match self.request(Request::CreateBackup).await? { | 998 | + expect!(self.request(Request::CreateBackup).await?, Response::Backup) |
| 1052 | - Response::Backup(backup) => Ok(backup), | ||
| 1053 | - _ => Err(Error::Server), | ||
| 1054 | - } | ||
| 1055 | } | 999 | } |
| 1056 | 1000 | ||
| 1057 | pub async fn backups(&self) -> Result<Vec<BackupInfo>, Error> { | 1001 | pub async fn backups(&self) -> Result<Vec<BackupInfo>, Error> { |
| 1058 | - match self.request(Request::Backups).await? { | 1002 | + expect!(self.request(Request::Backups).await?, Response::Backups) |
| 1059 | - Response::Backups(backups) => Ok(backups), | ||
| 1060 | - _ => Err(Error::Server), | ||
| 1061 | - } | ||
| 1062 | } | 1003 | } |
| 1063 | 1004 | ||
| 1064 | pub async fn delete_backup(&self, name: &str) -> Result<(), Error> { | 1005 | pub async fn delete_backup(&self, name: &str) -> Result<(), Error> { |
| @@ -1073,16 +1014,14 @@ impl NetworkHandle { | |||
| 1073 | user_id: Option<String>, | 1014 | user_id: Option<String>, |
| 1074 | community_id: Option<String>, | 1015 | community_id: Option<String>, |
| 1075 | ) -> Result<Vec<AttachmentInfo>, Error> { | 1016 | ) -> Result<Vec<AttachmentInfo>, Error> { |
| 1076 | - match self | 1017 | + expect!( |
| 1077 | - .request(Request::AllAttachments { | 1018 | + self.request(Request::AllAttachments { |
| 1078 | user_id, | 1019 | user_id, |
| 1079 | community_id, | 1020 | community_id, |
| 1080 | }) | 1021 | }) |
| 1081 | - .await? | 1022 | + .await?, |
| 1082 | - { | 1023 | + Response::AttachmentInfos |
| 1083 | - Response::AttachmentInfos(infos) => Ok(infos), | 1024 | + ) |
| 1084 | - _ => Err(Error::Server), | ||
| 1085 | - } | ||
| 1086 | } | 1025 | } |
| 1087 | 1026 | ||
| 1088 | pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Error> { | 1027 | pub async fn delete_attachment(&self, attachment_id: &str) -> Result<(), Error> { |
| @@ -1148,23 +1087,18 @@ impl NetworkHandle { | |||
| 1148 | community_id: &str, | 1087 | community_id: &str, |
| 1149 | before: Option<&str>, | 1088 | before: Option<&str>, |
| 1150 | ) -> Result<Vec<Message>, Error> { | 1089 | ) -> Result<Vec<Message>, Error> { |
| 1151 | - match self | 1090 | + expect!( |
| 1152 | - .request(Request::ReadMessages { | 1091 | + self.request(Request::ReadMessages { |
| 1153 | community_id: community_id.to_string(), | 1092 | community_id: community_id.to_string(), |
| 1154 | before: before.map(str::to_string), | 1093 | before: before.map(str::to_string), |
| 1155 | }) | 1094 | }) |
| 1156 | - .await? | 1095 | + .await?, |
| 1157 | - { | 1096 | + Response::Messages |
| 1158 | - Response::Messages(messages) => Ok(messages), | 1097 | + ) |
| 1159 | - _ => Err(Error::Server), | ||
| 1160 | - } | ||
| 1161 | } | 1098 | } |
| 1162 | 1099 | ||
| 1163 | pub async fn unreads(&self) -> Result<Vec<Unread>, Error> { | 1100 | pub async fn unreads(&self) -> Result<Vec<Unread>, Error> { |
| 1164 | - match self.request(Request::Unreads).await? { | 1101 | + expect!(self.request(Request::Unreads).await?, Response::Unreads) |
| 1165 | - Response::Unreads(unreads) => Ok(unreads), | ||
| 1166 | - _ => Err(Error::Server), | ||
| 1167 | - } | ||
| 1168 | } | 1102 | } |
| 1169 | 1103 | ||
| 1170 | pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> { | 1104 | pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> { |
| @@ -1178,24 +1112,22 @@ impl NetworkHandle { | |||
| 1178 | pub async fn update_status(&self, status: &str) -> Result<User, Error> { | 1112 | pub async fn update_status(&self, status: &str) -> Result<User, Error> { |
| 1179 | validate_status(status)?; | 1113 | validate_status(status)?; |
| 1180 | 1114 | ||
| 1181 | - match self | 1115 | + expect!( |
| 1182 | - .request(Request::UpdateStatus { | 1116 | + self.request(Request::UpdateStatus { |
| 1183 | status: status.to_string(), | 1117 | status: status.to_string(), |
| 1184 | }) | 1118 | }) |
| 1185 | - .await? | 1119 | + .await?, |
| 1186 | - { | 1120 | + Response::User |
| 1187 | - Response::User(user) => Ok(user), | 1121 | + ) |
| 1188 | - _ => Err(Error::Server), | ||
| 1189 | - } | ||
| 1190 | } | 1122 | } |
| 1191 | 1123 | ||
| 1192 | pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Error> { | 1124 | pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Error> { |
| 1193 | validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; | 1125 | validate_avatar_size(&bytes, MAXIMUM_AVATAR_BYTES as u64)?; |
| 1194 | 1126 | ||
| 1195 | - match self.request(Request::UpdateAvatar { image: bytes }).await? { | 1127 | + expect!( |
| 1196 | - Response::User(user) => Ok(user), | 1128 | + self.request(Request::UpdateAvatar { image: bytes }).await?, |
| 1197 | - _ => Err(Error::Server), | 1129 | + Response::User |
| 1198 | - } | 1130 | + ) |
| 1199 | } | 1131 | } |
| 1200 | 1132 | ||
| 1201 | pub async fn update_community_avatar( | 1133 | pub async fn update_community_avatar( |
| @@ -1207,47 +1139,38 @@ impl NetworkHandle { | |||
| 1207 | validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; | 1139 | validate_avatar_size(bytes, MAXIMUM_AVATAR_BYTES as u64)?; |
| 1208 | } | 1140 | } |
| 1209 | 1141 | ||
| 1210 | - match self | 1142 | + expect!( |
| 1211 | - .request(Request::UpdateCommunityAvatar { | 1143 | + self.request(Request::UpdateCommunityAvatar { |
| 1212 | community_id: community_id.to_string(), | 1144 | community_id: community_id.to_string(), |
| 1213 | image, | 1145 | image, |
| 1214 | }) | 1146 | }) |
| 1215 | - .await? | 1147 | + .await?, |
| 1216 | - { | 1148 | + Response::Community |
| 1217 | - Response::Community(community) => Ok(community), | 1149 | + ) |
| 1218 | - _ => Err(Error::Server), | ||
| 1219 | - } | ||
| 1220 | } | 1150 | } |
| 1221 | 1151 | ||
| 1222 | pub async fn remove_avatar(&self) -> Result<User, Error> { | 1152 | pub async fn remove_avatar(&self) -> Result<User, Error> { |
| 1223 | - match self.request(Request::RemoveAvatar).await? { | 1153 | + expect!(self.request(Request::RemoveAvatar).await?, Response::User) |
| 1224 | - Response::User(user) => Ok(user), | ||
| 1225 | - _ => Err(Error::Server), | ||
| 1226 | - } | ||
| 1227 | } | 1154 | } |
| 1228 | 1155 | ||
| 1229 | pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Error> { | 1156 | pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Error> { |
| 1230 | - match self | 1157 | + expect!( |
| 1231 | - .request(Request::ReadAvatar { | 1158 | + self.request(Request::ReadAvatar { |
| 1232 | avatar_id: avatar_id.to_string(), | 1159 | avatar_id: avatar_id.to_string(), |
| 1233 | }) | 1160 | }) |
| 1234 | - .await? | 1161 | + .await?, |
| 1235 | - { | 1162 | + Response::Avatar |
| 1236 | - Response::Avatar(bytes) => Ok(bytes), | 1163 | + ) |
| 1237 | - _ => Err(Error::Server), | ||
| 1238 | - } | ||
| 1239 | } | 1164 | } |
| 1240 | 1165 | ||
| 1241 | pub async fn join_voice(&self, community_id: &str) -> Result<Vec<String>, Error> { | 1166 | pub async fn join_voice(&self, community_id: &str) -> Result<Vec<String>, Error> { |
| 1242 | - match self | 1167 | + expect!( |
| 1243 | - .request(Request::JoinVoice { | 1168 | + self.request(Request::JoinVoice { |
| 1244 | community_id: community_id.to_string(), | 1169 | community_id: community_id.to_string(), |
| 1245 | }) | 1170 | }) |
| 1246 | - .await? | 1171 | + .await?, |
| 1247 | - { | 1172 | + Response::Voice |
| 1248 | - Response::Voice(participants) => Ok(participants), | 1173 | + ) |
| 1249 | - _ => Err(Error::Server), | ||
| 1250 | - } | ||
| 1251 | } | 1174 | } |
| 1252 | 1175 | ||
| 1253 | pub async fn typing(&self, community_id: &str) -> Result<(), Error> { | 1176 | pub async fn typing(&self, community_id: &str) -> Result<(), Error> { |
| @@ -1262,34 +1185,30 @@ impl NetworkHandle { | |||
| 1262 | } | 1185 | } |
| 1263 | 1186 | ||
| 1264 | pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> { | 1187 | pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> { |
| 1265 | - match self | 1188 | + expect!( |
| 1266 | - .request(Request::ReadCommunity { | 1189 | + self.request(Request::ReadCommunity { |
| 1267 | community_id: community_id.to_string(), | 1190 | community_id: community_id.to_string(), |
| 1268 | }) | 1191 | }) |
| 1269 | - .await? | 1192 | + .await?, |
| 1270 | - { | 1193 | + Response::Community |
| 1271 | - Response::Community(community) => Ok(community), | 1194 | + ) |
| 1272 | - _ => Err(Error::Server), | ||
| 1273 | - } | ||
| 1274 | } | 1195 | } |
| 1275 | 1196 | ||
| 1276 | pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Error> { | 1197 | pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Error> { |
| 1277 | - match self | 1198 | + expect!( |
| 1278 | - .request(Request::VoiceParticipants { | 1199 | + self.request(Request::VoiceParticipants { |
| 1279 | community_id: community_id.to_string(), | 1200 | community_id: community_id.to_string(), |
| 1280 | }) | 1201 | }) |
| 1281 | - .await? | 1202 | + .await?, |
| 1282 | - { | 1203 | + Response::Voice |
| 1283 | - Response::Voice(participants) => Ok(participants), | 1204 | + ) |
| 1284 | - _ => Err(Error::Server), | ||
| 1285 | - } | ||
| 1286 | } | 1205 | } |
| 1287 | 1206 | ||
| 1288 | pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Error> { | 1207 | pub async fn voice_rooms(&self) -> Result<Vec<VoiceRoom>, Error> { |
| 1289 | - match self.request(Request::VoiceRooms).await? { | 1208 | + expect!( |
| 1290 | - Response::VoiceRooms(rooms) => Ok(rooms), | 1209 | + self.request(Request::VoiceRooms).await?, |
| 1291 | - _ => Err(Error::Server), | 1210 | + Response::VoiceRooms |
| 1292 | - } | 1211 | + ) |
| 1293 | } | 1212 | } |
| 1294 | 1213 | ||
| 1295 | pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> { | 1214 | pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> { |
| @@ -1316,56 +1235,60 @@ impl NetworkHandle { | |||
| 1316 | community_id: &str, | 1235 | community_id: &str, |
| 1317 | enabled: bool, | 1236 | enabled: bool, |
| 1318 | ) -> Result<Community, Error> { | 1237 | ) -> Result<Community, Error> { |
| 1319 | - match self | 1238 | + expect!( |
| 1320 | - .request(Request::SetCommunityVoice { | 1239 | + self.request(Request::SetCommunityVoice { |
| 1321 | community_id: community_id.to_string(), | 1240 | community_id: community_id.to_string(), |
| 1322 | enabled, | 1241 | enabled, |
| 1323 | }) | 1242 | }) |
| 1324 | - .await? | 1243 | + .await?, |
| 1325 | - { | 1244 | + Response::Community |
| 1326 | - Response::Community(community) => Ok(community), | 1245 | + ) |
| 1327 | - _ => Err(Error::Server), | ||
| 1328 | - } | ||
| 1329 | } | 1246 | } |
| 1330 | 1247 | ||
| 1331 | pub fn set_voice_settings(&self, settings: VoiceSettings) { | 1248 | pub fn set_voice_settings(&self, settings: VoiceSettings) { |
| 1332 | - *self.voice_settings.lock().unwrap() = settings.clone(); | 1249 | + *self.shared.voice_settings.lock().unwrap() = settings.clone(); |
| 1333 | 1250 | ||
| 1334 | - if let Some(voice) = self.voice.lock().unwrap().as_mut() { | 1251 | + if let Some(voice) = self.shared.voice.lock().unwrap().as_mut() { |
| 1335 | voice.apply(&settings); | 1252 | voice.apply(&settings); |
| 1336 | } | 1253 | } |
| 1337 | - if let Some(voice) = self.mic_test.lock().unwrap().as_mut() { | 1254 | + if let Some(voice) = self.shared.mic_test.lock().unwrap().as_mut() { |
| 1338 | voice.apply(&settings); | 1255 | voice.apply(&settings); |
| 1339 | } | 1256 | } |
| 1340 | } | 1257 | } |
| 1341 | 1258 | ||
| 1342 | pub fn start_mic_test(&self) { | 1259 | pub fn start_mic_test(&self) { |
| 1343 | - if self.voice.lock().unwrap().is_some() { | 1260 | + if self.shared.voice.lock().unwrap().is_some() { |
| 1344 | return; | 1261 | return; |
| 1345 | } | 1262 | } |
| 1346 | - let settings = self.voice_settings.lock().unwrap().clone(); | 1263 | + let settings = self.shared.voice_settings.lock().unwrap().clone(); |
| 1347 | - *self.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); | 1264 | + *self.shared.mic_test.lock().unwrap() = Some(voice::start(None, &settings)); |
| 1348 | } | 1265 | } |
| 1349 | 1266 | ||
| 1350 | pub fn play_chime(&self) { | 1267 | pub fn play_chime(&self) { |
| 1351 | - voice::play_chime(&self.voice_settings.lock().unwrap()); | 1268 | + voice::play_chime(&self.shared.voice_settings.lock().unwrap()); |
| 1352 | } | 1269 | } |
| 1353 | 1270 | ||
| 1354 | pub fn play_notification(&self) { | 1271 | pub fn play_notification(&self) { |
| 1355 | - voice::play_yumush(&self.voice_settings.lock().unwrap()); | 1272 | + voice::play_yumush(&self.shared.voice_settings.lock().unwrap()); |
| 1356 | } | 1273 | } |
| 1357 | 1274 | ||
| 1358 | pub fn play_ring(&self) { | 1275 | pub fn play_ring(&self) { |
| 1359 | - voice::play_ring(&self.voice_settings.lock().unwrap()); | 1276 | + voice::play_ring(&self.shared.voice_settings.lock().unwrap()); |
| 1360 | } | 1277 | } |
| 1361 | 1278 | ||
| 1362 | pub fn stop_mic_test(&self) { | 1279 | pub fn stop_mic_test(&self) { |
| 1363 | - self.mic_test.lock().unwrap().take(); | 1280 | + self.shared.mic_test.lock().unwrap().take(); |
| 1364 | } | 1281 | } |
| 1365 | 1282 | ||
| 1366 | pub fn voice_level_db(&self) -> Option<f32> { | 1283 | pub fn voice_level_db(&self) -> Option<f32> { |
| 1367 | - self.with_voice(Voice::level_db) | 1284 | + self.with_voice(Voice::level_db).or_else(|| { |
| 1368 | - .or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db)) | 1285 | + self.shared |
| 1286 | + .mic_test | ||
| 1287 | + .lock() | ||
| 1288 | + .unwrap() | ||
| 1289 | + .as_ref() | ||
| 1290 | + .map(Voice::level_db) | ||
| 1291 | + }) | ||
| 1369 | } | 1292 | } |
| 1370 | 1293 | ||
| 1371 | pub fn voice_sample(&self) -> Option<VoiceSample> { | 1294 | pub fn voice_sample(&self) -> Option<VoiceSample> { |
| @@ -1385,7 +1308,7 @@ impl NetworkHandle { | |||
| 1385 | } | 1308 | } |
| 1386 | 1309 | ||
| 1387 | pub fn levels(&self) -> Levels { | 1310 | pub fn levels(&self) -> Levels { |
| 1388 | - let share = self.share.lock().unwrap(); | 1311 | + let share = self.shared.share.lock().unwrap(); |
| 1389 | Levels { | 1312 | Levels { |
| 1390 | voice: self.with_voice(Voice::levels).unwrap_or_default(), | 1313 | voice: self.with_voice(Voice::levels).unwrap_or_default(), |
| 1391 | watching: share | 1314 | watching: share |
| @@ -1407,7 +1330,7 @@ impl NetworkHandle { | |||
| 1407 | } | 1330 | } |
| 1408 | 1331 | ||
| 1409 | async fn start(&self, kind: Kind) -> Result<(), Error> { | 1332 | async fn start(&self, kind: Kind) -> Result<(), Error> { |
| 1410 | - let settings = self.share_settings.lock().unwrap().clone(); | 1333 | + let settings = self.shared.share_settings.lock().unwrap().clone(); |
| 1411 | self.ask(|reply| Command::StartShare { | 1334 | self.ask(|reply| Command::StartShare { |
| 1412 | kind, | 1335 | kind, |
| 1413 | settings, | 1336 | settings, |
| @@ -1417,7 +1340,7 @@ impl NetworkHandle { | |||
| 1417 | } | 1340 | } |
| 1418 | 1341 | ||
| 1419 | pub async fn update_share(&self) -> Result<(), Error> { | 1342 | pub async fn update_share(&self) -> Result<(), Error> { |
| 1420 | - let settings = self.share_settings.lock().unwrap().clone(); | 1343 | + let settings = self.shared.share_settings.lock().unwrap().clone(); |
| 1421 | self.ask(|reply| Command::UpdateShare { settings, reply }) | 1344 | self.ask(|reply| Command::UpdateShare { settings, reply }) |
| 1422 | .await | 1345 | .await |
| 1423 | } | 1346 | } |
| @@ -1432,14 +1355,15 @@ impl NetworkHandle { | |||
| 1432 | 1355 | ||
| 1433 | async fn stop(&self, kind: Kind) -> Result<(), Error> { | 1356 | async fn stop(&self, kind: Kind) -> Result<(), Error> { |
| 1434 | let result = self.done(Request::StopShare { kind }).await; | 1357 | let result = self.done(Request::StopShare { kind }).await; |
| 1435 | - let mut share = self.share.lock().unwrap(); | 1358 | + let mut share = self.shared.share.lock().unwrap(); |
| 1436 | share.sharing.remove(&kind); | 1359 | share.sharing.remove(&kind); |
| 1437 | share.sources.remove(&kind); | 1360 | share.sources.remove(&kind); |
| 1438 | result | 1361 | result |
| 1439 | } | 1362 | } |
| 1440 | 1363 | ||
| 1441 | pub fn sharing(&self) -> bool { | 1364 | pub fn sharing(&self) -> bool { |
| 1442 | - self.share | 1365 | + self.shared |
| 1366 | + .share | ||
| 1443 | .lock() | 1367 | .lock() |
| 1444 | .unwrap() | 1368 | .unwrap() |
| 1445 | .sharing | 1369 | .sharing |
| @@ -1447,7 +1371,8 @@ impl NetworkHandle { | |||
| 1447 | } | 1371 | } |
| 1448 | 1372 | ||
| 1449 | pub fn camera_on(&self) -> bool { | 1373 | pub fn camera_on(&self) -> bool { |
| 1450 | - self.share | 1374 | + self.shared |
| 1375 | + .share | ||
| 1451 | .lock() | 1376 | .lock() |
| 1452 | .unwrap() | 1377 | .unwrap() |
| 1453 | .sharing | 1378 | .sharing |
| @@ -1455,7 +1380,8 @@ impl NetworkHandle { | |||
| 1455 | } | 1380 | } |
| 1456 | 1381 | ||
| 1457 | pub fn share_source(&self) -> Option<Source> { | 1382 | pub fn share_source(&self) -> Option<Source> { |
| 1458 | - self.share | 1383 | + self.shared |
| 1384 | + .share | ||
| 1459 | .lock() | 1385 | .lock() |
| 1460 | .unwrap() | 1386 | .unwrap() |
| 1461 | .sources | 1387 | .sources |
| @@ -1464,15 +1390,13 @@ impl NetworkHandle { | |||
| 1464 | } | 1390 | } |
| 1465 | 1391 | ||
| 1466 | pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Error> { | 1392 | pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Error> { |
| 1467 | - match self | 1393 | + expect!( |
| 1468 | - .request(Request::Shares { | 1394 | + self.request(Request::Shares { |
| 1469 | community_id: community_id.to_string(), | 1395 | community_id: community_id.to_string(), |
| 1470 | }) | 1396 | }) |
| 1471 | - .await? | 1397 | + .await?, |
| 1472 | - { | 1398 | + Response::Shares |
| 1473 | - Response::Shares(shares) => Ok(shares), | 1399 | + ) |
| 1474 | - _ => Err(Error::Server), | ||
| 1475 | - } | ||
| 1476 | } | 1400 | } |
| 1477 | 1401 | ||
| 1478 | pub async fn watch_share( | 1402 | pub async fn watch_share( |
| @@ -1481,15 +1405,13 @@ impl NetworkHandle { | |||
| 1481 | kind: Kind, | 1405 | kind: Kind, |
| 1482 | watch: WatchQuality, | 1406 | watch: WatchQuality, |
| 1483 | ) -> Result<(), Error> { | 1407 | ) -> Result<(), Error> { |
| 1484 | - let quality = match watch { | 1408 | + let volume = self.shared.share_settings.lock().unwrap().volume; |
| 1485 | - WatchQuality::Fixed(quality) => quality, | 1409 | + let choice = self.shared.voice_settings.lock().unwrap().choice.clone(); |
| 1486 | - WatchQuality::Auto => SHARE_QUALITY, | ||
| 1487 | - }; | ||
| 1488 | - let volume = self.share_settings.lock().unwrap().volume; | ||
| 1489 | - let choice = self.voice_settings.lock().unwrap().choice.clone(); | ||
| 1490 | let key = (user_id.to_string(), kind); | 1410 | let key = (user_id.to_string(), kind); |
| 1491 | let watching = Watching::new(kind, watch, volume, choice); | 1411 | let watching = Watching::new(kind, watch, volume, choice); |
| 1492 | - self.share | 1412 | + let quality = watching.wanted(); |
| 1413 | + self.shared | ||
| 1414 | + .share | ||
| 1493 | .lock() | 1415 | .lock() |
| 1494 | .unwrap() | 1416 | .unwrap() |
| 1495 | .watching | 1417 | .watching |
| @@ -1504,13 +1426,14 @@ impl NetworkHandle { | |||
| 1504 | }) | 1426 | }) |
| 1505 | .await; | 1427 | .await; |
| 1506 | if result.is_err() { | 1428 | if result.is_err() { |
| 1507 | - self.share.lock().unwrap().watching.remove(&key); | 1429 | + self.shared.share.lock().unwrap().watching.remove(&key); |
| 1508 | } | 1430 | } |
| 1509 | result | 1431 | result |
| 1510 | } | 1432 | } |
| 1511 | 1433 | ||
| 1512 | pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Error> { | 1434 | pub async fn unwatch_share(&self, user_id: &str, kind: Kind) -> Result<(), Error> { |
| 1513 | - self.share | 1435 | + self.shared |
| 1436 | + .share | ||
| 1514 | .lock() | 1437 | .lock() |
| 1515 | .unwrap() | 1438 | .unwrap() |
| 1516 | .watching | 1439 | .watching |
| @@ -1524,6 +1447,7 @@ impl NetworkHandle { | |||
| 1524 | 1447 | ||
| 1525 | pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { | 1448 | pub fn set_watch_quality(&self, user_id: &str, kind: Kind, quality: WatchQuality) { |
| 1526 | if let Some(watching) = self | 1449 | if let Some(watching) = self |
| 1450 | + .shared | ||
| 1527 | .share | 1451 | .share |
| 1528 | .lock() | 1452 | .lock() |
| 1529 | .unwrap() | 1453 | .unwrap() |
| @@ -1535,7 +1459,7 @@ impl NetworkHandle { | |||
| 1535 | } | 1459 | } |
| 1536 | 1460 | ||
| 1537 | pub fn share_sample(&self) -> ShareSample { | 1461 | pub fn share_sample(&self) -> ShareSample { |
| 1538 | - let mut share = self.share.lock().unwrap(); | 1462 | + let mut share = self.shared.share.lock().unwrap(); |
| 1539 | ShareSample { | 1463 | ShareSample { |
| 1540 | sending: share | 1464 | sending: share |
| 1541 | .sharing | 1465 | .sharing |
| @@ -1552,7 +1476,8 @@ impl NetworkHandle { | |||
| 1552 | } | 1476 | } |
| 1553 | 1477 | ||
| 1554 | pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> { | 1478 | pub fn share_frame(&self, user_id: &str, kind: Kind) -> Option<crate::media::Frame> { |
| 1555 | - self.share | 1479 | + self.shared |
| 1480 | + .share | ||
| 1556 | .lock() | 1481 | .lock() |
| 1557 | .unwrap() | 1482 | .unwrap() |
| 1558 | .watching | 1483 | .watching |
| @@ -1563,12 +1488,13 @@ impl NetworkHandle { | |||
| 1563 | pub fn set_share_settings(&self, settings: ShareSettings) -> bool { | 1488 | pub fn set_share_settings(&self, settings: ShareSettings) -> bool { |
| 1564 | let changed = self.sharing() | 1489 | let changed = self.sharing() |
| 1565 | && self | 1490 | && self |
| 1491 | + .shared | ||
| 1566 | .share_settings | 1492 | .share_settings |
| 1567 | .lock() | 1493 | .lock() |
| 1568 | .unwrap() | 1494 | .unwrap() |
| 1569 | .encoding_differs(&settings); | 1495 | .encoding_differs(&settings); |
| 1570 | - *self.share_settings.lock().unwrap() = settings.clone(); | 1496 | + *self.shared.share_settings.lock().unwrap() = settings.clone(); |
| 1571 | - for ((_, kind), watching) in self.share.lock().unwrap().watching.iter_mut() { | 1497 | + for ((_, kind), watching) in self.shared.share.lock().unwrap().watching.iter_mut() { |
| 1572 | if *kind == Kind::Screen { | 1498 | if *kind == Kind::Screen { |
| 1573 | watching.set_volume(settings.volume); | 1499 | watching.set_volume(settings.volume); |
| 1574 | watching.set_quality(settings.watch); | 1500 | watching.set_quality(settings.watch); |
| @@ -1585,33 +1511,18 @@ impl NetworkHandle { | |||
| 1585 | pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) { | 1511 | pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) { |
| 1586 | let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); | 1512 | let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); |
| 1587 | let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); | 1513 | let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); |
| 1588 | - let voice: SharedVoice = Arc::new(Mutex::new(None)); | 1514 | + let shared = Shared::default(); |
| 1589 | - let mic_test: SharedVoice = Arc::new(Mutex::new(None)); | ||
| 1590 | - let voice_settings: SharedSettings = Arc::new(Mutex::new(VoiceSettings::default())); | ||
| 1591 | - let share: SharedShare = Arc::new(Mutex::new(Share::default())); | ||
| 1592 | - let share_settings: SharedShareSettings = Arc::new(Mutex::new(ShareSettings::default())); | ||
| 1593 | 1515 | ||
| 1594 | std::thread::Builder::new() | 1516 | std::thread::Builder::new() |
| 1595 | .name("network".to_string()) | 1517 | .name("network".to_string()) |
| 1596 | .spawn({ | 1518 | .spawn({ |
| 1597 | - let voice = voice.clone(); | 1519 | + let shared = shared.clone(); |
| 1598 | - let mic_test = mic_test.clone(); | ||
| 1599 | - let voice_settings = voice_settings.clone(); | ||
| 1600 | - let share = share.clone(); | ||
| 1601 | move || { | 1520 | move || { |
| 1602 | tokio::runtime::Builder::new_current_thread() | 1521 | tokio::runtime::Builder::new_current_thread() |
| 1603 | .enable_all() | 1522 | .enable_all() |
| 1604 | .build() | 1523 | .build() |
| 1605 | .expect("network runtime") | 1524 | .expect("network runtime") |
| 1606 | - .block_on(actor( | 1525 | + .block_on(actor(client_config, command_receiver, event_sender, shared)); |
| 1607 | - client_config, | ||
| 1608 | - command_receiver, | ||
| 1609 | - event_sender, | ||
| 1610 | - voice, | ||
| 1611 | - mic_test, | ||
| 1612 | - voice_settings, | ||
| 1613 | - share, | ||
| 1614 | - )); | ||
| 1615 | } | 1526 | } |
| 1616 | }) | 1527 | }) |
| 1617 | .expect("network thread"); | 1528 | .expect("network thread"); |
| @@ -1619,11 +1530,7 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw | |||
| 1619 | ( | 1530 | ( |
| 1620 | NetworkHandle { | 1531 | NetworkHandle { |
| 1621 | command_sender, | 1532 | command_sender, |
| 1622 | - voice, | 1533 | + shared, |
| 1623 | - mic_test, | ||
| 1624 | - voice_settings, | ||
| 1625 | - share, | ||
| 1626 | - share_settings, | ||
| 1627 | }, | 1534 | }, |
| 1628 | event_receiver, | 1535 | event_receiver, |
| 1629 | ) | 1536 | ) |
| @@ -1738,6 +1645,14 @@ async fn send(connection: &quinn::Connection, request: &Request) -> Result<Respo | |||
| 1738 | send_request(request, send_stream, receive_stream).await | 1645 | send_request(request, send_stream, receive_stream).await |
| 1739 | } | 1646 | } |
| 1740 | 1647 | ||
| 1648 | +async fn done(connection: &quinn::Connection, request: Request) -> Result<(), Error> { | ||
| 1649 | + match send(connection, &request).await? { | ||
| 1650 | + Response::Done => Ok(()), | ||
| 1651 | + Response::Error(error) => Err(error), | ||
| 1652 | + _ => Err(Error::Server), | ||
| 1653 | + } | ||
| 1654 | +} | ||
| 1655 | + | ||
| 1741 | async fn send_body( | 1656 | async fn send_body( |
| 1742 | send_stream: &mut quinn::SendStream, | 1657 | send_stream: &mut quinn::SendStream, |
| 1743 | file: &mut tokio::fs::File, | 1658 | file: &mut tokio::fs::File, |
| @@ -1843,26 +1758,22 @@ async fn download( | |||
| 1843 | Ok(bytes) | 1758 | Ok(bytes) |
| 1844 | } | 1759 | } |
| 1845 | 1760 | ||
| 1846 | -async fn dispatch( | 1761 | +fn answer<T: Send + 'static>( |
| 1847 | - connection: quinn::Connection, | 1762 | + reply: oneshot::Sender<Result<T, Error>>, |
| 1848 | - request: Request, | 1763 | + work: impl Future<Output = Result<T, Error>> + Send + 'static, |
| 1849 | - reply: oneshot::Sender<Result<Response, Error>>, | ||
| 1850 | ) { | 1764 | ) { |
| 1851 | - let _ = reply.send(send(&connection, &request).await); | 1765 | + tokio::spawn(async move { |
| 1766 | + let _ = reply.send(work.await); | ||
| 1767 | + }); | ||
| 1852 | } | 1768 | } |
| 1853 | 1769 | ||
| 1854 | async fn actor( | 1770 | async fn actor( |
| 1855 | client_config: ClientConfig, | 1771 | client_config: ClientConfig, |
| 1856 | mut command_receiver: mpsc::Receiver<Command>, | 1772 | mut command_receiver: mpsc::Receiver<Command>, |
| 1857 | event_sender: mpsc::Sender<NetworkEvent>, | 1773 | event_sender: mpsc::Sender<NetworkEvent>, |
| 1858 | - voice: SharedVoice, | 1774 | + shared: Shared, |
| 1859 | - mic_test: SharedVoice, | ||
| 1860 | - voice_settings: SharedSettings, | ||
| 1861 | - share: SharedShare, | ||
| 1862 | ) { | 1775 | ) { |
| 1863 | let mut token: Option<String> = None; | 1776 | let mut token: Option<String> = None; |
| 1864 | - let mut token_epoch = 0; | ||
| 1865 | - let (token_sender, mut token_receiver) = mpsc::channel(CHANNEL_SIZE); | ||
| 1866 | 'session: loop { | 1777 | 'session: loop { |
| 1867 | let connection = loop { | 1778 | let connection = loop { |
| 1868 | match connect(&client_config).await { | 1779 | match connect(&client_config).await { |
| @@ -1887,8 +1798,13 @@ async fn actor( | |||
| 1887 | let request = Request::Resume { token: stored }; | 1798 | let request = Request::Resume { token: stored }; |
| 1888 | match send(&connection, &request).await { | 1799 | match send(&connection, &request).await { |
| 1889 | Ok(Response::Session { token: resumed, .. }) => token = Some(resumed), | 1800 | Ok(Response::Session { token: resumed, .. }) => token = Some(resumed), |
| 1890 | - _ => { | 1801 | + Err(error) => { |
| 1891 | - warn!("session resume failed"); | 1802 | + warn!("session resume failed: {error}"); |
| 1803 | + tokio::time::sleep(RECONNECT_DELAY).await; | ||
| 1804 | + continue 'session; | ||
| 1805 | + } | ||
| 1806 | + Ok(_) => { | ||
| 1807 | + warn!("session resume rejected"); | ||
| 1892 | token = None; | 1808 | token = None; |
| 1893 | 1809 | ||
| 1894 | if event_sender.send(NetworkEvent::SessionLost).await.is_err() { | 1810 | if event_sender.send(NetworkEvent::SessionLost).await.is_err() { |
| @@ -1906,13 +1822,9 @@ async fn actor( | |||
| 1906 | tokio::spawn(event_receive_loop( | 1822 | tokio::spawn(event_receive_loop( |
| 1907 | connection.clone(), | 1823 | connection.clone(), |
| 1908 | event_sender.clone(), | 1824 | event_sender.clone(), |
| 1909 | - share.clone(), | 1825 | + shared.share.clone(), |
| 1910 | - )); | ||
| 1911 | - tokio::spawn(datagram_receive_loop( | ||
| 1912 | - connection.clone(), | ||
| 1913 | - voice.clone(), | ||
| 1914 | - share.clone(), | ||
| 1915 | )); | 1826 | )); |
| 1827 | + tokio::spawn(datagram_receive_loop(connection.clone(), shared.clone())); | ||
| 1916 | let mut ticker = tokio::time::interval(SHARE_TICK); | 1828 | let mut ticker = tokio::time::interval(SHARE_TICK); |
| 1917 | 1829 | ||
| 1918 | loop { | 1830 | loop { |
| @@ -1920,103 +1832,79 @@ async fn actor( | |||
| 1920 | command = command_receiver.recv() => match command { | 1832 | command = command_receiver.recv() => match command { |
| 1921 | Some(Command::Request { request, reply }) => match &request { | 1833 | Some(Command::Request { request, reply }) => match &request { |
| 1922 | Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { | 1834 | Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { |
| 1923 | - voice.lock().unwrap().take(); | 1835 | + hang_up(&shared); |
| 1924 | - Share::clear(&share); | ||
| 1925 | - let token_sender = token_sender.clone(); | ||
| 1926 | - let epoch = token_epoch; | ||
| 1927 | - let connection = connection.clone(); | ||
| 1928 | - | ||
| 1929 | - tokio::spawn(async move { | ||
| 1930 | - let response = send(&connection, &request).await; | ||
| 1931 | - if let Ok(Response::Session { token: session_token, .. }) = &response { | ||
| 1932 | - let _ = token_sender.send((epoch, session_token.clone())).await; | ||
| 1933 | - } | ||
| 1934 | 1836 | ||
| 1935 | - let _ = reply.send(response); | 1837 | + let response = send(&connection, &request).await; |
| 1936 | - }); | 1838 | + if let Ok(Response::Session { token: session_token, .. }) = &response { |
| 1839 | + token = Some(session_token.clone()); | ||
| 1840 | + } | ||
| 1841 | + let _ = reply.send(response); | ||
| 1937 | } | 1842 | } |
| 1938 | Request::Logout | Request::Detach => { | 1843 | Request::Logout | Request::Detach => { |
| 1939 | token = None; | 1844 | token = None; |
| 1940 | - token_epoch += 1; | 1845 | + hang_up(&shared); |
| 1941 | - voice.lock().unwrap().take(); | ||
| 1942 | - Share::clear(&share); | ||
| 1943 | 1846 | ||
| 1944 | - tokio::spawn(dispatch(connection.clone(), request, reply)); | 1847 | + let connection = connection.clone(); |
| 1848 | + answer(reply, async move { send(&connection, &request).await }); | ||
| 1945 | } | 1849 | } |
| 1946 | Request::JoinVoice { .. } => { | 1850 | Request::JoinVoice { .. } => { |
| 1947 | - let voice = voice.clone(); | 1851 | + let shared = shared.clone(); |
| 1948 | - let mic_test = mic_test.clone(); | 1852 | + let settings = shared.voice_settings.lock().unwrap().clone(); |
| 1949 | - let settings = voice_settings.lock().unwrap().clone(); | ||
| 1950 | let connection = connection.clone(); | 1853 | let connection = connection.clone(); |
| 1951 | 1854 | ||
| 1952 | - tokio::spawn(async move { | 1855 | + answer(reply, async move { |
| 1953 | let response = send(&connection, &request).await; | 1856 | let response = send(&connection, &request).await; |
| 1954 | if let Ok(Response::Voice(_)) = &response { | 1857 | if let Ok(Response::Voice(_)) = &response { |
| 1955 | - mic_test.lock().unwrap().take(); | 1858 | + shared.mic_test.lock().unwrap().take(); |
| 1956 | - *voice.lock().unwrap() = | 1859 | + *shared.voice.lock().unwrap() = |
| 1957 | Some(voice::start(Some(connection), &settings)); | 1860 | Some(voice::start(Some(connection), &settings)); |
| 1958 | } | 1861 | } |
| 1959 | - | 1862 | + response |
| 1960 | - let _ = reply.send(response); | ||
| 1961 | }); | 1863 | }); |
| 1962 | } | 1864 | } |
| 1963 | Request::LeaveVoice => { | 1865 | Request::LeaveVoice => { |
| 1964 | - voice.lock().unwrap().take(); | 1866 | + hang_up(&shared); |
| 1965 | - Share::clear(&share); | ||
| 1966 | 1867 | ||
| 1967 | - tokio::spawn(dispatch(connection.clone(), request, reply)); | 1868 | + let connection = connection.clone(); |
| 1869 | + answer(reply, async move { send(&connection, &request).await }); | ||
| 1968 | } | 1870 | } |
| 1969 | _ => { | 1871 | _ => { |
| 1970 | - tokio::spawn(dispatch(connection.clone(), request, reply)); | 1872 | + let connection = connection.clone(); |
| 1873 | + answer(reply, async move { send(&connection, &request).await }); | ||
| 1971 | } | 1874 | } |
| 1972 | }, | 1875 | }, |
| 1973 | Some(Command::StartShare { kind, settings, reply }) => { | 1876 | Some(Command::StartShare { kind, settings, reply }) => { |
| 1974 | let connection = connection.clone(); | 1877 | let connection = connection.clone(); |
| 1975 | - let share = share.clone(); | 1878 | + let share = shared.share.clone(); |
| 1976 | 1879 | ||
| 1977 | - tokio::spawn(async move { | 1880 | + answer(reply, async move { start_share(&connection, &share, kind, &settings).await }); |
| 1978 | - let _ = reply.send(start_share(&connection, &share, kind, &settings).await); | ||
| 1979 | - }); | ||
| 1980 | } | 1881 | } |
| 1981 | Some(Command::UpdateShare { settings, reply }) => { | 1882 | Some(Command::UpdateShare { settings, reply }) => { |
| 1982 | let connection = connection.clone(); | 1883 | let connection = connection.clone(); |
| 1983 | - let share = share.clone(); | 1884 | + let share = shared.share.clone(); |
| 1984 | 1885 | ||
| 1985 | - tokio::spawn(async move { | 1886 | + answer(reply, async move { update_share(&connection, &share, &settings).await }); |
| 1986 | - let _ = reply.send(update_share(&connection, &share, &settings).await); | ||
| 1987 | - }); | ||
| 1988 | } | 1887 | } |
| 1989 | Some(Command::Upload { community_id, path, maximum, reply }) => { | 1888 | Some(Command::Upload { community_id, path, maximum, reply }) => { |
| 1990 | let connection = connection.clone(); | 1889 | let connection = connection.clone(); |
| 1991 | 1890 | ||
| 1992 | - tokio::spawn(async move { | 1891 | + answer(reply, async move { upload(&connection, &community_id, &path, maximum).await }); |
| 1993 | - let _ = reply.send(upload(&connection, &community_id, &path, maximum).await); | ||
| 1994 | - }); | ||
| 1995 | } | 1892 | } |
| 1996 | Some(Command::Download { attachment_id, thumbnail, reply }) => { | 1893 | Some(Command::Download { attachment_id, thumbnail, reply }) => { |
| 1997 | let connection = connection.clone(); | 1894 | let connection = connection.clone(); |
| 1998 | 1895 | ||
| 1999 | - tokio::spawn(async move { | 1896 | + answer(reply, async move { download(&connection, &attachment_id, thumbnail).await }); |
| 2000 | - let _ = reply.send(download(&connection, &attachment_id, thumbnail).await); | ||
| 2001 | - }); | ||
| 2002 | } | 1897 | } |
| 2003 | Some(Command::BackupDownload { name, path, reply }) => { | 1898 | Some(Command::BackupDownload { name, path, reply }) => { |
| 2004 | let connection = connection.clone(); | 1899 | let connection = connection.clone(); |
| 2005 | 1900 | ||
| 2006 | - tokio::spawn(async move { | 1901 | + answer(reply, async move { backup_download(&connection, &name, &path).await }); |
| 2007 | - let _ = reply.send(backup_download(&connection, &name, &path).await); | ||
| 2008 | - }); | ||
| 2009 | } | 1902 | } |
| 2010 | None => break 'session, | 1903 | None => break 'session, |
| 2011 | }, | 1904 | }, |
| 2012 | - Some((epoch, session_token)) = token_receiver.recv() => { | ||
| 2013 | - if epoch == token_epoch { | ||
| 2014 | - token = Some(session_token); | ||
| 2015 | - } | ||
| 2016 | - } | ||
| 2017 | 1905 | ||
| 2018 | _ = ticker.tick() => { | 1906 | _ = ticker.tick() => { |
| 2019 | - let requests = share.lock().unwrap().ticks(); | 1907 | + let requests = shared.share.lock().unwrap().ticks(); |
| 2020 | for request in requests { | 1908 | for request in requests { |
| 2021 | let connection = connection.clone(); | 1909 | let connection = connection.clone(); |
| 2022 | tokio::spawn(async move { | 1910 | tokio::spawn(async move { |
| @@ -2027,8 +1915,7 @@ async fn actor( | |||
| 2027 | 1915 | ||
| 2028 | error = connection.closed() => { | 1916 | error = connection.closed() => { |
| 2029 | warn!("disconnected: {error}"); | 1917 | warn!("disconnected: {error}"); |
| 2030 | - voice.lock().unwrap().take(); | 1918 | + hang_up(&shared); |
| 2031 | - Share::clear(&share); | ||
| 2032 | 1919 | ||
| 2033 | if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { | 1920 | if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { |
| 2034 | return; | 1921 | return; |
| @@ -2066,11 +1953,7 @@ async fn start_share( | |||
| 2066 | share.sources.insert(kind, source.clone()); | 1953 | share.sources.insert(kind, source.clone()); |
| 2067 | } | 1954 | } |
| 2068 | 1955 | ||
| 2069 | - let result = match send(connection, &Request::StartShare { kind, source }).await { | 1956 | + let result = done(connection, Request::StartShare { kind, source }).await; |
| 2070 | - Ok(Response::Done) => Ok(()), | ||
| 2071 | - Ok(_) => Err(Error::Server), | ||
| 2072 | - Err(error) => Err(error), | ||
| 2073 | - }; | ||
| 2074 | if result.is_err() { | 1957 | if result.is_err() { |
| 2075 | let mut share = share.lock().unwrap(); | 1958 | let mut share = share.lock().unwrap(); |
| 2076 | share.sharing.remove(&kind); | 1959 | share.sharing.remove(&kind); |
| @@ -2104,19 +1987,14 @@ async fn update_share( | |||
| 2104 | .sources | 1987 | .sources |
| 2105 | .insert(Kind::Screen, source.clone()); | 1988 | .insert(Kind::Screen, source.clone()); |
| 2106 | 1989 | ||
| 2107 | - match send( | 1990 | + done( |
| 2108 | connection, | 1991 | connection, |
| 2109 | - &Request::StartShare { | 1992 | + Request::StartShare { |
| 2110 | kind: Kind::Screen, | 1993 | kind: Kind::Screen, |
| 2111 | source, | 1994 | source, |
| 2112 | }, | 1995 | }, |
| 2113 | ) | 1996 | ) |
| 2114 | .await | 1997 | .await |
| 2115 | - { | ||
| 2116 | - Ok(Response::Done) => Ok(()), | ||
| 2117 | - Ok(_) => Err(Error::Server), | ||
| 2118 | - Err(error) => Err(error), | ||
| 2119 | - } | ||
| 2120 | } | 1998 | } |
| 2121 | 1999 | ||
| 2122 | async fn event_receive_loop( | 2000 | async fn event_receive_loop( |
| @@ -2140,18 +2018,14 @@ async fn event_receive_loop( | |||
| 2140 | } | 2018 | } |
| 2141 | } | 2019 | } |
| 2142 | 2020 | ||
| 2143 | -async fn datagram_receive_loop( | 2021 | +async fn datagram_receive_loop(connection: quinn::Connection, shared: Shared) { |
| 2144 | - connection: quinn::Connection, | ||
| 2145 | - voice: SharedVoice, | ||
| 2146 | - share: SharedShare, | ||
| 2147 | -) { | ||
| 2148 | let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") | 2022 | let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") |
| 2149 | .ok() | 2023 | .ok() |
| 2150 | .and_then(|value| value.parse().ok()) | 2024 | .and_then(|value| value.parse().ok()) |
| 2151 | .unwrap_or(0); | 2025 | .unwrap_or(0); |
| 2152 | let mut received: u64 = 0; | 2026 | let mut received: u64 = 0; |
| 2153 | while let Ok(datagram) = connection.read_datagram().await { | 2027 | while let Ok(datagram) = connection.read_datagram().await { |
| 2154 | - if let Some(voice) = voice.lock().unwrap().as_ref() { | 2028 | + if let Some(voice) = shared.voice.lock().unwrap().as_ref() { |
| 2155 | voice.receive(&datagram); | 2029 | voice.receive(&datagram); |
| 2156 | } | 2030 | } |
| 2157 | if let Some((user_id, packet)) = decode_relay(&datagram) { | 2031 | if let Some((user_id, packet)) = decode_relay(&datagram) { |
| @@ -2165,7 +2039,7 @@ async fn datagram_receive_loop( | |||
| 2165 | Datagram::Video(fragment) => fragment.kind, | 2039 | Datagram::Video(fragment) => fragment.kind, |
| 2166 | _ => Kind::Screen, | 2040 | _ => Kind::Screen, |
| 2167 | }; | 2041 | }; |
| 2168 | - if let Some(watching) = share.lock().unwrap().watching.get(&(user_id, kind)) { | 2042 | + if let Some(watching) = shared.share.lock().unwrap().watching.get(&(user_id, kind)) { |
| 2169 | watching.receive(packet); | 2043 | watching.receive(packet); |
| 2170 | } | 2044 | } |
| 2171 | } | 2045 | } |
crates/client/src/settings.rsmodified+32 -34
| @@ -1,4 +1,4 @@ | |||
| 1 | -use std::{collections::BTreeMap, fmt::Display, fs, ops::RangeInclusive}; | 1 | +use std::{collections::BTreeMap, fmt::Display, ops::RangeInclusive}; |
| 2 | 2 | ||
| 3 | use common::{ | 3 | use common::{ |
| 4 | config::Config, | 4 | config::Config, |
| @@ -10,12 +10,12 @@ use gpui_kit::{ | |||
| 10 | component::{Theme, ThemeMode}, | 10 | component::{Theme, ThemeMode}, |
| 11 | px, | 11 | px, |
| 12 | }; | 12 | }; |
| 13 | -use tracing::warn; | ||
| 14 | 13 | ||
| 15 | use crate::{ | 14 | use crate::{ |
| 16 | - config_file, | 15 | + read_config, |
| 17 | share::{audio::AudioMode, encode::capabilities, session::WatchQuality}, | 16 | share::{audio::AudioMode, encode::capabilities, session::WatchQuality}, |
| 18 | voice::audio::Choice, | 17 | voice::audio::Choice, |
| 18 | + write_config, | ||
| 19 | }; | 19 | }; |
| 20 | 20 | ||
| 21 | pub const SHARE_QUALITY: Quality = Quality { | 21 | pub const SHARE_QUALITY: Quality = Quality { |
| @@ -197,6 +197,18 @@ pub struct Settings { | |||
| 197 | pub close_to_tray: bool, | 197 | pub close_to_tray: bool, |
| 198 | } | 198 | } |
| 199 | 199 | ||
| 200 | +impl Default for Settings { | ||
| 201 | + fn default() -> Self { | ||
| 202 | + Self { | ||
| 203 | + theme: ThemeChoice::Dark, | ||
| 204 | + font_size: FontSize::Medium, | ||
| 205 | + voice: VoiceSettings::default(), | ||
| 206 | + share: ShareSettings::default(), | ||
| 207 | + close_to_tray: true, | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | +} | ||
| 211 | + | ||
| 200 | fn quality_text(quality: Quality) -> String { | 212 | fn quality_text(quality: Quality) -> String { |
| 201 | format!("{}p{}", quality.resolution.height(), quality.fps.value()) | 213 | format!("{}p{}", quality.resolution.height(), quality.fps.value()) |
| 202 | } | 214 | } |
| @@ -215,9 +227,7 @@ fn parse_quality(text: &str) -> Option<Quality> { | |||
| 215 | } | 227 | } |
| 216 | 228 | ||
| 217 | pub fn load() -> Settings { | 229 | pub fn load() -> Settings { |
| 218 | - let config = config_file("settings") | 230 | + let config = read_config("settings").and_then(|content| Config::parse(&content).ok()); |
| 219 | - .and_then(|path| fs::read_to_string(path).ok()) | ||
| 220 | - .and_then(|content| Config::parse(&content).ok()); | ||
| 221 | let text = |key: &str| { | 231 | let text = |key: &str| { |
| 222 | config | 232 | config |
| 223 | .as_ref() | 233 | .as_ref() |
| @@ -231,25 +241,25 @@ pub fn load() -> Settings { | |||
| 231 | .unwrap_or(default) | 241 | .unwrap_or(default) |
| 232 | }; | 242 | }; |
| 233 | 243 | ||
| 234 | - let defaults = VoiceSettings::default(); | 244 | + let defaults = Settings::default(); |
| 235 | let voice = VoiceSettings { | 245 | let voice = VoiceSettings { |
| 236 | sensitivity_db: number( | 246 | sensitivity_db: number( |
| 237 | "voice.sensitivity", | 247 | "voice.sensitivity", |
| 238 | - defaults.sensitivity_db, | 248 | + defaults.voice.sensitivity_db, |
| 239 | &SENSITIVITY_DB, | 249 | &SENSITIVITY_DB, |
| 240 | ), | 250 | ), |
| 241 | - input_volume: number("voice.input_volume", defaults.input_volume, &VOLUME), | 251 | + input_volume: number("voice.input_volume", defaults.voice.input_volume, &VOLUME), |
| 242 | - output_volume: number("voice.output_volume", defaults.output_volume, &VOLUME), | 252 | + output_volume: number("voice.output_volume", defaults.voice.output_volume, &VOLUME), |
| 243 | choice: Choice { | 253 | choice: Choice { |
| 244 | input: text("voice.input"), | 254 | input: text("voice.input"), |
| 245 | output: text("voice.output"), | 255 | output: text("voice.output"), |
| 246 | }, | 256 | }, |
| 247 | activation: text("voice.activation") | 257 | activation: text("voice.activation") |
| 248 | .and_then(|value| Activation::parse(&value)) | 258 | .and_then(|value| Activation::parse(&value)) |
| 249 | - .unwrap_or(Activation::VoiceActivity), | 259 | + .unwrap_or(defaults.voice.activation), |
| 250 | profile: text("voice.profile") | 260 | profile: text("voice.profile") |
| 251 | .and_then(|value| Profile::parse(&value)) | 261 | .and_then(|value| Profile::parse(&value)) |
| 252 | - .unwrap_or(Profile::Voice), | 262 | + .unwrap_or(defaults.voice.profile), |
| 253 | push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), | 263 | push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), |
| 254 | user_volumes: text("voice.user_volumes") | 264 | user_volumes: text("voice.user_volumes") |
| 255 | .map(|value| { | 265 | .map(|value| { |
| @@ -265,11 +275,10 @@ pub fn load() -> Settings { | |||
| 265 | .unwrap_or_default(), | 275 | .unwrap_or_default(), |
| 266 | }; | 276 | }; |
| 267 | 277 | ||
| 268 | - let share_defaults = ShareSettings::default(); | ||
| 269 | let share = ShareSettings { | 278 | let share = ShareSettings { |
| 270 | top: text("share.top") | 279 | top: text("share.top") |
| 271 | .and_then(|value| parse_quality(&value)) | 280 | .and_then(|value| parse_quality(&value)) |
| 272 | - .unwrap_or(share_defaults.top), | 281 | + .unwrap_or(defaults.share.top), |
| 273 | codec: text("share.codec") | 282 | codec: text("share.codec") |
| 274 | .and_then(|value| Codec::parse(&value)) | 283 | .and_then(|value| Codec::parse(&value)) |
| 275 | .map_or(ShareCodec::Auto, ShareCodec::Only), | 284 | .map_or(ShareCodec::Auto, ShareCodec::Only), |
| @@ -281,24 +290,25 @@ pub fn load() -> Settings { | |||
| 281 | _ => ShareAudio::Everything, | 290 | _ => ShareAudio::Everything, |
| 282 | }, | 291 | }, |
| 283 | excluded: text("share.excluded") | 292 | excluded: text("share.excluded") |
| 284 | - .map(|value| value.split(',').map(str::to_string).collect()) | 293 | + .map(|value| value.split('\t').map(str::to_string).collect()) |
| 285 | .unwrap_or_default(), | 294 | .unwrap_or_default(), |
| 286 | watch: text("share.watch") | 295 | watch: text("share.watch") |
| 287 | .and_then(|value| parse_quality(&value)) | 296 | .and_then(|value| parse_quality(&value)) |
| 288 | .map_or(WatchQuality::Auto, WatchQuality::Fixed), | 297 | .map_or(WatchQuality::Auto, WatchQuality::Fixed), |
| 289 | - volume: number("share.volume", share_defaults.volume, &VOLUME), | 298 | + volume: number("share.volume", defaults.share.volume, &VOLUME), |
| 290 | }; | 299 | }; |
| 291 | 300 | ||
| 292 | Settings { | 301 | Settings { |
| 293 | theme: text("theme") | 302 | theme: text("theme") |
| 294 | .and_then(|value| ThemeChoice::parse(&value)) | 303 | .and_then(|value| ThemeChoice::parse(&value)) |
| 295 | - .unwrap_or(ThemeChoice::Dark), | 304 | + .unwrap_or(defaults.theme), |
| 296 | font_size: text("font_size") | 305 | font_size: text("font_size") |
| 297 | .and_then(|value| FontSize::parse(&value)) | 306 | .and_then(|value| FontSize::parse(&value)) |
| 298 | - .unwrap_or(FontSize::Medium), | 307 | + .unwrap_or(defaults.font_size), |
| 299 | voice, | 308 | voice, |
| 300 | share, | 309 | share, |
| 301 | - close_to_tray: text("close_to_tray").is_none_or(|value| value != "false"), | 310 | + close_to_tray: text("close_to_tray") |
| 311 | + .map_or(defaults.close_to_tray, |value| value != "false"), | ||
| 302 | } | 312 | } |
| 303 | } | 313 | } |
| 304 | 314 | ||
| @@ -307,12 +317,7 @@ fn line(key: &str, value: impl Display) -> String { | |||
| 307 | } | 317 | } |
| 308 | 318 | ||
| 309 | pub fn save(settings: &Settings) { | 319 | pub fn save(settings: &Settings) { |
| 310 | - let Some(path) = config_file("settings") else { | ||
| 311 | - return; | ||
| 312 | - }; | ||
| 313 | - | ||
| 314 | let voice = &settings.voice; | 320 | let voice = &settings.voice; |
| 315 | - let key = voice.push_to_talk_key.as_str(); | ||
| 316 | let share = &settings.share; | 321 | let share = &settings.share; |
| 317 | let (audio, source) = match &share.audio { | 322 | let (audio, source) = match &share.audio { |
| 318 | ShareAudio::Off => ("off", ""), | 323 | ShareAudio::Off => ("off", ""), |
| @@ -340,7 +345,7 @@ pub fn save(settings: &Settings) { | |||
| 340 | ), | 345 | ), |
| 341 | line("voice.activation", voice.activation.as_str()), | 346 | line("voice.activation", voice.activation.as_str()), |
| 342 | line("voice.profile", voice.profile.as_str()), | 347 | line("voice.profile", voice.profile.as_str()), |
| 343 | - line("voice.push_to_talk", key), | 348 | + line("voice.push_to_talk", &voice.push_to_talk_key), |
| 344 | line( | 349 | line( |
| 345 | "voice.user_volumes", | 350 | "voice.user_volumes", |
| 346 | voice | 351 | voice |
| @@ -360,20 +365,13 @@ pub fn save(settings: &Settings) { | |||
| 360 | ), | 365 | ), |
| 361 | line("share.audio", audio), | 366 | line("share.audio", audio), |
| 362 | line("share.audio_source", source), | 367 | line("share.audio_source", source), |
| 363 | - line("share.excluded", share.excluded.join(",")), | 368 | + line("share.excluded", share.excluded.join("\t")), |
| 364 | line("share.watch", watch), | 369 | line("share.watch", watch), |
| 365 | line("share.volume", share.volume), | 370 | line("share.volume", share.volume), |
| 366 | ] | 371 | ] |
| 367 | .concat(); | 372 | .concat(); |
| 368 | 373 | ||
| 369 | - let result = path | 374 | + write_config("settings", &content); |
| 370 | - .parent() | ||
| 371 | - .map_or(Ok(()), fs::create_dir_all) | ||
| 372 | - .and_then(|()| fs::write(&path, content)); | ||
| 373 | - | ||
| 374 | - if let Err(error) = result { | ||
| 375 | - warn!("save settings failed: {error}"); | ||
| 376 | - } | ||
| 377 | } | 375 | } |
| 378 | 376 | ||
| 379 | pub fn apply(choice: ThemeChoice, font_size: FontSize, cx: &mut App) { | 377 | pub fn apply(choice: ThemeChoice, font_size: FontSize, cx: &mut App) { |
crates/client/src/share/audio_capture.rsmodified+19 -46
| @@ -4,11 +4,7 @@ use std::{ | |||
| 4 | error::Error, | 4 | error::Error, |
| 5 | process, | 5 | process, |
| 6 | rc::Rc, | 6 | rc::Rc, |
| 7 | - sync::{ | 7 | + sync::atomic::{AtomicBool, Ordering}, |
| 8 | - Arc, | ||
| 9 | - atomic::{AtomicBool, Ordering}, | ||
| 10 | - }, | ||
| 11 | - thread::JoinHandle, | ||
| 12 | time::Duration, | 8 | time::Duration, |
| 13 | }; | 9 | }; |
| 14 | 10 | ||
| @@ -28,9 +24,9 @@ use spa::{pod::Pod, utils::dict::DictRef}; | |||
| 28 | use tracing::warn; | 24 | use tracing::warn; |
| 29 | 25 | ||
| 30 | use super::audio::{AudioApp, AudioKind, AudioMode}; | 26 | use super::audio::{AudioApp, AudioKind, AudioMode}; |
| 27 | +use crate::voice::audio::{Worker, supervise}; | ||
| 31 | 28 | ||
| 32 | const STOP_CHECK: Duration = Duration::from_millis(100); | 29 | const STOP_CHECK: Duration = Duration::from_millis(100); |
| 33 | -const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); | ||
| 34 | const OWN_PREFIX: &str = "yumush"; | 30 | const OWN_PREFIX: &str = "yumush"; |
| 35 | const APP_CLASS: &str = "Stream/Output/Audio"; | 31 | const APP_CLASS: &str = "Stream/Output/Audio"; |
| 36 | const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"]; | 32 | const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"]; |
| @@ -46,19 +42,7 @@ impl AudioKind { | |||
| 46 | } | 42 | } |
| 47 | } | 43 | } |
| 48 | 44 | ||
| 49 | -pub struct AudioCapture { | 45 | +pub type AudioCapture = Worker; |
| 50 | - stop: Arc<AtomicBool>, | ||
| 51 | - thread: Option<JoinHandle<()>>, | ||
| 52 | -} | ||
| 53 | - | ||
| 54 | -impl Drop for AudioCapture { | ||
| 55 | - fn drop(&mut self) { | ||
| 56 | - self.stop.store(true, Ordering::Relaxed); | ||
| 57 | - if let Some(thread) = self.thread.take() { | ||
| 58 | - let _ = thread.join(); | ||
| 59 | - } | ||
| 60 | - } | ||
| 61 | -} | ||
| 62 | 46 | ||
| 63 | #[derive(Default)] | 47 | #[derive(Default)] |
| 64 | struct Node { | 48 | struct Node { |
| @@ -103,25 +87,17 @@ pub fn apps() -> Vec<AudioApp> { | |||
| 103 | } | 87 | } |
| 104 | 88 | ||
| 105 | pub fn start(mode: AudioMode, output: rtrb::Producer<f32>) -> AudioCapture { | 89 | pub fn start(mode: AudioMode, output: rtrb::Producer<f32>) -> AudioCapture { |
| 106 | - let stop = Arc::new(AtomicBool::new(false)); | 90 | + Worker::spawn("share-audio", move |stop| { |
| 107 | - let thread = { | 91 | + let output = Rc::new(RefCell::new(output)); |
| 108 | - let stop = stop.clone(); | 92 | + let is_sink = match &mode { |
| 109 | - std::thread::Builder::new() | 93 | + AudioMode::Everything { .. } => false, |
| 110 | - .name("share-audio".to_string()) | 94 | + AudioMode::Source(name) => nodes() |
| 111 | - .spawn(move || { | 95 | + .unwrap_or_default() |
| 112 | - let output = Rc::new(RefCell::new(output)); | 96 | + .iter() |
| 113 | - while !stop.load(Ordering::Relaxed) { | 97 | + .any(|node| &node.name == name && node.class == "Audio/Sink"), |
| 114 | - if let Err(error) = run(&mode, &output, &stop) { | 98 | + }; |
| 115 | - warn!("share audio: {error}, retrying"); | 99 | + supervise("share audio", stop, || run(&mode, &output, is_sink, stop)); |
| 116 | - std::thread::sleep(RETRY_AFTER_ERROR); | 100 | + }) |
| 117 | - } | ||
| 118 | - } | ||
| 119 | - }) | ||
| 120 | - .inspect_err(|error| warn!("share audio not started: {error}")) | ||
| 121 | - .ok() | ||
| 122 | - }; | ||
| 123 | - | ||
| 124 | - AudioCapture { stop, thread } | ||
| 125 | } | 101 | } |
| 126 | 102 | ||
| 127 | fn nodes() -> Result<Vec<Node>, Box<dyn Error>> { | 103 | fn nodes() -> Result<Vec<Node>, Box<dyn Error>> { |
| @@ -343,6 +319,7 @@ fn format_values() -> Option<Vec<u8>> { | |||
| 343 | fn run( | 319 | fn run( |
| 344 | mode: &AudioMode, | 320 | mode: &AudioMode, |
| 345 | output: &Rc<RefCell<rtrb::Producer<f32>>>, | 321 | output: &Rc<RefCell<rtrb::Producer<f32>>>, |
| 322 | + is_sink: bool, | ||
| 346 | stop: &AtomicBool, | 323 | stop: &AtomicBool, |
| 347 | ) -> Result<(), Box<dyn Error>> { | 324 | ) -> Result<(), Box<dyn Error>> { |
| 348 | pw::init(); | 325 | pw::init(); |
| @@ -355,9 +332,11 @@ fn run( | |||
| 355 | let error_failed = failed.clone(); | 332 | let error_failed = failed.clone(); |
| 356 | let _core_listener = core | 333 | let _core_listener = core |
| 357 | .add_listener_local() | 334 | .add_listener_local() |
| 358 | - .error(move |_, _, _, message| { | 335 | + .error(move |id, _, _, message| { |
| 359 | warn!("pipewire: {message}"); | 336 | warn!("pipewire: {message}"); |
| 360 | - error_failed.set(true); | 337 | + if id == pw::core::PW_ID_CORE { |
| 338 | + error_failed.set(true); | ||
| 339 | + } | ||
| 361 | }) | 340 | }) |
| 362 | .register(); | 341 | .register(); |
| 363 | 342 | ||
| @@ -378,12 +357,6 @@ fn run( | |||
| 378 | AudioMode::Everything { .. } => None, | 357 | AudioMode::Everything { .. } => None, |
| 379 | AudioMode::Source(name) => Some(name.as_str()), | 358 | AudioMode::Source(name) => Some(name.as_str()), |
| 380 | }; | 359 | }; |
| 381 | - let is_sink = target.is_some_and(|target| { | ||
| 382 | - nodes() | ||
| 383 | - .unwrap_or_default() | ||
| 384 | - .iter() | ||
| 385 | - .any(|node| node.name == target && node.class == "Audio/Sink") | ||
| 386 | - }); | ||
| 387 | 360 | ||
| 388 | let mut props = properties! { | 361 | let mut props = properties! { |
| 389 | *pw::keys::MEDIA_TYPE => "Audio", | 362 | *pw::keys::MEDIA_TYPE => "Audio", |
crates/client/src/share/audio_capture_windows.rsmodified+12 -40
| @@ -2,11 +2,7 @@ use std::{ | |||
| 2 | collections::{HashMap, VecDeque}, | 2 | collections::{HashMap, VecDeque}, |
| 3 | error::Error, | 3 | error::Error, |
| 4 | process, | 4 | process, |
| 5 | - sync::{ | 5 | + sync::atomic::{AtomicBool, Ordering}, |
| 6 | - Arc, | ||
| 7 | - atomic::{AtomicBool, Ordering}, | ||
| 8 | - }, | ||
| 9 | - thread::JoinHandle, | ||
| 10 | time::Duration, | 6 | time::Duration, |
| 11 | }; | 7 | }; |
| 12 | 8 | ||
| @@ -19,25 +15,13 @@ use wasapi::{ | |||
| 19 | }; | 15 | }; |
| 20 | 16 | ||
| 21 | use super::audio::{AudioApp, AudioKind, AudioMode}; | 17 | use super::audio::{AudioApp, AudioKind, AudioMode}; |
| 18 | +use crate::voice::audio::{Worker, supervise}; | ||
| 22 | 19 | ||
| 23 | const STOP_CHECK: Duration = Duration::from_millis(100); | 20 | const STOP_CHECK: Duration = Duration::from_millis(100); |
| 24 | -const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); | ||
| 25 | const BUFFER_HNS: i64 = 200_000; | 21 | const BUFFER_HNS: i64 = 200_000; |
| 26 | const BYTES_PER_SAMPLE: usize = 4; | 22 | const BYTES_PER_SAMPLE: usize = 4; |
| 27 | 23 | ||
| 28 | -pub struct AudioCapture { | 24 | +pub type AudioCapture = Worker; |
| 29 | - stop: Arc<AtomicBool>, | ||
| 30 | - thread: Option<JoinHandle<()>>, | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -impl Drop for AudioCapture { | ||
| 34 | - fn drop(&mut self) { | ||
| 35 | - self.stop.store(true, Ordering::Relaxed); | ||
| 36 | - if let Some(thread) = self.thread.take() { | ||
| 37 | - let _ = thread.join(); | ||
| 38 | - } | ||
| 39 | - } | ||
| 40 | -} | ||
| 41 | 25 | ||
| 42 | fn with_com<T: Default>(body: impl FnOnce() -> T) -> T { | 26 | fn with_com<T: Default>(body: impl FnOnce() -> T) -> T { |
| 43 | if let Err(error) = initialize_mta().ok() { | 27 | if let Err(error) = initialize_mta().ok() { |
| @@ -99,27 +83,12 @@ fn sessions() -> Result<Vec<AudioApp>, Box<dyn Error>> { | |||
| 99 | } | 83 | } |
| 100 | 84 | ||
| 101 | pub fn start(mode: AudioMode, output: Producer<f32>) -> AudioCapture { | 85 | pub fn start(mode: AudioMode, output: Producer<f32>) -> AudioCapture { |
| 102 | - let stop = Arc::new(AtomicBool::new(false)); | 86 | + Worker::spawn("share-audio", move |stop| { |
| 103 | - let thread = { | 87 | + with_com(|| { |
| 104 | - let stop = stop.clone(); | 88 | + let mut output = output; |
| 105 | - std::thread::Builder::new() | 89 | + supervise("share audio", stop, || run(&mode, &mut output, stop)); |
| 106 | - .name("share-audio".to_string()) | 90 | + }) |
| 107 | - .spawn(move || { | 91 | + }) |
| 108 | - with_com(|| { | ||
| 109 | - let mut output = output; | ||
| 110 | - while !stop.load(Ordering::Relaxed) { | ||
| 111 | - if let Err(error) = run(&mode, &mut output, &stop) { | ||
| 112 | - warn!("share audio: {error}, retrying"); | ||
| 113 | - std::thread::sleep(RETRY_AFTER_ERROR); | ||
| 114 | - } | ||
| 115 | - } | ||
| 116 | - }) | ||
| 117 | - }) | ||
| 118 | - .inspect_err(|error| warn!("share audio not started: {error}")) | ||
| 119 | - .ok() | ||
| 120 | - }; | ||
| 121 | - | ||
| 122 | - AudioCapture { stop, thread } | ||
| 123 | } | 92 | } |
| 124 | 93 | ||
| 125 | fn wave_format() -> WaveFormat { | 94 | fn wave_format() -> WaveFormat { |
| @@ -143,6 +112,9 @@ fn run( | |||
| 143 | AudioClient::new_application_loopback_client(process::id(), false)? | 112 | AudioClient::new_application_loopback_client(process::id(), false)? |
| 144 | } | 113 | } |
| 145 | AudioMode::Source(node) => { | 114 | AudioMode::Source(node) => { |
| 115 | + if !sessions()?.iter().any(|app| &app.node == node) { | ||
| 116 | + return Err("share audio app is not running".into()); | ||
| 117 | + } | ||
| 146 | AudioClient::new_application_loopback_client(node.parse()?, true)? | 118 | AudioClient::new_application_loopback_client(node.parse()?, true)? |
| 147 | } | 119 | } |
| 148 | }; | 120 | }; |
crates/client/src/share/camera.rsmodified+14 -10
| @@ -24,6 +24,7 @@ use super::{ | |||
| 24 | 24 | ||
| 25 | const OPEN_TIMEOUT: Duration = Duration::from_secs(10); | 25 | const OPEN_TIMEOUT: Duration = Duration::from_secs(10); |
| 26 | const RETRY_DELAY: Duration = Duration::from_millis(5); | 26 | const RETRY_DELAY: Duration = Duration::from_millis(5); |
| 27 | +const MAX_FAILURES: u32 = 200; | ||
| 27 | const WANTED_FORMATS: [FrameFormat; 3] = [FrameFormat::YUYV, FrameFormat::NV12, FrameFormat::MJPEG]; | 28 | const WANTED_FORMATS: [FrameFormat; 3] = [FrameFormat::YUYV, FrameFormat::NV12, FrameFormat::MJPEG]; |
| 28 | 29 | ||
| 29 | type Negotiated = (u32, u32, u32); | 30 | type Negotiated = (u32, u32, u32); |
| @@ -129,11 +130,21 @@ fn run( | |||
| 129 | let format = camera.camera_format(); | 130 | let format = camera.camera_format(); |
| 130 | let _ = negotiated.send(Ok((format.width(), format.height(), format.frame_rate()))); | 131 | let _ = negotiated.send(Ok((format.width(), format.height(), format.frame_rate()))); |
| 131 | let started = Instant::now(); | 132 | let started = Instant::now(); |
| 133 | + let mut failures = 0; | ||
| 132 | while !stop.load(Ordering::Relaxed) { | 134 | while !stop.load(Ordering::Relaxed) { |
| 133 | - let Ok(buffer) = camera.frame() else { | 135 | + let buffer = match camera.frame() { |
| 134 | - std::thread::sleep(RETRY_DELAY); | 136 | + Ok(buffer) => buffer, |
| 135 | - continue; | 137 | + Err(error) => { |
| 138 | + failures += 1; | ||
| 139 | + if failures >= MAX_FAILURES { | ||
| 140 | + tracing::warn!(%error, "camera lost"); | ||
| 141 | + break; | ||
| 142 | + } | ||
| 143 | + std::thread::sleep(RETRY_DELAY); | ||
| 144 | + continue; | ||
| 145 | + } | ||
| 136 | }; | 146 | }; |
| 147 | + failures = 0; | ||
| 137 | let Some((width, height, bgra)) = to_bgra(&buffer) else { | 148 | let Some((width, height, bgra)) = to_bgra(&buffer) else { |
| 138 | continue; | 149 | continue; |
| 139 | }; | 150 | }; |
| @@ -157,13 +168,6 @@ fn to_bgra(buffer: &Buffer) -> Option<(u32, u32, Vec<u8>)> { | |||
| 157 | FrameFormat::YUYV => Some((width, height, pixel::yuyv_to_bgra(data, width, height)?)), | 168 | FrameFormat::YUYV => Some((width, height, pixel::yuyv_to_bgra(data, width, height)?)), |
| 158 | FrameFormat::NV12 => Some((width, height, pixel::nv12_to_bgra(data, width, height)?)), | 169 | FrameFormat::NV12 => Some((width, height, pixel::nv12_to_bgra(data, width, height)?)), |
| 159 | FrameFormat::MJPEG => mjpeg_to_bgra(data), | 170 | FrameFormat::MJPEG => mjpeg_to_bgra(data), |
| 160 | - FrameFormat::GRAY if data.len() == (width * height) as usize => Some(( | ||
| 161 | - width, | ||
| 162 | - height, | ||
| 163 | - data.iter() | ||
| 164 | - .flat_map(|&luma| [luma, luma, luma, 255]) | ||
| 165 | - .collect(), | ||
| 166 | - )), | ||
| 167 | _ => None, | 171 | _ => None, |
| 168 | } | 172 | } |
| 169 | } | 173 | } |
crates/client/src/share/capture.rsmodified+57 -19
| @@ -47,7 +47,8 @@ pub struct Capture { | |||
| 47 | pub frames: Receiver<Frame>, | 47 | pub frames: Receiver<Frame>, |
| 48 | stop: Arc<AtomicBool>, | 48 | stop: Arc<AtomicBool>, |
| 49 | thread: Option<JoinHandle<()>>, | 49 | thread: Option<JoinHandle<()>>, |
| 50 | - _session: Option<Session<Screencast>>, | 50 | + session: Option<Session<Screencast>>, |
| 51 | + runtime: tokio::runtime::Handle, | ||
| 51 | _fake: Option<fake::Generator>, | 52 | _fake: Option<fake::Generator>, |
| 52 | } | 53 | } |
| 53 | 54 | ||
| @@ -57,10 +58,16 @@ impl Drop for Capture { | |||
| 57 | if let Some(thread) = self.thread.take() { | 58 | if let Some(thread) = self.thread.take() { |
| 58 | let _ = thread.join(); | 59 | let _ = thread.join(); |
| 59 | } | 60 | } |
| 61 | + if let Some(session) = self.session.take() { | ||
| 62 | + self.runtime.spawn(async move { | ||
| 63 | + let _ = session.close().await; | ||
| 64 | + }); | ||
| 65 | + } | ||
| 60 | } | 66 | } |
| 61 | } | 67 | } |
| 62 | 68 | ||
| 63 | pub async fn open() -> Result<Capture, String> { | 69 | pub async fn open() -> Result<Capture, String> { |
| 70 | + let runtime = tokio::runtime::Handle::current(); | ||
| 64 | if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") { | 71 | if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") { |
| 65 | let (width, height, refresh, frames, generator) = fake::start(&spec); | 72 | let (width, height, refresh, frames, generator) = fake::start(&spec); |
| 66 | return Ok(Capture { | 73 | return Ok(Capture { |
| @@ -70,7 +77,8 @@ pub async fn open() -> Result<Capture, String> { | |||
| 70 | frames, | 77 | frames, |
| 71 | stop: Arc::new(AtomicBool::new(false)), | 78 | stop: Arc::new(AtomicBool::new(false)), |
| 72 | thread: None, | 79 | thread: None, |
| 73 | - _session: None, | 80 | + session: None, |
| 81 | + runtime, | ||
| 74 | _fake: Some(generator), | 82 | _fake: Some(generator), |
| 75 | }); | 83 | }); |
| 76 | } | 84 | } |
| @@ -79,9 +87,39 @@ pub async fn open() -> Result<Capture, String> { | |||
| 79 | .create_session(Default::default()) | 87 | .create_session(Default::default()) |
| 80 | .await | 88 | .await |
| 81 | .map_err(text)?; | 89 | .map_err(text)?; |
| 90 | + let (node_id, fd) = match pick(&screencast, &session).await { | ||
| 91 | + Ok(picked) => picked, | ||
| 92 | + Err(error) => { | ||
| 93 | + let _ = session.close().await; | ||
| 94 | + return Err(error); | ||
| 95 | + } | ||
| 96 | + }; | ||
| 97 | + match launch(fd, node_id).await { | ||
| 98 | + Ok(((width, height, refresh), frames, stop, thread)) => Ok(Capture { | ||
| 99 | + width, | ||
| 100 | + height, | ||
| 101 | + refresh, | ||
| 102 | + frames, | ||
| 103 | + stop, | ||
| 104 | + thread: Some(thread), | ||
| 105 | + session: Some(session), | ||
| 106 | + runtime, | ||
| 107 | + _fake: None, | ||
| 108 | + }), | ||
| 109 | + Err(error) => { | ||
| 110 | + let _ = session.close().await; | ||
| 111 | + Err(error) | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +async fn pick( | ||
| 117 | + screencast: &Screencast, | ||
| 118 | + session: &Session<Screencast>, | ||
| 119 | +) -> Result<(u32, OwnedFd), String> { | ||
| 82 | screencast | 120 | screencast |
| 83 | .select_sources( | 121 | .select_sources( |
| 84 | - &session, | 122 | + session, |
| 85 | SelectSourcesOptions::default() | 123 | SelectSourcesOptions::default() |
| 86 | .set_cursor_mode(CursorMode::EMBEDDED) | 124 | .set_cursor_mode(CursorMode::EMBEDDED) |
| 87 | .set_sources(SourceType::MONITOR | SourceType::WINDOW) | 125 | .set_sources(SourceType::MONITOR | SourceType::WINDOW) |
| @@ -93,19 +131,24 @@ pub async fn open() -> Result<Capture, String> { | |||
| 93 | .response() | 131 | .response() |
| 94 | .map_err(text)?; | 132 | .map_err(text)?; |
| 95 | let streams = screencast | 133 | let streams = screencast |
| 96 | - .start(&session, None, Default::default()) | 134 | + .start(session, None, Default::default()) |
| 97 | .await | 135 | .await |
| 98 | .map_err(text)? | 136 | .map_err(text)? |
| 99 | .response() | 137 | .response() |
| 100 | .map_err(text)?; | 138 | .map_err(text)?; |
| 101 | let stream = streams.streams().first().ok_or("no screen stream")?; | 139 | let stream = streams.streams().first().ok_or("no screen stream")?; |
| 102 | let node_id = stream.pipe_wire_node_id(); | 140 | let node_id = stream.pipe_wire_node_id(); |
| 103 | - let (portal_width, portal_height) = stream.size().unwrap_or((0, 0)); | ||
| 104 | let fd = screencast | 141 | let fd = screencast |
| 105 | - .open_pipe_wire_remote(&session, Default::default()) | 142 | + .open_pipe_wire_remote(session, Default::default()) |
| 106 | .await | 143 | .await |
| 107 | .map_err(text)?; | 144 | .map_err(text)?; |
| 145 | + Ok((node_id, fd)) | ||
| 146 | +} | ||
| 108 | 147 | ||
| 148 | +async fn launch( | ||
| 149 | + fd: OwnedFd, | ||
| 150 | + node_id: u32, | ||
| 151 | +) -> Result<(Negotiated, Receiver<Frame>, Arc<AtomicBool>, JoinHandle<()>), String> { | ||
| 109 | let (negotiated_tx, negotiated_rx) = sync_channel::<Negotiated>(1); | 152 | let (negotiated_tx, negotiated_rx) = sync_channel::<Negotiated>(1); |
| 110 | let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); | 153 | let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); |
| 111 | let stop = Arc::new(AtomicBool::new(false)); | 154 | let stop = Arc::new(AtomicBool::new(false)); |
| @@ -126,19 +169,14 @@ pub async fn open() -> Result<Capture, String> { | |||
| 126 | .await | 169 | .await |
| 127 | .ok() | 170 | .ok() |
| 128 | .flatten(); | 171 | .flatten(); |
| 129 | - let (width, height, refresh) = | 172 | + match negotiated { |
| 130 | - negotiated.unwrap_or((portal_width as u32, portal_height as u32, DEFAULT_REFRESH)); | 173 | + Some(size) => Ok((size, frames_rx, stop, thread)), |
| 131 | - | 174 | + None => { |
| 132 | - Ok(Capture { | 175 | + stop.store(true, Ordering::Relaxed); |
| 133 | - width, | 176 | + let _ = thread.join(); |
| 134 | - height, | 177 | + Err("screen capture did not start".into()) |
| 135 | - refresh, | 178 | + } |
| 136 | - frames: frames_rx, | 179 | + } |
| 137 | - stop, | ||
| 138 | - thread: Some(thread), | ||
| 139 | - _session: Some(session), | ||
| 140 | - _fake: None, | ||
| 141 | - }) | ||
| 142 | } | 180 | } |
| 143 | 181 | ||
| 144 | fn text(error: impl std::fmt::Display) -> String { | 182 | fn text(error: impl std::fmt::Display) -> String { |
crates/client/src/share/capture_windows.rsmodified+7 -3
| @@ -6,7 +6,7 @@ use std::{ | |||
| 6 | use windows_capture::{ | 6 | use windows_capture::{ |
| 7 | capture::{CaptureControl, Context, GraphicsCaptureApiHandler}, | 7 | capture::{CaptureControl, Context, GraphicsCaptureApiHandler}, |
| 8 | frame::Frame as CaptureFrame, | 8 | frame::Frame as CaptureFrame, |
| 9 | - graphics_capture_api::InternalCaptureControl, | 9 | + graphics_capture_api::{GraphicsCaptureApi, InternalCaptureControl}, |
| 10 | monitor::Monitor, | 10 | monitor::Monitor, |
| 11 | settings::{ | 11 | settings::{ |
| 12 | ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings, | 12 | ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings, |
| @@ -57,11 +57,15 @@ pub async fn open() -> Result<Capture, String> { | |||
| 57 | .filter(|refresh| *refresh > 1) | 57 | .filter(|refresh| *refresh > 1) |
| 58 | .unwrap_or(DEFAULT_REFRESH); | 58 | .unwrap_or(DEFAULT_REFRESH); |
| 59 | 59 | ||
| 60 | + let border = match GraphicsCaptureApi::is_border_settings_supported() { | ||
| 61 | + Ok(true) => DrawBorderSettings::WithoutBorder, | ||
| 62 | + _ => DrawBorderSettings::Default, | ||
| 63 | + }; | ||
| 60 | let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); | 64 | let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); |
| 61 | let settings = Settings::new( | 65 | let settings = Settings::new( |
| 62 | monitor, | 66 | monitor, |
| 63 | - CursorCaptureSettings::WithCursor, | 67 | + CursorCaptureSettings::Default, |
| 64 | - DrawBorderSettings::WithoutBorder, | 68 | + border, |
| 65 | SecondaryWindowSettings::Default, | 69 | SecondaryWindowSettings::Default, |
| 66 | MinimumUpdateIntervalSettings::Default, | 70 | MinimumUpdateIntervalSettings::Default, |
| 67 | DirtyRegionSettings::Default, | 71 | DirtyRegionSettings::Default, |
crates/client/src/share/convert.rsdeleted+0 -13
| @@ -1,13 +0,0 @@ | |||
| 1 | -pub use pixel::I420; | ||
| 2 | - | ||
| 3 | -use super::frame::Frame; | ||
| 4 | - | ||
| 5 | -pub fn bgra_to_i420(frame: &Frame, width: u32, height: u32) -> Option<I420> { | ||
| 6 | - let source = pixel::Bgra { | ||
| 7 | - data: &frame.bgra, | ||
| 8 | - width: frame.width, | ||
| 9 | - height: frame.height, | ||
| 10 | - stride: frame.stride, | ||
| 11 | - }; | ||
| 12 | - pixel::bgra_to_i420(&source, width, height) | ||
| 13 | -} | ||
crates/client/src/share/encode.rsmodified+9 -12
| @@ -6,13 +6,13 @@ use std::thread; | |||
| 6 | 6 | ||
| 7 | use common::share::{Codec, Layer}; | 7 | use common::share::{Codec, Layer}; |
| 8 | 8 | ||
| 9 | -use super::convert; | ||
| 10 | use super::frame::{Encoded, Frame}; | 9 | use super::frame::{Encoded, Frame}; |
| 11 | -use crate::media::decode::{Engine, VideoDecoder}; | 10 | +use crate::media::decode::Engine; |
| 12 | 11 | ||
| 13 | const SOFTWARE: Codec = Codec::H264; | 12 | const SOFTWARE: Codec = Codec::H264; |
| 14 | const DEFAULT_MAX_HEIGHT: u32 = 2160; | 13 | const DEFAULT_MAX_HEIGHT: u32 = 2160; |
| 15 | const KEYFRAME_SECONDS: u32 = 2; | 14 | const KEYFRAME_SECONDS: u32 = 2; |
| 15 | +const SLACK_MS: u32 = 4; | ||
| 16 | 16 | ||
| 17 | pub struct Capabilities { | 17 | pub struct Capabilities { |
| 18 | pub encode: Vec<Codec>, | 18 | pub encode: Vec<Codec>, |
| @@ -42,10 +42,7 @@ fn probe() -> &'static Probe { | |||
| 42 | Probe { | 42 | Probe { |
| 43 | capabilities: Capabilities { | 43 | capabilities: Capabilities { |
| 44 | encode, | 44 | encode, |
| 45 | - decode: Codec::ALL | 45 | + decode: Codec::ALL.to_vec(), |
| 46 | - .into_iter() | ||
| 47 | - .filter(|codec| VideoDecoder::for_codec(*codec).is_some()) | ||
| 48 | - .collect(), | ||
| 49 | max_height, | 46 | max_height, |
| 50 | }, | 47 | }, |
| 51 | hardware: codecs, | 48 | hardware: codecs, |
| @@ -121,7 +118,7 @@ impl Backend { | |||
| 121 | match self { | 118 | match self { |
| 122 | Self::Hardware(encoder) => encoder.encode(frame, settings, force), | 119 | Self::Hardware(encoder) => encoder.encode(frame, settings, force), |
| 123 | Self::H264(encoder) => { | 120 | Self::H264(encoder) => { |
| 124 | - let planes = convert::bgra_to_i420(frame, settings.width, settings.height)?; | 121 | + let planes = frame.to_i420(settings.width, settings.height)?; |
| 125 | let picture = ec_h264::PictureView::i420( | 122 | let picture = ec_h264::PictureView::i420( |
| 126 | planes.width, | 123 | planes.width, |
| 127 | planes.height, | 124 | planes.height, |
| @@ -146,7 +143,7 @@ mod hardware { | |||
| 146 | use common::share::Codec; | 143 | use common::share::Codec; |
| 147 | 144 | ||
| 148 | use super::{Settings, report}; | 145 | use super::{Settings, report}; |
| 149 | - use crate::share::{convert, frame::Frame}; | 146 | + use crate::share::frame::Frame; |
| 150 | 147 | ||
| 151 | pub struct Encoder(ec_hw::HwEncoder); | 148 | pub struct Encoder(ec_hw::HwEncoder); |
| 152 | 149 | ||
| @@ -178,7 +175,7 @@ mod hardware { | |||
| 178 | }; | 175 | }; |
| 179 | self.0.encode_rgb(&rgb, meta) | 176 | self.0.encode_rgb(&rgb, meta) |
| 180 | } else { | 177 | } else { |
| 181 | - let planes = convert::bgra_to_i420(frame, settings.width, settings.height)?; | 178 | + let planes = frame.to_i420(settings.width, settings.height)?; |
| 182 | let picture = ec_hw::I420 { | 179 | let picture = ec_hw::I420 { |
| 183 | y: planes.y, | 180 | y: planes.y, |
| 184 | u: planes.u, | 181 | u: planes.u, |
| @@ -249,12 +246,12 @@ fn run( | |||
| 249 | }; | 246 | }; |
| 250 | let mut applied = 1.0; | 247 | let mut applied = 1.0; |
| 251 | let interval = 1000 / settings.fps; | 248 | let interval = 1000 / settings.fps; |
| 252 | - let mut last: Option<u32> = None; | 249 | + let mut due = 0u32; |
| 253 | for frame in input { | 250 | for frame in input { |
| 254 | - if last.is_some_and(|last| frame.timestamp_ms.wrapping_sub(last) < interval) { | 251 | + if frame.timestamp_ms + SLACK_MS < due { |
| 255 | continue; | 252 | continue; |
| 256 | } | 253 | } |
| 257 | - last = Some(frame.timestamp_ms); | 254 | + due = due.max(frame.timestamp_ms.saturating_sub(SLACK_MS)) + interval; |
| 258 | let wanted = f32::from_bits(scale.load(Ordering::Relaxed)); | 255 | let wanted = f32::from_bits(scale.load(Ordering::Relaxed)); |
| 259 | if wanted != applied { | 256 | if wanted != applied { |
| 260 | applied = wanted; | 257 | applied = wanted; |
crates/client/src/share/frame.rsmodified+12 -0
| @@ -14,6 +14,18 @@ pub struct Frame { | |||
| 14 | pub bgra: Vec<u8>, | 14 | pub bgra: Vec<u8>, |
| 15 | } | 15 | } |
| 16 | 16 | ||
| 17 | +impl Frame { | ||
| 18 | + pub fn to_i420(&self, width: u32, height: u32) -> Option<pixel::I420> { | ||
| 19 | + let source = pixel::Bgra { | ||
| 20 | + data: &self.bgra, | ||
| 21 | + width: self.width, | ||
| 22 | + height: self.height, | ||
| 23 | + stride: self.stride, | ||
| 24 | + }; | ||
| 25 | + pixel::bgra_to_i420(&source, width, height) | ||
| 26 | + } | ||
| 27 | +} | ||
| 28 | + | ||
| 17 | pub struct Encoded { | 29 | pub struct Encoded { |
| 18 | pub layer: Layer, | 30 | pub layer: Layer, |
| 19 | pub engine: Engine, | 31 | pub engine: Engine, |
crates/client/src/share/mod.rsmodified+4 -1
| @@ -12,10 +12,13 @@ pub mod capture; | |||
| 12 | #[path = "capture_windows.rs"] | 12 | #[path = "capture_windows.rs"] |
| 13 | pub mod capture; | 13 | pub mod capture; |
| 14 | pub mod congestion; | 14 | pub mod congestion; |
| 15 | -pub mod convert; | ||
| 16 | pub mod encode; | 15 | pub mod encode; |
| 17 | #[cfg(any(target_os = "linux", target_os = "windows"))] | 16 | #[cfg(any(target_os = "linux", target_os = "windows"))] |
| 18 | pub mod fake; | 17 | pub mod fake; |
| 19 | pub mod frame; | 18 | pub mod frame; |
| 20 | pub mod reassembly; | 19 | pub mod reassembly; |
| 21 | pub mod session; | 20 | pub mod session; |
| 21 | +#[cfg(not(any(target_os = "linux", target_os = "windows")))] | ||
| 22 | +mod unsupported; | ||
| 23 | +#[cfg(not(any(target_os = "linux", target_os = "windows")))] | ||
| 24 | +pub use unsupported::{audio_capture, camera, capture}; | ||
crates/client/src/share/reassembly.rsmodified+2 -6
| @@ -88,7 +88,6 @@ pub struct Reassembler { | |||
| 88 | pending: HashMap<u32, Pending>, | 88 | pending: HashMap<u32, Pending>, |
| 89 | last: Option<u32>, | 89 | last: Option<u32>, |
| 90 | phase: Phase, | 90 | phase: Phase, |
| 91 | - lost: bool, | ||
| 92 | received_frames: u32, | 91 | received_frames: u32, |
| 93 | lost_frames: u32, | 92 | lost_frames: u32, |
| 94 | } | 93 | } |
| @@ -100,7 +99,6 @@ impl Reassembler { | |||
| 100 | pending: HashMap::new(), | 99 | pending: HashMap::new(), |
| 101 | last: None, | 100 | last: None, |
| 102 | phase: Phase::WaitingKeyframe, | 101 | phase: Phase::WaitingKeyframe, |
| 103 | - lost: false, | ||
| 104 | received_frames: 0, | 102 | received_frames: 0, |
| 105 | lost_frames: 0, | 103 | lost_frames: 0, |
| 106 | } | 104 | } |
| @@ -121,7 +119,6 @@ impl Reassembler { | |||
| 121 | } | 119 | } |
| 122 | if !self.pending.contains_key(&fragment.frame) && self.pending.len() >= PENDING_LIMIT { | 120 | if !self.pending.contains_key(&fragment.frame) && self.pending.len() >= PENDING_LIMIT { |
| 123 | self.pending.clear(); | 121 | self.pending.clear(); |
| 124 | - self.lost = true; | ||
| 125 | self.phase = Phase::WaitingKeyframe; | 122 | self.phase = Phase::WaitingKeyframe; |
| 126 | } | 123 | } |
| 127 | let pending = self | 124 | let pending = self |
| @@ -146,7 +143,6 @@ impl Reassembler { | |||
| 146 | self.last = Some(frame); | 143 | self.last = Some(frame); |
| 147 | if skipped > 0 || data.is_none() { | 144 | if skipped > 0 || data.is_none() { |
| 148 | self.lost_frames += skipped + u32::from(data.is_none()); | 145 | self.lost_frames += skipped + u32::from(data.is_none()); |
| 149 | - self.lost = true; | ||
| 150 | self.phase = Phase::WaitingKeyframe; | 146 | self.phase = Phase::WaitingKeyframe; |
| 151 | self.pending.retain(|&older, _| is_newer(older, frame)); | 147 | self.pending.retain(|&older, _| is_newer(older, frame)); |
| 152 | } | 148 | } |
| @@ -166,8 +162,8 @@ impl Reassembler { | |||
| 166 | }) | 162 | }) |
| 167 | } | 163 | } |
| 168 | 164 | ||
| 169 | - pub fn take_lost(&mut self) -> bool { | 165 | + pub fn needs_keyframe(&self) -> bool { |
| 170 | - std::mem::take(&mut self.lost) | 166 | + self.phase == Phase::WaitingKeyframe |
| 171 | } | 167 | } |
| 172 | 168 | ||
| 173 | pub fn loss_ratio(&mut self) -> f32 { | 169 | pub fn loss_ratio(&mut self) -> f32 { |
crates/client/src/share/session.rsmodified+40 -77
| @@ -2,7 +2,7 @@ use std::{ | |||
| 2 | cmp::Reverse, | 2 | cmp::Reverse, |
| 3 | collections::{HashMap, VecDeque}, | 3 | collections::{HashMap, VecDeque}, |
| 4 | sync::{ | 4 | sync::{ |
| 5 | - Arc, Mutex, | 5 | + Arc, LazyLock, Mutex, |
| 6 | atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering}, | 6 | atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering}, |
| 7 | mpsc::{self, Receiver, RecvTimeoutError, Sender}, | 7 | mpsc::{self, Receiver, RecvTimeoutError, Sender}, |
| 8 | }, | 8 | }, |
| @@ -146,13 +146,11 @@ fn next<T>(rx: &Receiver<T>, stop: &AtomicBool) -> Option<T> { | |||
| 146 | None | 146 | None |
| 147 | } | 147 | } |
| 148 | 148 | ||
| 149 | -#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 150 | enum Input { | 149 | enum Input { |
| 151 | Screen(Capture), | 150 | Screen(Capture), |
| 152 | Camera(Camera), | 151 | Camera(Camera), |
| 153 | } | 152 | } |
| 154 | 153 | ||
| 155 | -#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 156 | impl Input { | 154 | impl Input { |
| 157 | fn size(&self) -> (u32, u32, u32) { | 155 | fn size(&self) -> (u32, u32, u32) { |
| 158 | match self { | 156 | match self { |
| @@ -170,10 +168,6 @@ impl Input { | |||
| 170 | } | 168 | } |
| 171 | } | 169 | } |
| 172 | 170 | ||
| 173 | -#[cfg(not(any(target_os = "linux", target_os = "windows")))] | ||
| 174 | -pub struct Sharing {} | ||
| 175 | - | ||
| 176 | -#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 177 | pub struct Sharing { | 171 | pub struct Sharing { |
| 178 | encoders: Arc<Mutex<Encoders>>, | 172 | encoders: Arc<Mutex<Encoders>>, |
| 179 | _feed: Worker, | 173 | _feed: Worker, |
| @@ -190,58 +184,22 @@ pub struct Sharing { | |||
| 190 | sent: Arc<Mutex<Sent>>, | 184 | sent: Arc<Mutex<Sent>>, |
| 191 | } | 185 | } |
| 192 | 186 | ||
| 193 | -#[cfg(not(any(target_os = "linux", target_os = "windows")))] | ||
| 194 | impl Sharing { | 187 | impl Sharing { |
| 195 | - pub async fn start( | 188 | + fn clamp(top: Quality, height: u32, refresh: u32) -> Quality { |
| 196 | - _: Connection, | ||
| 197 | - _: Kind, | ||
| 198 | - _: Quality, | ||
| 199 | - _: Vec<Codec>, | ||
| 200 | - _: Option<AudioMode>, | ||
| 201 | - ) -> Result<(Sharing, Source), String> { | ||
| 202 | - Err("screen share needs linux".into()) | ||
| 203 | - } | ||
| 204 | - | ||
| 205 | - pub fn update( | ||
| 206 | - &mut self, | ||
| 207 | - _: &Connection, | ||
| 208 | - _: Quality, | ||
| 209 | - _: Vec<Codec>, | ||
| 210 | - _: Option<AudioMode>, | ||
| 211 | - ) -> Result<Source, String> { | ||
| 212 | - Err("screen share needs linux".into()) | ||
| 213 | - } | ||
| 214 | - | ||
| 215 | - pub fn set_layers(&mut self, _: &[Layer]) {} | ||
| 216 | - | ||
| 217 | - pub fn keyframe(&self, _: Layer) {} | ||
| 218 | - | ||
| 219 | - pub fn stats(&self) -> Vec<LayerStats> { | ||
| 220 | - Vec::new() | ||
| 221 | - } | ||
| 222 | - | ||
| 223 | - pub fn level(&self) -> Vec<f32> { | ||
| 224 | - Vec::new() | ||
| 225 | - } | ||
| 226 | -} | ||
| 227 | - | ||
| 228 | -#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 229 | -impl Sharing { | ||
| 230 | - fn clamp(top: Quality, height: u32, refresh: u32) -> Result<Quality, String> { | ||
| 231 | let (resolutions, frame_rates) = | 189 | let (resolutions, frame_rates) = |
| 232 | options(height, refresh, encode::capabilities().max_height); | 190 | options(height, refresh, encode::capabilities().max_height); |
| 233 | - Ok(Quality { | 191 | + Quality { |
| 234 | resolution: resolutions | 192 | resolution: resolutions |
| 235 | .into_iter() | 193 | .into_iter() |
| 236 | .filter(|resolution| *resolution <= top.resolution) | 194 | .filter(|resolution| *resolution <= top.resolution) |
| 237 | .max() | 195 | .max() |
| 238 | - .ok_or("no share resolution")?, | 196 | + .unwrap_or(Resolution::P360), |
| 239 | fps: frame_rates | 197 | fps: frame_rates |
| 240 | .into_iter() | 198 | .into_iter() |
| 241 | .filter(|fps| *fps <= top.fps) | 199 | .filter(|fps| *fps <= top.fps) |
| 242 | .max() | 200 | .max() |
| 243 | - .ok_or("no share fps")?, | 201 | + .unwrap_or(Fps::F15), |
| 244 | - }) | 202 | + } |
| 245 | } | 203 | } |
| 246 | 204 | ||
| 247 | pub async fn start( | 205 | pub async fn start( |
| @@ -267,7 +225,7 @@ impl Sharing { | |||
| 267 | let source = Source { | 225 | let source = Source { |
| 268 | width, | 226 | width, |
| 269 | height, | 227 | height, |
| 270 | - top: Self::clamp(top, height, refresh)?, | 228 | + top: Self::clamp(top, height, refresh), |
| 271 | encode, | 229 | encode, |
| 272 | }; | 230 | }; |
| 273 | 231 | ||
| @@ -333,7 +291,7 @@ impl Sharing { | |||
| 333 | if encode.is_empty() { | 291 | if encode.is_empty() { |
| 334 | return Err("codec unavailable".into()); | 292 | return Err("codec unavailable".into()); |
| 335 | } | 293 | } |
| 336 | - self.source.top = Self::clamp(top, self.source.height, self.refresh)?; | 294 | + self.source.top = Self::clamp(top, self.source.height, self.refresh); |
| 337 | self.source.encode = encode; | 295 | self.source.encode = encode; |
| 338 | if self.audio != audio { | 296 | if self.audio != audio { |
| 339 | self.audio = audio.clone(); | 297 | self.audio = audio.clone(); |
| @@ -562,7 +520,7 @@ impl Watching { | |||
| 562 | Kind::Camera => (None, None, None), | 520 | Kind::Camera => (None, None, None), |
| 563 | }; | 521 | }; |
| 564 | 522 | ||
| 565 | - Watching { | 523 | + let mut watching = Watching { |
| 566 | clock, | 524 | clock, |
| 567 | video, | 525 | video, |
| 568 | health, | 526 | health, |
| @@ -583,6 +541,15 @@ impl Watching { | |||
| 583 | .unwrap_or(0), | 541 | .unwrap_or(0), |
| 584 | clean: 0, | 542 | clean: 0, |
| 585 | requested: None, | 543 | requested: None, |
| 544 | + }; | ||
| 545 | + watching.emitted = Some(watching.wanted()); | ||
| 546 | + watching | ||
| 547 | + } | ||
| 548 | + | ||
| 549 | + pub fn wanted(&self) -> Quality { | ||
| 550 | + match self.quality { | ||
| 551 | + WatchQuality::Fixed(quality) => quality, | ||
| 552 | + WatchQuality::Auto => rungs()[self.rung], | ||
| 586 | } | 553 | } |
| 587 | } | 554 | } |
| 588 | 555 | ||
| @@ -658,14 +625,11 @@ impl Watching { | |||
| 658 | 625 | ||
| 659 | pub fn tick(&mut self) -> Vec<Tick> { | 626 | pub fn tick(&mut self) -> Vec<Tick> { |
| 660 | let (loss, served, lost) = { | 627 | let (loss, served, lost) = { |
| 661 | - let mut health = lock(&self.health); | 628 | + let health = lock(&self.health); |
| 662 | let due = self | 629 | let due = self |
| 663 | .requested | 630 | .requested |
| 664 | .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); | 631 | .is_none_or(|at| at.elapsed() >= KEYFRAME_INTERVAL); |
| 665 | let lost = health.lost && due; | 632 | let lost = health.lost && due; |
| 666 | - if lost { | ||
| 667 | - health.lost = false; | ||
| 668 | - } | ||
| 669 | (health.loss, health.served, lost) | 633 | (health.loss, health.served, lost) |
| 670 | }; | 634 | }; |
| 671 | let mut ticks = Vec::new(); | 635 | let mut ticks = Vec::new(); |
| @@ -673,13 +637,10 @@ impl Watching { | |||
| 673 | self.requested = Some(Instant::now()); | 637 | self.requested = Some(Instant::now()); |
| 674 | ticks.push(Tick::Keyframe); | 638 | ticks.push(Tick::Keyframe); |
| 675 | } | 639 | } |
| 676 | - let wanted = match self.quality { | 640 | + if self.quality == WatchQuality::Auto { |
| 677 | - WatchQuality::Fixed(quality) => quality, | 641 | + self.adapt(loss, served); |
| 678 | - WatchQuality::Auto => { | 642 | + } |
| 679 | - self.adapt(loss, served); | 643 | + let wanted = self.wanted(); |
| 680 | - rungs()[self.rung] | ||
| 681 | - } | ||
| 682 | - }; | ||
| 683 | if self.emitted != Some(wanted) { | 644 | if self.emitted != Some(wanted) { |
| 684 | self.emitted = Some(wanted); | 645 | self.emitted = Some(wanted); |
| 685 | ticks.push(Tick::Quality(wanted)); | 646 | ticks.push(Tick::Quality(wanted)); |
| @@ -705,19 +666,22 @@ impl Watching { | |||
| 705 | } | 666 | } |
| 706 | } | 667 | } |
| 707 | 668 | ||
| 708 | -fn rungs() -> Vec<Quality> { | 669 | +fn rungs() -> &'static [Quality] { |
| 709 | - let mut rungs: Vec<Quality> = Resolution::ALL | 670 | + static RUNGS: LazyLock<Vec<Quality>> = LazyLock::new(|| { |
| 710 | - .into_iter() | 671 | + let mut rungs: Vec<Quality> = Resolution::ALL |
| 711 | - .flat_map(|resolution| { | 672 | + .into_iter() |
| 712 | - Fps::ALL | 673 | + .flat_map(|resolution| { |
| 713 | - .into_iter() | 674 | + Fps::ALL |
| 714 | - .map(move |fps| Quality { resolution, fps }) | 675 | + .into_iter() |
| 715 | - }) | 676 | + .map(move |fps| Quality { resolution, fps }) |
| 716 | - .collect(); | 677 | + }) |
| 717 | - rungs.sort_by_key(|quality| { | 678 | + .collect(); |
| 718 | - Reverse((quality.resolution.height() * quality.fps.value(), *quality)) | 679 | + rungs.sort_by_key(|quality| { |
| 680 | + Reverse((quality.resolution.height() * quality.fps.value(), *quality)) | ||
| 681 | + }); | ||
| 682 | + rungs | ||
| 719 | }); | 683 | }); |
| 720 | - rungs | 684 | + &RUNGS |
| 721 | } | 685 | } |
| 722 | 686 | ||
| 723 | fn watch_video( | 687 | fn watch_video( |
| @@ -747,10 +711,9 @@ fn watch_video( | |||
| 747 | Err(RecvTimeoutError::Timeout) => {} | 711 | Err(RecvTimeoutError::Timeout) => {} |
| 748 | Err(RecvTimeoutError::Disconnected) => break, | 712 | Err(RecvTimeoutError::Disconnected) => break, |
| 749 | } | 713 | } |
| 714 | + lock(health).lost = reassembler.needs_keyframe(); | ||
| 750 | if sampled.elapsed() >= SAMPLE { | 715 | if sampled.elapsed() >= SAMPLE { |
| 751 | - let mut health = lock(health); | 716 | + lock(health).loss = reassembler.loss_ratio(); |
| 752 | - health.loss = reassembler.loss_ratio(); | ||
| 753 | - health.lost |= reassembler.take_lost(); | ||
| 754 | sampled = Instant::now(); | 717 | sampled = Instant::now(); |
| 755 | } | 718 | } |
| 756 | } | 719 | } |
crates/client/src/share/unsupported.rsadded+52 -0
| @@ -0,0 +1,52 @@ | |||
| 1 | +use std::sync::mpsc::Receiver; | ||
| 2 | + | ||
| 3 | +use super::{ | ||
| 4 | + audio::{AudioApp, AudioMode}, | ||
| 5 | + frame::Frame, | ||
| 6 | +}; | ||
| 7 | + | ||
| 8 | +const UNSUPPORTED: &str = "screen share is not supported on this OS"; | ||
| 9 | + | ||
| 10 | +pub mod capture { | ||
| 11 | + use super::*; | ||
| 12 | + | ||
| 13 | + pub struct Capture { | ||
| 14 | + pub width: u32, | ||
| 15 | + pub height: u32, | ||
| 16 | + pub refresh: u32, | ||
| 17 | + pub frames: Receiver<Frame>, | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + pub async fn open() -> Result<Capture, String> { | ||
| 21 | + Err(UNSUPPORTED.into()) | ||
| 22 | + } | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +pub mod camera { | ||
| 26 | + use super::*; | ||
| 27 | + | ||
| 28 | + pub struct Camera { | ||
| 29 | + pub width: u32, | ||
| 30 | + pub height: u32, | ||
| 31 | + pub refresh: u32, | ||
| 32 | + pub frames: Receiver<Frame>, | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + pub fn open() -> Result<Camera, String> { | ||
| 36 | + Err(UNSUPPORTED.into()) | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +pub mod audio_capture { | ||
| 41 | + use super::*; | ||
| 42 | + | ||
| 43 | + pub struct AudioCapture; | ||
| 44 | + | ||
| 45 | + pub fn apps() -> Vec<AudioApp> { | ||
| 46 | + Vec::new() | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + pub fn start(_: AudioMode, _: rtrb::Producer<f32>) -> AudioCapture { | ||
| 50 | + AudioCapture | ||
| 51 | + } | ||
| 52 | +} | ||
crates/client/src/tray.rsmodified+154 -154
| @@ -1,5 +1,7 @@ | |||
| 1 | use tokio::sync::mpsc; | 1 | use tokio::sync::mpsc; |
| 2 | 2 | ||
| 3 | +pub const AVAILABLE: bool = cfg!(target_os = "linux"); | ||
| 4 | + | ||
| 3 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 4 | pub enum TrayAction { | 6 | pub enum TrayAction { |
| 5 | Show, | 7 | Show, |
| @@ -12,23 +14,6 @@ pub struct TrayState { | |||
| 12 | pub mentions: u32, | 14 | pub mentions: u32, |
| 13 | } | 15 | } |
| 14 | 16 | ||
| 15 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 16 | -enum Badge { | ||
| 17 | - None, | ||
| 18 | - Unread, | ||
| 19 | - Mention, | ||
| 20 | -} | ||
| 21 | - | ||
| 22 | -impl TrayState { | ||
| 23 | - fn badge(self) -> Badge { | ||
| 24 | - match (self.messages, self.mentions) { | ||
| 25 | - (_, 1..) => Badge::Mention, | ||
| 26 | - (1.., _) => Badge::Unread, | ||
| 27 | - _ => Badge::None, | ||
| 28 | - } | ||
| 29 | - } | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | #[derive(Clone)] | 17 | #[derive(Clone)] |
| 33 | pub struct TrayHandle(mpsc::UnboundedSender<TrayState>); | 18 | pub struct TrayHandle(mpsc::UnboundedSender<TrayState>); |
| 34 | 19 | ||
| @@ -39,45 +24,7 @@ impl TrayHandle { | |||
| 39 | } | 24 | } |
| 40 | 25 | ||
| 41 | #[cfg(target_os = "linux")] | 26 | #[cfg(target_os = "linux")] |
| 42 | -pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { | 27 | +pub use linux::start; |
| 43 | - use ksni::TrayMethods; | ||
| 44 | - use tracing::warn; | ||
| 45 | - | ||
| 46 | - let (sender, receiver) = mpsc::unbounded_channel(); | ||
| 47 | - let (state_sender, mut state_receiver) = mpsc::unbounded_channel(); | ||
| 48 | - let tray = Tray { | ||
| 49 | - sender, | ||
| 50 | - state: TrayState::default(), | ||
| 51 | - }; | ||
| 52 | - | ||
| 53 | - let _ = std::thread::Builder::new() | ||
| 54 | - .name("tray".to_string()) | ||
| 55 | - .spawn(move || { | ||
| 56 | - let runtime = match tokio::runtime::Builder::new_current_thread() | ||
| 57 | - .enable_all() | ||
| 58 | - .build() | ||
| 59 | - { | ||
| 60 | - Ok(runtime) => runtime, | ||
| 61 | - Err(error) => { | ||
| 62 | - warn!("tray runtime: {error}"); | ||
| 63 | - return; | ||
| 64 | - } | ||
| 65 | - }; | ||
| 66 | - runtime.block_on(async move { | ||
| 67 | - match tray.assume_sni_available(true).spawn().await { | ||
| 68 | - Ok(handle) => { | ||
| 69 | - while let Some(state) = state_receiver.recv().await { | ||
| 70 | - handle.update(|tray| tray.state = state).await; | ||
| 71 | - } | ||
| 72 | - std::future::pending::<()>().await | ||
| 73 | - } | ||
| 74 | - Err(error) => warn!("tray: {error}"), | ||
| 75 | - } | ||
| 76 | - }); | ||
| 77 | - }); | ||
| 78 | - | ||
| 79 | - (receiver, TrayHandle(state_sender)) | ||
| 80 | -} | ||
| 81 | 28 | ||
| 82 | #[cfg(not(target_os = "linux"))] | 29 | #[cfg(not(target_os = "linux"))] |
| 83 | pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { | 30 | pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { |
| @@ -88,123 +35,176 @@ pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { | |||
| 88 | } | 35 | } |
| 89 | 36 | ||
| 90 | #[cfg(target_os = "linux")] | 37 | #[cfg(target_os = "linux")] |
| 91 | -struct Tray { | 38 | +mod linux { |
| 92 | - sender: mpsc::UnboundedSender<TrayAction>, | 39 | + use ksni::TrayMethods; |
| 93 | - state: TrayState, | 40 | + use tokio::sync::mpsc; |
| 94 | -} | 41 | + use tracing::warn; |
| 95 | 42 | ||
| 96 | -#[cfg(target_os = "linux")] | 43 | + use super::{TrayAction, TrayHandle, TrayState}; |
| 97 | -impl ksni::Tray for Tray { | ||
| 98 | - fn id(&self) -> String { | ||
| 99 | - crate::NAME.to_string() | ||
| 100 | - } | ||
| 101 | 44 | ||
| 102 | - fn title(&self) -> String { | 45 | + #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 103 | - crate::NAME.to_string() | 46 | + enum Badge { |
| 47 | + None, | ||
| 48 | + Unread, | ||
| 49 | + Mention, | ||
| 104 | } | 50 | } |
| 105 | 51 | ||
| 106 | - fn icon_pixmap(&self) -> Vec<ksni::Icon> { | 52 | + impl TrayState { |
| 107 | - vec![icon(self.state.badge())] | 53 | + fn badge(self) -> Badge { |
| 108 | - } | 54 | + match (self.messages, self.mentions) { |
| 109 | - | 55 | + (_, 1..) => Badge::Mention, |
| 110 | - fn status(&self) -> ksni::Status { | 56 | + (1.., _) => Badge::Unread, |
| 111 | - match self.state.badge() { | 57 | + _ => Badge::None, |
| 112 | - Badge::Mention => ksni::Status::NeedsAttention, | 58 | + } |
| 113 | - _ => ksni::Status::Active, | ||
| 114 | } | 59 | } |
| 115 | } | 60 | } |
| 116 | 61 | ||
| 117 | - fn tool_tip(&self) -> ksni::ToolTip { | 62 | + pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { |
| 118 | - let description = match self.state.badge() { | 63 | + let (sender, receiver) = mpsc::unbounded_channel(); |
| 119 | - Badge::None => String::new(), | 64 | + let (state_sender, mut state_receiver) = mpsc::unbounded_channel(); |
| 120 | - _ => format!( | 65 | + let tray = Tray { |
| 121 | - "{} unread · {} mentions", | 66 | + sender, |
| 122 | - self.state.messages, self.state.mentions | 67 | + state: TrayState::default(), |
| 123 | - ), | ||
| 124 | }; | 68 | }; |
| 125 | - ksni::ToolTip { | 69 | + |
| 126 | - title: crate::NAME.to_string(), | 70 | + let _ = std::thread::Builder::new() |
| 127 | - description, | 71 | + .name("tray".to_string()) |
| 128 | - ..Default::default() | 72 | + .spawn(move || { |
| 129 | - } | 73 | + let runtime = match tokio::runtime::Builder::new_current_thread() |
| 74 | + .enable_all() | ||
| 75 | + .build() | ||
| 76 | + { | ||
| 77 | + Ok(runtime) => runtime, | ||
| 78 | + Err(error) => { | ||
| 79 | + warn!("tray runtime: {error}"); | ||
| 80 | + return; | ||
| 81 | + } | ||
| 82 | + }; | ||
| 83 | + runtime.block_on(async move { | ||
| 84 | + match tray.assume_sni_available(true).spawn().await { | ||
| 85 | + Ok(handle) => { | ||
| 86 | + while let Some(state) = state_receiver.recv().await { | ||
| 87 | + handle.update(|tray| tray.state = state).await; | ||
| 88 | + } | ||
| 89 | + std::future::pending::<()>().await | ||
| 90 | + } | ||
| 91 | + Err(error) => warn!("tray: {error}"), | ||
| 92 | + } | ||
| 93 | + }); | ||
| 94 | + }); | ||
| 95 | + | ||
| 96 | + (receiver, TrayHandle(state_sender)) | ||
| 130 | } | 97 | } |
| 131 | 98 | ||
| 132 | - fn activate(&mut self, _x: i32, _y: i32) { | 99 | + struct Tray { |
| 133 | - let _ = self.sender.send(TrayAction::Show); | 100 | + sender: mpsc::UnboundedSender<TrayAction>, |
| 101 | + state: TrayState, | ||
| 134 | } | 102 | } |
| 135 | 103 | ||
| 136 | - fn menu(&self) -> Vec<ksni::MenuItem<Self>> { | 104 | + impl ksni::Tray for Tray { |
| 137 | - use ksni::menu::StandardItem; | 105 | + fn id(&self) -> String { |
| 106 | + crate::NAME.to_string() | ||
| 107 | + } | ||
| 138 | 108 | ||
| 139 | - vec![ | 109 | + fn title(&self) -> String { |
| 140 | - StandardItem { | 110 | + crate::NAME.to_string() |
| 141 | - label: "Show".to_string(), | 111 | + } |
| 142 | - activate: Box::new(|tray: &mut Self| { | 112 | + |
| 143 | - let _ = tray.sender.send(TrayAction::Show); | 113 | + fn icon_pixmap(&self) -> Vec<ksni::Icon> { |
| 144 | - }), | 114 | + vec![icon(self.state.badge())] |
| 145 | - ..Default::default() | 115 | + } |
| 116 | + | ||
| 117 | + fn status(&self) -> ksni::Status { | ||
| 118 | + match self.state.badge() { | ||
| 119 | + Badge::Mention => ksni::Status::NeedsAttention, | ||
| 120 | + _ => ksni::Status::Active, | ||
| 146 | } | 121 | } |
| 147 | - .into(), | 122 | + } |
| 148 | - StandardItem { | 123 | + |
| 149 | - label: "Quit".to_string(), | 124 | + fn tool_tip(&self) -> ksni::ToolTip { |
| 150 | - activate: Box::new(|tray: &mut Self| { | 125 | + let description = match self.state.badge() { |
| 151 | - let _ = tray.sender.send(TrayAction::Quit); | 126 | + Badge::None => String::new(), |
| 152 | - }), | 127 | + _ => format!( |
| 128 | + "{} unread · {} mentions", | ||
| 129 | + self.state.messages, self.state.mentions | ||
| 130 | + ), | ||
| 131 | + }; | ||
| 132 | + ksni::ToolTip { | ||
| 133 | + title: crate::NAME.to_string(), | ||
| 134 | + description, | ||
| 153 | ..Default::default() | 135 | ..Default::default() |
| 154 | } | 136 | } |
| 155 | - .into(), | 137 | + } |
| 156 | - ] | ||
| 157 | - } | ||
| 158 | -} | ||
| 159 | 138 | ||
| 160 | -#[cfg(target_os = "linux")] | 139 | + fn activate(&mut self, _x: i32, _y: i32) { |
| 161 | -const ICON_SIZE: i32 = 32; | 140 | + let _ = self.sender.send(TrayAction::Show); |
| 162 | -#[cfg(target_os = "linux")] | 141 | + } |
| 163 | -const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; | ||
| 164 | -#[cfg(target_os = "linux")] | ||
| 165 | -const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; | ||
| 166 | -#[cfg(target_os = "linux")] | ||
| 167 | -const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); | ||
| 168 | -#[cfg(target_os = "linux")] | ||
| 169 | -const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; | ||
| 170 | -#[cfg(target_os = "linux")] | ||
| 171 | -const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; | ||
| 172 | 142 | ||
| 173 | -#[cfg(target_os = "linux")] | 143 | + fn menu(&self) -> Vec<ksni::MenuItem<Self>> { |
| 174 | -fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { | 144 | + use ksni::menu::StandardItem; |
| 175 | - let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); | ||
| 176 | - (radius - distance + 0.5).clamp(0.0, 1.0) | ||
| 177 | -} | ||
| 178 | 145 | ||
| 179 | -#[cfg(target_os = "linux")] | 146 | + vec![ |
| 180 | -fn icon(badge: Badge) -> ksni::Icon { | 147 | + StandardItem { |
| 181 | - let dot = match badge { | 148 | + label: "Show".to_string(), |
| 182 | - Badge::None => None, | 149 | + activate: Box::new(|tray: &mut Self| { |
| 183 | - Badge::Unread => Some(UNREAD_COLOR), | 150 | + let _ = tray.sender.send(TrayAction::Show); |
| 184 | - Badge::Mention => Some(MENTION_COLOR), | 151 | + }), |
| 185 | - }; | 152 | + ..Default::default() |
| 186 | - let data = (0..ICON_SIZE * ICON_SIZE) | ||
| 187 | - .flat_map(|index| { | ||
| 188 | - let x = (index % ICON_SIZE) as f32 + 0.5; | ||
| 189 | - let y = (index / ICON_SIZE) as f32 + 0.5; | ||
| 190 | - let base = ICON_DROPS | ||
| 191 | - .iter() | ||
| 192 | - .map(|drop| coverage(x, y, *drop)) | ||
| 193 | - .fold(0.0, f32::max); | ||
| 194 | - let ([red, green, blue], alpha) = match dot { | ||
| 195 | - Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), | ||
| 196 | - Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { | ||
| 197 | - (ICON_COLOR, 0.0) | ||
| 198 | } | 153 | } |
| 199 | - _ => (ICON_COLOR, base), | 154 | + .into(), |
| 200 | - }; | 155 | + StandardItem { |
| 201 | - [(alpha * 255.0) as u8, red, green, blue] | 156 | + label: "Quit".to_string(), |
| 202 | - }) | 157 | + activate: Box::new(|tray: &mut Self| { |
| 203 | - .collect(); | 158 | + let _ = tray.sender.send(TrayAction::Quit); |
| 204 | - | 159 | + }), |
| 205 | - ksni::Icon { | 160 | + ..Default::default() |
| 206 | - width: ICON_SIZE, | 161 | + } |
| 207 | - height: ICON_SIZE, | 162 | + .into(), |
| 208 | - data, | 163 | + ] |
| 164 | + } | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + const ICON_SIZE: i32 = 32; | ||
| 168 | + const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; | ||
| 169 | + const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; | ||
| 170 | + const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); | ||
| 171 | + const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; | ||
| 172 | + const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; | ||
| 173 | + | ||
| 174 | + fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { | ||
| 175 | + let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); | ||
| 176 | + (radius - distance + 0.5).clamp(0.0, 1.0) | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + fn icon(badge: Badge) -> ksni::Icon { | ||
| 180 | + let dot = match badge { | ||
| 181 | + Badge::None => None, | ||
| 182 | + Badge::Unread => Some(UNREAD_COLOR), | ||
| 183 | + Badge::Mention => Some(MENTION_COLOR), | ||
| 184 | + }; | ||
| 185 | + let data = (0..ICON_SIZE * ICON_SIZE) | ||
| 186 | + .flat_map(|index| { | ||
| 187 | + let x = (index % ICON_SIZE) as f32 + 0.5; | ||
| 188 | + let y = (index / ICON_SIZE) as f32 + 0.5; | ||
| 189 | + let base = ICON_DROPS | ||
| 190 | + .iter() | ||
| 191 | + .map(|drop| coverage(x, y, *drop)) | ||
| 192 | + .fold(0.0, f32::max); | ||
| 193 | + let ([red, green, blue], alpha) = match dot { | ||
| 194 | + Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), | ||
| 195 | + Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { | ||
| 196 | + (ICON_COLOR, 0.0) | ||
| 197 | + } | ||
| 198 | + _ => (ICON_COLOR, base), | ||
| 199 | + }; | ||
| 200 | + [(alpha * 255.0) as u8, red, green, blue] | ||
| 201 | + }) | ||
| 202 | + .collect(); | ||
| 203 | + | ||
| 204 | + ksni::Icon { | ||
| 205 | + width: ICON_SIZE, | ||
| 206 | + height: ICON_SIZE, | ||
| 207 | + data, | ||
| 208 | + } | ||
| 209 | } | 209 | } |
| 210 | } | 210 | } |
crates/client/src/voice/audio.rsmodified+1 -20
| @@ -22,14 +22,6 @@ mod backend; | |||
| 22 | #[cfg(target_os = "windows")] | 22 | #[cfg(target_os = "windows")] |
| 23 | #[path = "audio/wasapi.rs"] | 23 | #[path = "audio/wasapi.rs"] |
| 24 | mod backend; | 24 | mod backend; |
| 25 | -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] | ||
| 26 | -mod backend { | ||
| 27 | - use super::Devices; | ||
| 28 | - | ||
| 29 | - pub fn devices() -> Devices { | ||
| 30 | - Devices::default() | ||
| 31 | - } | ||
| 32 | -} | ||
| 33 | 25 | ||
| 34 | const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); | 26 | const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); |
| 35 | const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); | 27 | const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); |
| @@ -58,7 +50,6 @@ pub struct Choice { | |||
| 58 | pub enum Audio { | 50 | pub enum Audio { |
| 59 | Silent, | 51 | Silent, |
| 60 | Tone(Worker), | 52 | Tone(Worker), |
| 61 | - #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] | ||
| 62 | Device(backend::Backend), | 53 | Device(backend::Backend), |
| 63 | } | 54 | } |
| 64 | 55 | ||
| @@ -82,20 +73,10 @@ pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Au | |||
| 82 | Mode::Tone => Audio::Tone(Worker::spawn("voice-tone", move |stop| { | 73 | Mode::Tone => Audio::Tone(Worker::spawn("voice-tone", move |stop| { |
| 83 | tone(capture.as_ref(), &playback, stop) | 74 | tone(capture.as_ref(), &playback, stop) |
| 84 | })), | 75 | })), |
| 85 | - Mode::Device => device(capture, playback, choice), | 76 | + Mode::Device => Audio::Device(backend::start(capture, playback, choice)), |
| 86 | } | 77 | } |
| 87 | } | 78 | } |
| 88 | 79 | ||
| 89 | -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] | ||
| 90 | -fn device(capture: Option<Capture>, playback: Playback, choice: Choice) -> Audio { | ||
| 91 | - Audio::Device(backend::start(capture, playback, choice)) | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))] | ||
| 95 | -fn device(_: Option<Capture>, _: Playback, _: Choice) -> Audio { | ||
| 96 | - Audio::Silent | ||
| 97 | -} | ||
| 98 | - | ||
| 99 | pub fn devices() -> Devices { | 80 | pub fn devices() -> Devices { |
| 100 | match mode() { | 81 | match mode() { |
| 101 | Mode::Off | Mode::Tone => Devices::default(), | 82 | Mode::Off | Mode::Tone => Devices::default(), |
crates/client/src/voice/audio/coreaudio.rsmodified+25 -59
| @@ -76,26 +76,21 @@ fn attempt( | |||
| 76 | stop: &AtomicBool, | 76 | stop: &AtomicBool, |
| 77 | ) -> Result<(), Box<dyn StdError>> { | 77 | ) -> Result<(), Box<dyn StdError>> { |
| 78 | let output_id = output_device(choice); | 78 | let output_id = output_device(choice); |
| 79 | - let mut output = playback_unit(playback.clone(), output_id.0)?; | 79 | + let _output = playback_unit(playback.clone(), output_id.0)?; |
| 80 | let device = capture.and_then(|_| input_device(choice)); | 80 | let device = capture.and_then(|_| input_device(choice)); |
| 81 | - let mut input = capture.zip(device).and_then(|(capture, device)| { | 81 | + let input = capture.zip(device).and_then(|(capture, device)| { |
| 82 | capture_unit(device, capture.clone()) | 82 | capture_unit(device, capture.clone()) |
| 83 | .inspect_err(|error| warn!("voice capture unavailable: {error}")) | 83 | .inspect_err(|error| warn!("voice capture unavailable: {error}")) |
| 84 | .ok() | 84 | .ok() |
| 85 | }); | 85 | }); |
| 86 | - let outcome = watch( | 86 | + watch( |
| 87 | stop, | 87 | stop, |
| 88 | choice, | 88 | choice, |
| 89 | capture.is_some(), | 89 | capture.is_some(), |
| 90 | input.as_ref(), | 90 | input.as_ref(), |
| 91 | device, | 91 | device, |
| 92 | output_id, | 92 | output_id, |
| 93 | - ); | 93 | + )?; |
| 94 | - stop_unit(&mut output); | ||
| 95 | - if let Some((unit, _)) = input.as_mut() { | ||
| 96 | - stop_unit(unit); | ||
| 97 | - } | ||
| 98 | - outcome?; | ||
| 99 | Ok(()) | 94 | Ok(()) |
| 100 | } | 95 | } |
| 101 | 96 | ||
| @@ -126,12 +121,6 @@ fn watch( | |||
| 126 | Ok(()) | 121 | Ok(()) |
| 127 | } | 122 | } |
| 128 | 123 | ||
| 129 | -fn stop_unit(unit: &mut AudioUnit) { | ||
| 130 | - if let Err(error) = unit.stop() { | ||
| 131 | - warn!("voice audio stop failed: {error}"); | ||
| 132 | - } | ||
| 133 | -} | ||
| 134 | - | ||
| 135 | fn format(sample_rate: f64, channels: u32) -> StreamFormat { | 124 | fn format(sample_rate: f64, channels: u32) -> StreamFormat { |
| 136 | StreamFormat { | 125 | StreamFormat { |
| 137 | sample_rate, | 126 | sample_rate, |
| @@ -182,6 +171,7 @@ fn capture_unit(device: u32, capture: Capture) -> Result<(AudioUnit, f64), Error | |||
| 182 | let mut resampler = (rate != f64::from(VOICE_SAMPLE_RATE)).then(|| Resampler::new(rate)); | 171 | let mut resampler = (rate != f64::from(VOICE_SAMPLE_RATE)).then(|| Resampler::new(rate)); |
| 183 | let mut downmix = Downmix::default(); | 172 | let mut downmix = Downmix::default(); |
| 184 | let mut mixed = Vec::new(); | 173 | let mut mixed = Vec::new(); |
| 174 | + let mut resampled = Vec::new(); | ||
| 185 | unit.set_input_callback(move |args: Args| { | 175 | unit.set_input_callback(move |args: Args| { |
| 186 | let Args { data, .. } = args; | 176 | let Args { data, .. } = args; |
| 187 | let mut channels = data.channels(); | 177 | let mut channels = data.channels(); |
| @@ -193,7 +183,10 @@ fn capture_unit(device: u32, capture: Capture) -> Result<(AudioUnit, f64), Error | |||
| 193 | mixed.clear(); | 183 | mixed.clear(); |
| 194 | mixed.extend(downmix.mix(frames)); | 184 | mixed.extend(downmix.mix(frames)); |
| 195 | match resampler.as_mut() { | 185 | match resampler.as_mut() { |
| 196 | - Some(resampler) => record(&capture, resampler.resample(&mixed)), | 186 | + Some(resampler) => { |
| 187 | + resampler.resample(&mixed, &mut resampled); | ||
| 188 | + record(&capture, resampled.iter().copied()); | ||
| 189 | + } | ||
| 197 | None => record(&capture, mixed.iter().copied()), | 190 | None => record(&capture, mixed.iter().copied()), |
| 198 | } | 191 | } |
| 199 | Ok(()) | 192 | Ok(()) |
| @@ -218,50 +211,23 @@ impl Resampler { | |||
| 218 | } | 211 | } |
| 219 | } | 212 | } |
| 220 | 213 | ||
| 221 | - fn resample<'a>(&'a mut self, input: &'a [f32]) -> Resampled<'a> { | 214 | + fn resample(&mut self, input: &[f32], out: &mut Vec<f32>) { |
| 222 | - Resampled { | 215 | + out.clear(); |
| 223 | - resampler: self, | 216 | + while (self.position as usize) < input.len() { |
| 224 | - input, | 217 | + let index = self.position as usize; |
| 218 | + let fraction = (self.position - index as f64) as f32; | ||
| 219 | + let a = if index == 0 { | ||
| 220 | + self.previous | ||
| 221 | + } else { | ||
| 222 | + input[index - 1] | ||
| 223 | + }; | ||
| 224 | + let b = input[index]; | ||
| 225 | + out.push(a + (b - a) * fraction); | ||
| 226 | + self.position += self.step; | ||
| 225 | } | 227 | } |
| 226 | - } | 228 | + self.position -= input.len() as f64; |
| 227 | -} | 229 | + if let Some(&last) = input.last() { |
| 228 | - | 230 | + self.previous = last; |
| 229 | -struct Resampled<'a> { | ||
| 230 | - resampler: &'a mut Resampler, | ||
| 231 | - input: &'a [f32], | ||
| 232 | -} | ||
| 233 | - | ||
| 234 | -impl Resampled<'_> { | ||
| 235 | - fn at(&self, index: usize) -> f32 { | ||
| 236 | - if index == 0 { | ||
| 237 | - self.resampler.previous | ||
| 238 | - } else { | ||
| 239 | - self.input[index - 1] | ||
| 240 | - } | ||
| 241 | - } | ||
| 242 | -} | ||
| 243 | - | ||
| 244 | -impl Iterator for Resampled<'_> { | ||
| 245 | - type Item = f32; | ||
| 246 | - | ||
| 247 | - fn next(&mut self) -> Option<f32> { | ||
| 248 | - let index = self.resampler.position as usize; | ||
| 249 | - if index >= self.input.len() { | ||
| 250 | - return None; | ||
| 251 | - } | ||
| 252 | - let fraction = (self.resampler.position - index as f64) as f32; | ||
| 253 | - let (a, b) = (self.at(index), self.at(index + 1)); | ||
| 254 | - self.resampler.position += self.resampler.step; | ||
| 255 | - Some(a + (b - a) * fraction) | ||
| 256 | - } | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | -impl Drop for Resampled<'_> { | ||
| 260 | - fn drop(&mut self) { | ||
| 261 | - for _ in self.by_ref() {} | ||
| 262 | - self.resampler.position -= self.input.len() as f64; | ||
| 263 | - if let Some(&last) = self.input.last() { | ||
| 264 | - self.resampler.previous = last; | ||
| 265 | } | 231 | } |
| 266 | } | 232 | } |
| 267 | } | 233 | } |
crates/client/src/voice/audio/pipewire.rsmodified+60 -65
| @@ -7,7 +7,13 @@ use std::{ | |||
| 7 | 7 | ||
| 8 | use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; | 8 | use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; |
| 9 | use pipewire as pw; | 9 | use pipewire as pw; |
| 10 | -use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType}; | 10 | +use pw::{ |
| 11 | + loop_::Timeout, | ||
| 12 | + properties::properties, | ||
| 13 | + spa, | ||
| 14 | + stream::{StreamBox, StreamListener, StreamState}, | ||
| 15 | + types::ObjectType, | ||
| 16 | +}; | ||
| 11 | use spa::pod::Pod; | 17 | use spa::pod::Pod; |
| 12 | 18 | ||
| 13 | use super::{ | 19 | use super::{ |
| @@ -16,9 +22,7 @@ use super::{ | |||
| 16 | }; | 22 | }; |
| 17 | use crate::voice::{Capture, Playback}; | 23 | use crate::voice::{Capture, Playback}; |
| 18 | 24 | ||
| 19 | -pub struct Backend { | 25 | +pub type Backend = Worker; |
| 20 | - _worker: Worker, | ||
| 21 | -} | ||
| 22 | 26 | ||
| 23 | pub fn devices() -> Devices { | 27 | pub fn devices() -> Devices { |
| 24 | collect_devices().unwrap_or_default() | 28 | collect_devices().unwrap_or_default() |
| @@ -32,7 +36,6 @@ fn collect_devices() -> Result<Devices, Box<dyn Error>> { | |||
| 32 | let registry = core.get_registry_rc()?; | 36 | let registry = core.get_registry_rc()?; |
| 33 | 37 | ||
| 34 | let devices = Rc::new(RefCell::new(Devices::default())); | 38 | let devices = Rc::new(RefCell::new(Devices::default())); |
| 35 | - let done = Rc::new(Cell::new(false)); | ||
| 36 | let failed = Rc::new(Cell::new(false)); | 39 | let failed = Rc::new(Cell::new(false)); |
| 37 | 40 | ||
| 38 | let pending = core.sync(0)?; | 41 | let pending = core.sync(0)?; |
| @@ -40,22 +43,18 @@ fn collect_devices() -> Result<Devices, Box<dyn Error>> { | |||
| 40 | let _core_listener = core | 43 | let _core_listener = core |
| 41 | .add_listener_local() | 44 | .add_listener_local() |
| 42 | .done({ | 45 | .done({ |
| 43 | - let done = done.clone(); | ||
| 44 | let mainloop = mainloop.clone(); | 46 | let mainloop = mainloop.clone(); |
| 45 | move |id, seq| { | 47 | move |id, seq| { |
| 46 | if id == pw::core::PW_ID_CORE && seq == pending { | 48 | if id == pw::core::PW_ID_CORE && seq == pending { |
| 47 | - done.set(true); | ||
| 48 | mainloop.quit(); | 49 | mainloop.quit(); |
| 49 | } | 50 | } |
| 50 | } | 51 | } |
| 51 | }) | 52 | }) |
| 52 | .error({ | 53 | .error({ |
| 53 | - let done = done.clone(); | ||
| 54 | let failed = failed.clone(); | 54 | let failed = failed.clone(); |
| 55 | let mainloop = mainloop.clone(); | 55 | let mainloop = mainloop.clone(); |
| 56 | move |_, _, _, _| { | 56 | move |_, _, _, _| { |
| 57 | failed.set(true); | 57 | failed.set(true); |
| 58 | - done.set(true); | ||
| 59 | mainloop.quit(); | 58 | mainloop.quit(); |
| 60 | } | 59 | } |
| 61 | }) | 60 | }) |
| @@ -75,9 +74,6 @@ fn collect_devices() -> Result<Devices, Box<dyn Error>> { | |||
| 75 | let Some(node) = props.get(*pw::keys::NODE_NAME) else { | 74 | let Some(node) = props.get(*pw::keys::NODE_NAME) else { |
| 76 | return; | 75 | return; |
| 77 | }; | 76 | }; |
| 78 | - if node == "yumush" { | ||
| 79 | - return; | ||
| 80 | - } | ||
| 81 | let device = Device { | 77 | let device = Device { |
| 82 | id: node.to_string(), | 78 | id: node.to_string(), |
| 83 | name: props | 79 | name: props |
| @@ -95,9 +91,7 @@ fn collect_devices() -> Result<Devices, Box<dyn Error>> { | |||
| 95 | }) | 91 | }) |
| 96 | .register(); | 92 | .register(); |
| 97 | 93 | ||
| 98 | - while !done.get() { | 94 | + mainloop.run(); |
| 99 | - mainloop.run(); | ||
| 100 | - } | ||
| 101 | 95 | ||
| 102 | if failed.get() { | 96 | if failed.get() { |
| 103 | return Err("pipewire devices".into()); | 97 | return Err("pipewire devices".into()); |
| @@ -106,13 +100,11 @@ fn collect_devices() -> Result<Devices, Box<dyn Error>> { | |||
| 106 | } | 100 | } |
| 107 | 101 | ||
| 108 | pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend { | 102 | pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend { |
| 109 | - Backend { | 103 | + Worker::spawn("voice-audio", move |stop| { |
| 110 | - _worker: Worker::spawn("voice-audio", move |stop| { | 104 | + supervise("voice audio", stop, || { |
| 111 | - supervise("voice audio", stop, || { | 105 | + run(capture.as_ref(), &playback, &choice, stop) |
| 112 | - run(capture.as_ref(), &playback, &choice, stop) | 106 | + }) |
| 113 | - }) | 107 | + }) |
| 114 | - }), | ||
| 115 | - } | ||
| 116 | } | 108 | } |
| 117 | 109 | ||
| 118 | fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::PropertiesBox { | 110 | fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::PropertiesBox { |
| @@ -185,49 +177,10 @@ fn run( | |||
| 185 | | pw::stream::StreamFlags::MAP_BUFFERS | 177 | | pw::stream::StreamFlags::MAP_BUFFERS |
| 186 | | pw::stream::StreamFlags::RT_PROCESS; | 178 | | pw::stream::StreamFlags::RT_PROCESS; |
| 187 | 179 | ||
| 188 | - let capture_stream = pw::stream::StreamBox::new( | 180 | + let _capture = capture |
| 189 | - &core, | 181 | + .cloned() |
| 190 | - "yumush-capture", | 182 | + .map(|capture| capture_stream(&core, capture, choice, &failed, &capture_values, flags)) |
| 191 | - stream_properties("Capture", choice.input.as_deref()), | 183 | + .transpose()?; |
| 192 | - )?; | ||
| 193 | - let capture = capture.cloned(); | ||
| 194 | - let connect_capture = capture.is_some(); | ||
| 195 | - let _capture_listener = capture_stream | ||
| 196 | - .add_local_listener_with_user_data(()) | ||
| 197 | - .state_changed(state_watch(&failed)) | ||
| 198 | - .process(move |stream, _| { | ||
| 199 | - let Some(mut buffer) = stream.dequeue_buffer() else { | ||
| 200 | - return; | ||
| 201 | - }; | ||
| 202 | - let Some(data) = buffer.datas_mut().first_mut() else { | ||
| 203 | - return; | ||
| 204 | - }; | ||
| 205 | - let size = data.chunk().size() as usize; | ||
| 206 | - let Some(bytes) = data.data() else { | ||
| 207 | - return; | ||
| 208 | - }; | ||
| 209 | - let bytes = &bytes[..size.min(bytes.len())]; | ||
| 210 | - let Some(capture) = &capture else { | ||
| 211 | - return; | ||
| 212 | - }; | ||
| 213 | - let samples = bytes | ||
| 214 | - .as_chunks::<4>() | ||
| 215 | - .0 | ||
| 216 | - .iter() | ||
| 217 | - .copied() | ||
| 218 | - .map(f32::from_le_bytes); | ||
| 219 | - record(capture, samples); | ||
| 220 | - }) | ||
| 221 | - .register()?; | ||
| 222 | - if connect_capture { | ||
| 223 | - let mut capture_params = [Pod::from_bytes(&capture_values).ok_or("pipewire format")?]; | ||
| 224 | - capture_stream.connect( | ||
| 225 | - spa::utils::Direction::Input, | ||
| 226 | - None, | ||
| 227 | - flags, | ||
| 228 | - &mut capture_params, | ||
| 229 | - )?; | ||
| 230 | - } | ||
| 231 | 184 | ||
| 232 | let playback_stream = pw::stream::StreamBox::new( | 185 | let playback_stream = pw::stream::StreamBox::new( |
| 233 | &core, | 186 | &core, |
| @@ -283,6 +236,48 @@ fn run( | |||
| 283 | Ok(()) | 236 | Ok(()) |
| 284 | } | 237 | } |
| 285 | 238 | ||
| 239 | +fn capture_stream<'c>( | ||
| 240 | + core: &'c pw::core::Core, | ||
| 241 | + capture: Capture, | ||
| 242 | + choice: &Choice, | ||
| 243 | + failed: &Rc<Cell<bool>>, | ||
| 244 | + values: &[u8], | ||
| 245 | + flags: pw::stream::StreamFlags, | ||
| 246 | +) -> Result<(StreamListener<()>, StreamBox<'c>), Box<dyn Error>> { | ||
| 247 | + let stream = StreamBox::new( | ||
| 248 | + core, | ||
| 249 | + "yumush-capture", | ||
| 250 | + stream_properties("Capture", choice.input.as_deref()), | ||
| 251 | + )?; | ||
| 252 | + let listener = stream | ||
| 253 | + .add_local_listener_with_user_data(()) | ||
| 254 | + .state_changed(state_watch(failed)) | ||
| 255 | + .process(move |stream, _| { | ||
| 256 | + let Some(mut buffer) = stream.dequeue_buffer() else { | ||
| 257 | + return; | ||
| 258 | + }; | ||
| 259 | + let Some(data) = buffer.datas_mut().first_mut() else { | ||
| 260 | + return; | ||
| 261 | + }; | ||
| 262 | + let size = data.chunk().size() as usize; | ||
| 263 | + let Some(bytes) = data.data() else { | ||
| 264 | + return; | ||
| 265 | + }; | ||
| 266 | + let bytes = &bytes[..size.min(bytes.len())]; | ||
| 267 | + let samples = bytes | ||
| 268 | + .as_chunks::<4>() | ||
| 269 | + .0 | ||
| 270 | + .iter() | ||
| 271 | + .copied() | ||
| 272 | + .map(f32::from_le_bytes); | ||
| 273 | + record(&capture, samples); | ||
| 274 | + }) | ||
| 275 | + .register()?; | ||
| 276 | + let mut params = [Pod::from_bytes(values).ok_or("pipewire format")?]; | ||
| 277 | + stream.connect(spa::utils::Direction::Input, None, flags, &mut params)?; | ||
| 278 | + Ok((listener, stream)) | ||
| 279 | +} | ||
| 280 | + | ||
| 286 | fn state_watch( | 281 | fn state_watch( |
| 287 | failed: &Rc<Cell<bool>>, | 282 | failed: &Rc<Cell<bool>>, |
| 288 | ) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static { | 283 | ) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static { |
crates/client/src/voice/audio/wasapi.rsmodified+37 -40
| @@ -20,12 +20,10 @@ use crate::voice::{Capture, Playback}; | |||
| 20 | 20 | ||
| 21 | const CHECK_DEFAULT_EVERY: Duration = Duration::from_secs(1); | 21 | const CHECK_DEFAULT_EVERY: Duration = Duration::from_secs(1); |
| 22 | 22 | ||
| 23 | -pub struct Backend { | 23 | +pub type Backend = Vec<Worker>; |
| 24 | - _workers: Vec<Worker>, | ||
| 25 | -} | ||
| 26 | 24 | ||
| 27 | struct Target<'a> { | 25 | struct Target<'a> { |
| 28 | - enumerator: &'a DeviceEnumerator, | 26 | + enumerator: DeviceEnumerator, |
| 29 | direction: Direction, | 27 | direction: Direction, |
| 30 | id: String, | 28 | id: String, |
| 31 | choice: Option<&'a str>, | 29 | choice: Option<&'a str>, |
| @@ -72,23 +70,24 @@ fn list( | |||
| 72 | pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend { | 70 | pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend { |
| 73 | let input = choice.input; | 71 | let input = choice.input; |
| 74 | let output = choice.output; | 72 | let output = choice.output; |
| 75 | - let mut workers = vec![Worker::spawn("voice render", move |stop| { | 73 | + let mut workers = vec![worker("voice render", move |stop| { |
| 76 | - with_com(|| { | 74 | + run_render(&playback, stop, output.as_deref()) |
| 77 | - supervise("voice render", stop, || { | ||
| 78 | - run_render(&playback, stop, output.as_deref()) | ||
| 79 | - }) | ||
| 80 | - }) | ||
| 81 | })]; | 75 | })]; |
| 82 | if let Some(capture) = capture { | 76 | if let Some(capture) = capture { |
| 83 | - workers.push(Worker::spawn("voice capture", move |stop| { | 77 | + workers.push(worker("voice capture", move |stop| { |
| 84 | - with_com(|| { | 78 | + run_capture(&capture, stop, input.as_deref()) |
| 85 | - supervise("voice capture", stop, || { | ||
| 86 | - run_capture(&capture, stop, input.as_deref()) | ||
| 87 | - }) | ||
| 88 | - }) | ||
| 89 | })); | 79 | })); |
| 90 | } | 80 | } |
| 91 | - Backend { _workers: workers } | 81 | + workers |
| 82 | +} | ||
| 83 | + | ||
| 84 | +fn worker( | ||
| 85 | + name: &'static str, | ||
| 86 | + mut run: impl FnMut(&AtomicBool) -> Result<(), Box<dyn Error>> + Send + 'static, | ||
| 87 | +) -> Worker { | ||
| 88 | + Worker::spawn(name, move |stop| { | ||
| 89 | + with_com(|| supervise(name, stop, || run(stop))) | ||
| 90 | + }) | ||
| 92 | } | 91 | } |
| 93 | 92 | ||
| 94 | fn with_com<T: Default>(body: impl FnOnce() -> T) -> T { | 93 | fn with_com<T: Default>(body: impl FnOnce() -> T) -> T { |
| @@ -170,34 +169,42 @@ fn default_changed(target: &Target, checked: &mut Instant) -> Result<bool, Box<d | |||
| 170 | *checked = Instant::now(); | 169 | *checked = Instant::now(); |
| 171 | match target.choice { | 170 | match target.choice { |
| 172 | Some(chosen) if chosen == target.id => Ok(false), | 171 | Some(chosen) if chosen == target.id => Ok(false), |
| 173 | - Some(chosen) if find_device(target.enumerator, target.direction, chosen).is_some() => { | 172 | + Some(chosen) if find_device(&target.enumerator, target.direction, chosen).is_some() => { |
| 174 | Ok(true) | 173 | Ok(true) |
| 175 | } | 174 | } |
| 176 | - _ => Ok(default_id(target.enumerator, target.direction)? != target.id), | 175 | + _ => Ok(default_id(&target.enumerator, target.direction)? != target.id), |
| 177 | } | 176 | } |
| 178 | } | 177 | } |
| 179 | 178 | ||
| 180 | -fn run_capture( | 179 | +fn open( |
| 181 | - capture: &Capture, | 180 | + direction: Direction, |
| 182 | - stop: &AtomicBool, | ||
| 183 | choice: Option<&str>, | 181 | choice: Option<&str>, |
| 184 | -) -> Result<(), Box<dyn Error>> { | 182 | +) -> Result<(Target<'_>, AudioClient, Handle), Box<dyn Error>> { |
| 185 | let enumerator = DeviceEnumerator::new()?; | 183 | let enumerator = DeviceEnumerator::new()?; |
| 186 | - let device = open_device(&enumerator, Direction::Capture, choice)?; | 184 | + let device = open_device(&enumerator, direction, choice)?; |
| 187 | let target = Target { | 185 | let target = Target { |
| 188 | - enumerator: &enumerator, | ||
| 189 | - direction: Direction::Capture, | ||
| 190 | id: device.get_id()?, | 186 | id: device.get_id()?, |
| 187 | + enumerator, | ||
| 188 | + direction, | ||
| 191 | choice, | 189 | choice, |
| 192 | }; | 190 | }; |
| 193 | let mut client = device.get_iaudioclient()?; | 191 | let mut client = device.get_iaudioclient()?; |
| 194 | - init_shared_event(&mut client, Direction::Capture)?; | 192 | + init_shared_event(&mut client, direction)?; |
| 195 | let event = client.set_get_eventhandle()?; | 193 | let event = client.set_get_eventhandle()?; |
| 194 | + Ok((target, client, event)) | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +fn run_capture( | ||
| 198 | + capture: &Capture, | ||
| 199 | + stop: &AtomicBool, | ||
| 200 | + choice: Option<&str>, | ||
| 201 | +) -> Result<(), Box<dyn Error>> { | ||
| 202 | + let (target, client, event) = open(Direction::Capture, choice)?; | ||
| 196 | let reader = client.get_audiocaptureclient()?; | 203 | let reader = client.get_audiocaptureclient()?; |
| 197 | 204 | ||
| 198 | client.start_stream()?; | 205 | client.start_stream()?; |
| 199 | let result = capture_frames(capture, stop, &target, &event, &reader); | 206 | let result = capture_frames(capture, stop, &target, &event, &reader); |
| 200 | - client.stop_stream()?; | 207 | + let _ = client.stop_stream(); |
| 201 | result | 208 | result |
| 202 | } | 209 | } |
| 203 | 210 | ||
| @@ -236,17 +243,7 @@ fn run_render( | |||
| 236 | stop: &AtomicBool, | 243 | stop: &AtomicBool, |
| 237 | choice: Option<&str>, | 244 | choice: Option<&str>, |
| 238 | ) -> Result<(), Box<dyn Error>> { | 245 | ) -> Result<(), Box<dyn Error>> { |
| 239 | - let enumerator = DeviceEnumerator::new()?; | 246 | + let (target, client, event) = open(Direction::Render, choice)?; |
| 240 | - let device = open_device(&enumerator, Direction::Render, choice)?; | ||
| 241 | - let target = Target { | ||
| 242 | - enumerator: &enumerator, | ||
| 243 | - direction: Direction::Render, | ||
| 244 | - id: device.get_id()?, | ||
| 245 | - choice, | ||
| 246 | - }; | ||
| 247 | - let mut client = device.get_iaudioclient()?; | ||
| 248 | - init_shared_event(&mut client, Direction::Render)?; | ||
| 249 | - let event = client.set_get_eventhandle()?; | ||
| 250 | let writer = client.get_audiorenderclient()?; | 247 | let writer = client.get_audiorenderclient()?; |
| 251 | 248 | ||
| 252 | let silence = vec![0u8; client.get_available_space_in_frames()? as usize * BYTES_PER_FRAME]; | 249 | let silence = vec![0u8; client.get_available_space_in_frames()? as usize * BYTES_PER_FRAME]; |
| @@ -254,7 +251,7 @@ fn run_render( | |||
| 254 | 251 | ||
| 255 | client.start_stream()?; | 252 | client.start_stream()?; |
| 256 | let result = render_frames(playback, stop, &target, &event, &client, &writer); | 253 | let result = render_frames(playback, stop, &target, &event, &client, &writer); |
| 257 | - client.stop_stream()?; | 254 | + let _ = client.stop_stream(); |
| 258 | result | 255 | result |
| 259 | } | 256 | } |
| 260 | 257 | ||
crates/client/src/voice/engine.rsmodified+2 -2
| @@ -116,7 +116,7 @@ impl Speaker { | |||
| 116 | fn decode_next(&mut self) -> (Vec<f32>, bool) { | 116 | fn decode_next(&mut self) -> (Vec<f32>, bool) { |
| 117 | let (decoded, real) = match ( | 117 | let (decoded, real) = match ( |
| 118 | self.jitter.remove(&self.next), | 118 | self.jitter.remove(&self.next), |
| 119 | - self.jitter.get(&(self.next + 1)), | 119 | + self.jitter.get(&self.next.wrapping_add(1)), |
| 120 | ) { | 120 | ) { |
| 121 | (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true), | 121 | (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true), |
| 122 | (None, Some(following)) => ( | 122 | (None, Some(following)) => ( |
| @@ -129,7 +129,7 @@ impl Speaker { | |||
| 129 | false, | 129 | false, |
| 130 | ), | 130 | ), |
| 131 | }; | 131 | }; |
| 132 | - self.next += 1; | 132 | + self.next = self.next.wrapping_add(1); |
| 133 | 133 | ||
| 134 | let samples = match decoded { | 134 | let samples = match decoded { |
| 135 | Ok(samples) => self.scratch[..samples].to_vec(), | 135 | Ok(samples) => self.scratch[..samples].to_vec(), |
crates/client/src/voice/mod.rsmodified+12 -31
| @@ -3,7 +3,6 @@ use std::{ | |||
| 3 | Arc, Mutex, | 3 | Arc, Mutex, |
| 4 | atomic::{AtomicBool, Ordering}, | 4 | atomic::{AtomicBool, Ordering}, |
| 5 | }, | 5 | }, |
| 6 | - thread::JoinHandle, | ||
| 7 | time::Duration, | 6 | time::Duration, |
| 8 | }; | 7 | }; |
| 9 | 8 | ||
| @@ -14,13 +13,12 @@ use common::{ | |||
| 14 | }; | 13 | }; |
| 15 | use quinn::Connection; | 14 | use quinn::Connection; |
| 16 | use rtrb::{Consumer, Producer, RingBuffer}; | 15 | use rtrb::{Consumer, Producer, RingBuffer}; |
| 17 | -use tracing::warn; | ||
| 18 | 16 | ||
| 19 | pub mod audio; | 17 | pub mod audio; |
| 20 | pub mod engine; | 18 | pub mod engine; |
| 21 | 19 | ||
| 22 | use crate::settings::VoiceSettings; | 20 | use crate::settings::VoiceSettings; |
| 23 | -use audio::{Audio, Choice}; | 21 | +use audio::{Audio, Choice, Worker}; |
| 24 | use engine::{Engine, SILENT_DB, Traffic}; | 22 | use engine::{Engine, SILENT_DB, Traffic}; |
| 25 | 23 | ||
| 26 | const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; | 24 | const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; |
| @@ -45,8 +43,7 @@ pub struct VoiceSample { | |||
| 45 | pub struct Voice { | 43 | pub struct Voice { |
| 46 | engine: Arc<Mutex<Engine>>, | 44 | engine: Arc<Mutex<Engine>>, |
| 47 | connection: Option<Connection>, | 45 | connection: Option<Connection>, |
| 48 | - stop: Arc<AtomicBool>, | 46 | + _worker: Worker, |
| 49 | - worker: Option<JoinHandle<()>>, | ||
| 50 | capture: Capture, | 47 | capture: Capture, |
| 51 | playback: Playback, | 48 | playback: Playback, |
| 52 | choice: Choice, | 49 | choice: Choice, |
| @@ -55,7 +52,6 @@ pub struct Voice { | |||
| 55 | 52 | ||
| 56 | pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice { | 53 | pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice { |
| 57 | let engine = Arc::new(Mutex::new(Engine::new())); | 54 | let engine = Arc::new(Mutex::new(Engine::new())); |
| 58 | - let stop = Arc::new(AtomicBool::new(false)); | ||
| 59 | let (capture_producer, from_capture) = RingBuffer::new(RING_SAMPLES); | 55 | let (capture_producer, from_capture) = RingBuffer::new(RING_SAMPLES); |
| 60 | let (to_playback, playback_consumer) = RingBuffer::new(PLAYBACK_RING); | 56 | let (to_playback, playback_consumer) = RingBuffer::new(PLAYBACK_RING); |
| 61 | let capture: Capture = Arc::new(Mutex::new(capture_producer)); | 57 | let capture: Capture = Arc::new(Mutex::new(capture_producer)); |
| @@ -69,27 +65,21 @@ pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice | |||
| 69 | let link = connection.clone(); | 65 | let link = connection.clone(); |
| 70 | let worker = { | 66 | let worker = { |
| 71 | let engine = engine.clone(); | 67 | let engine = engine.clone(); |
| 72 | - let stop = stop.clone(); | 68 | + Worker::spawn("voice-worker", move |stop| { |
| 73 | - std::thread::Builder::new() | 69 | + work( |
| 74 | - .name("voice-worker".to_string()) | 70 | + &engine, |
| 75 | - .spawn(move || { | 71 | + connection.as_ref(), |
| 76 | - work( | 72 | + from_capture, |
| 77 | - &engine, | 73 | + to_playback, |
| 78 | - connection.as_ref(), | 74 | + stop, |
| 79 | - from_capture, | 75 | + ) |
| 80 | - to_playback, | 76 | + }) |
| 81 | - &stop, | ||
| 82 | - ) | ||
| 83 | - }) | ||
| 84 | - .inspect_err(|error| warn!("voice worker not started: {error}")) | ||
| 85 | - .ok() | ||
| 86 | }; | 77 | }; |
| 87 | 78 | ||
| 88 | let mut voice = Voice { | 79 | let mut voice = Voice { |
| 89 | engine, | 80 | engine, |
| 90 | connection: link, | 81 | connection: link, |
| 91 | - stop, | 82 | + _worker: worker, |
| 92 | - worker, | ||
| 93 | capture, | 83 | capture, |
| 94 | playback, | 84 | playback, |
| 95 | choice: settings.choice.clone(), | 85 | choice: settings.choice.clone(), |
| @@ -335,12 +325,3 @@ impl Voice { | |||
| 335 | self.with_engine((), |engine| engine.set_talking(talking)); | 325 | self.with_engine((), |engine| engine.set_talking(talking)); |
| 336 | } | 326 | } |
| 337 | } | 327 | } |
| 338 | - | ||
| 339 | -impl Drop for Voice { | ||
| 340 | - fn drop(&mut self) { | ||
| 341 | - self.stop.store(true, Ordering::Relaxed); | ||
| 342 | - if let Some(worker) = self.worker.take() { | ||
| 343 | - let _ = worker.join(); | ||
| 344 | - } | ||
| 345 | - } | ||
| 346 | -} | ||
crates/common/src/error.rsmodified+7 -23
| @@ -4,29 +4,15 @@ use bitcode::{Decode, Encode}; | |||
| 4 | 4 | ||
| 5 | #[macro_export] | 5 | #[macro_export] |
| 6 | macro_rules! error_from { | 6 | macro_rules! error_from { |
| 7 | - ($target:ty { $($rest:tt)* }) => { | 7 | + ($target:ty { $($source:ty => $variant:path as $middle:ty),+ $(,)? }) => { |
| 8 | - $crate::error_from!(@arm $target, $($rest)*); | 8 | + $( |
| 9 | - }; | 9 | + impl From<$source> for $target { |
| 10 | - | 10 | + fn from(value: $source) -> Self { |
| 11 | - (@arm $target:ty, $source:ty => $variant:path as $middle:ty, $($rest:tt)*) => { | 11 | + $variant(<$middle>::from(value)) |
| 12 | - impl From<$source> for $target { | 12 | + } |
| 13 | - fn from(value: $source) -> Self { | ||
| 14 | - $variant(<$middle>::from(value).into()) | ||
| 15 | - } | ||
| 16 | - } | ||
| 17 | - $crate::error_from!(@arm $target, $($rest)*); | ||
| 18 | - }; | ||
| 19 | - | ||
| 20 | - (@arm $target:ty, $source:ty => $variant:path, $($rest:tt)*) => { | ||
| 21 | - impl From<$source> for $target { | ||
| 22 | - fn from(value: $source) -> Self { | ||
| 23 | - $variant(value) | ||
| 24 | } | 13 | } |
| 25 | - } | 14 | + )+ |
| 26 | - $crate::error_from!(@arm $target, $($rest)*); | ||
| 27 | }; | 15 | }; |
| 28 | - | ||
| 29 | - (@arm $target:ty,) => {}; | ||
| 30 | } | 16 | } |
| 31 | 17 | ||
| 32 | macro_rules! from_display { | 18 | macro_rules! from_display { |
| @@ -47,7 +33,6 @@ pub enum InvalidInput { | |||
| 47 | TooLong { maximum: usize, actual: usize }, | 33 | TooLong { maximum: usize, actual: usize }, |
| 48 | TooLarge { maximum: u64, actual: u64 }, | 34 | TooLarge { maximum: u64, actual: u64 }, |
| 49 | Empty, | 35 | Empty, |
| 50 | - NotASCII, | ||
| 51 | MultiLine, | 36 | MultiLine, |
| 52 | ForbiddenCharacter, | 37 | ForbiddenCharacter, |
| 53 | NotJpeg, | 38 | NotJpeg, |
| @@ -81,7 +66,6 @@ impl Display for InvalidInput { | |||
| 81 | ) | 66 | ) |
| 82 | } | 67 | } |
| 83 | InvalidInput::Empty => write!(f, "empty"), | 68 | InvalidInput::Empty => write!(f, "empty"), |
| 84 | - InvalidInput::NotASCII => write!(f, "not ASCII"), | ||
| 85 | InvalidInput::MultiLine => write!(f, "contains line break"), | 69 | InvalidInput::MultiLine => write!(f, "contains line break"), |
| 86 | InvalidInput::ForbiddenCharacter => write!(f, "contains forbidden character"), | 70 | InvalidInput::ForbiddenCharacter => write!(f, "contains forbidden character"), |
| 87 | InvalidInput::NotJpeg => write!(f, "not JPEG"), | 71 | InvalidInput::NotJpeg => write!(f, "not JPEG"), |
crates/common/src/model.rsmodified+6 -4
| @@ -162,8 +162,12 @@ pub struct Unread { | |||
| 162 | } | 162 | } |
| 163 | 163 | ||
| 164 | pub fn mentions(body: &str, username: &str) -> bool { | 164 | pub fn mentions(body: &str, username: &str) -> bool { |
| 165 | - body.to_lowercase() | 165 | + let body = body.to_lowercase(); |
| 166 | - .contains(&format!("@{}", username.to_lowercase())) | 166 | + let needle = format!("@{}", username.to_lowercase()); |
| 167 | + body.match_indices(&needle).any(|(at, _)| { | ||
| 168 | + !body[at + needle.len()..] | ||
| 169 | + .starts_with(|next: char| next.is_ascii_alphanumeric() || matches!(next, '_' | '-')) | ||
| 170 | + }) | ||
| 167 | } | 171 | } |
| 168 | 172 | ||
| 169 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 173 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| @@ -468,7 +472,6 @@ pub struct ServerBan { | |||
| 468 | pub kind: ServerBanKind, | 472 | pub kind: ServerBanKind, |
| 469 | pub value: String, | 473 | pub value: String, |
| 470 | pub reason: Option<String>, | 474 | pub reason: Option<String>, |
| 471 | - pub created_by: Option<User>, | ||
| 472 | } | 475 | } |
| 473 | 476 | ||
| 474 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 477 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
| @@ -476,7 +479,6 @@ pub struct InviteCode { | |||
| 476 | pub code: String, | 479 | pub code: String, |
| 477 | pub uses_left: u32, | 480 | pub uses_left: u32, |
| 478 | pub expires_at: Option<u64>, | 481 | pub expires_at: Option<u64>, |
| 479 | - pub created_by: Option<User>, | ||
| 480 | } | 482 | } |
| 481 | 483 | ||
| 482 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | 484 | #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] |
crates/common/src/network.rsmodified+21 -20
| @@ -2,26 +2,17 @@ use bitcode::{DecodeOwned, Encode}; | |||
| 2 | use quinn::{RecvStream, SendStream}; | 2 | use quinn::{RecvStream, SendStream}; |
| 3 | 3 | ||
| 4 | use crate::{ | 4 | use crate::{ |
| 5 | - constant::{ | ||
| 6 | - MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_ATTACHMENTS_PER_MESSAGE, MAXIMUM_AVATAR_BYTES, | ||
| 7 | - MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT, | ||
| 8 | - }, | ||
| 9 | error::Error, | 5 | error::Error, |
| 10 | event::Event, | 6 | event::Event, |
| 11 | request::{Request, UploadHeader}, | 7 | request::{Request, UploadHeader}, |
| 12 | response::Response, | 8 | response::Response, |
| 13 | }; | 9 | }; |
| 14 | 10 | ||
| 15 | -const ATTACHMENT_MAX_ENCODED_LENGTH: usize = MAXIMUM_ATTACHMENT_NAME_LENGTH * 4 + 128; | ||
| 16 | pub const UPLOAD_HEADER_MAX_LENGTH: usize = 1024; | 11 | pub const UPLOAD_HEADER_MAX_LENGTH: usize = 1024; |
| 17 | pub const DOWNLOAD_REQUEST_MAX_READ_LENGTH: usize = 1024; | 12 | pub const DOWNLOAD_REQUEST_MAX_READ_LENGTH: usize = 1024; |
| 18 | - | 13 | +pub const REQUEST_MAX_READ_LENGTH: usize = 64 * 1024; |
| 19 | -const MESSAGE_MAX_ENCODED_LENGTH: usize = | 14 | +pub const EVENT_MAX_ENCODED_LENGTH: usize = 16 * 1024 * 1024; |
| 20 | - MAXIMUM_MESSAGE_LENGTH * 2 + MAXIMUM_ATTACHMENTS_PER_MESSAGE * ATTACHMENT_MAX_ENCODED_LENGTH; | 15 | +pub const RESPONSE_MAX_READ_LENGTH: usize = 16 * 1024 * 1024; |
| 21 | -pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_AVATAR_BYTES + MESSAGE_MAX_ENCODED_LENGTH; | ||
| 22 | -pub const EVENT_MAX_ENCODED_LENGTH: usize = | ||
| 23 | - MESSAGE_MAX_ENCODED_LENGTH * (MAXIMUM_FORWARD_MESSAGES + 2); | ||
| 24 | -pub const RESPONSE_MAX_READ_LENGTH: usize = EVENT_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT; | ||
| 25 | 16 | ||
| 26 | #[repr(u8)] | 17 | #[repr(u8)] |
| 27 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -46,13 +37,13 @@ impl StreamKind { | |||
| 46 | 37 | ||
| 47 | #[repr(u8)] | 38 | #[repr(u8)] |
| 48 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 49 | -pub enum DownloadStatus { | 40 | +enum DownloadStatus { |
| 50 | Ok = 0, | 41 | Ok = 0, |
| 51 | Error = 1, | 42 | Error = 1, |
| 52 | } | 43 | } |
| 53 | 44 | ||
| 54 | impl DownloadStatus { | 45 | impl DownloadStatus { |
| 55 | - pub fn parse(byte: u8) -> Option<Self> { | 46 | + fn parse(byte: u8) -> Option<Self> { |
| 56 | match byte { | 47 | match byte { |
| 57 | 0 => Some(DownloadStatus::Ok), | 48 | 0 => Some(DownloadStatus::Ok), |
| 58 | 1 => Some(DownloadStatus::Error), | 49 | 1 => Some(DownloadStatus::Error), |
| @@ -73,17 +64,27 @@ pub async fn receive_stream_kind(receive_stream: &mut RecvStream) -> Result<Stre | |||
| 73 | StreamKind::parse(byte[0]).ok_or_else(|| Error::Decode(format!("stream kind {}", byte[0]))) | 64 | StreamKind::parse(byte[0]).ok_or_else(|| Error::Decode(format!("stream kind {}", byte[0]))) |
| 74 | } | 65 | } |
| 75 | 66 | ||
| 76 | -pub async fn send_download_status( | 67 | +pub async fn send_download_reply( |
| 77 | - status: DownloadStatus, | 68 | + reply: Result<u64, Error>, |
| 78 | send_stream: &mut SendStream, | 69 | send_stream: &mut SendStream, |
| 79 | ) -> Result<(), Error> { | 70 | ) -> Result<(), Error> { |
| 80 | - send_stream.write_all(&[status as u8]).await?; | 71 | + match reply { |
| 72 | + Ok(length) => { | ||
| 73 | + send_stream.write_all(&[DownloadStatus::Ok as u8]).await?; | ||
| 74 | + send_stream.write_all(&length.to_le_bytes()).await?; | ||
| 75 | + } | ||
| 76 | + Err(error) => { | ||
| 77 | + send_stream | ||
| 78 | + .write_all(&[DownloadStatus::Error as u8]) | ||
| 79 | + .await?; | ||
| 80 | + send_encoded(&error, send_stream).await?; | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + | ||
| 81 | Ok(()) | 84 | Ok(()) |
| 82 | } | 85 | } |
| 83 | 86 | ||
| 84 | -pub async fn receive_download_status( | 87 | +async fn receive_download_status(receive_stream: &mut RecvStream) -> Result<DownloadStatus, Error> { |
| 85 | - receive_stream: &mut RecvStream, | ||
| 86 | -) -> Result<DownloadStatus, Error> { | ||
| 87 | let mut byte = [0u8; 1]; | 88 | let mut byte = [0u8; 1]; |
| 88 | receive_stream.read_exact(&mut byte).await?; | 89 | receive_stream.read_exact(&mut byte).await?; |
| 89 | 90 | ||
crates/common/src/share.rsmodified+0 -20
| @@ -176,26 +176,6 @@ pub fn options(source_height: u32, refresh: u32, max_height: u32) -> (Vec<Resolu | |||
| 176 | (resolutions, fps) | 176 | (resolutions, fps) |
| 177 | } | 177 | } |
| 178 | 178 | ||
| 179 | -pub fn ladder(top: Quality) -> Vec<Quality> { | ||
| 180 | - let rungs = [ | ||
| 181 | - top, | ||
| 182 | - Quality { | ||
| 183 | - resolution: Resolution::P720, | ||
| 184 | - fps: Fps::F30, | ||
| 185 | - }, | ||
| 186 | - Quality { | ||
| 187 | - resolution: Resolution::P360, | ||
| 188 | - fps: Fps::F15, | ||
| 189 | - }, | ||
| 190 | - ]; | ||
| 191 | - let mut ladder: Vec<Quality> = rungs | ||
| 192 | - .into_iter() | ||
| 193 | - .filter(|rung| rung.resolution <= top.resolution && rung.fps <= top.fps) | ||
| 194 | - .collect(); | ||
| 195 | - ladder.dedup(); | ||
| 196 | - ladder | ||
| 197 | -} | ||
| 198 | - | ||
| 199 | pub fn best_codec(encode: &[Codec], decode: &[Codec]) -> Option<Codec> { | 179 | pub fn best_codec(encode: &[Codec], decode: &[Codec]) -> Option<Codec> { |
| 200 | Codec::PREFERENCE | 180 | Codec::PREFERENCE |
| 201 | .into_iter() | 181 | .into_iter() |
crates/common/src/time.rsmodified+1 -1
| @@ -27,6 +27,6 @@ pub fn range_bounds( | |||
| 27 | ) -> (Option<String>, Option<String>) { | 27 | ) -> (Option<String>, Option<String>) { |
| 28 | ( | 28 | ( |
| 29 | after_ms.map(id_bound), | 29 | after_ms.map(id_bound), |
| 30 | - before_ms.map(|before| id_bound(before + 1)), | 30 | + before_ms.map(|before| id_bound(before.saturating_add(1))), |
| 31 | ) | 31 | ) |
| 32 | } | 32 | } |
crates/common/src/validate.rsmodified+22 -47
| @@ -35,51 +35,28 @@ fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidI | |||
| 35 | check_length(text.chars().count(), minimum, maximum) | 35 | check_length(text.chars().count(), minimum, maximum) |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | -fn check( | 38 | +fn check_name(name: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { |
| 39 | - input: &str, | 39 | + let allowed = name.bytes().all(|byte| byte.is_ascii_graphic() || byte == b' '); |
| 40 | - minimum: usize, | 40 | + if !allowed || name != name.trim() { |
| 41 | - maximum: usize, | 41 | + return Err(InvalidInput::ForbiddenCharacter); |
| 42 | - ascii_only: bool, | ||
| 43 | -) -> Result<(), InvalidInput> { | ||
| 44 | - if ascii_only && !input.is_ascii() { | ||
| 45 | - return Err(InvalidInput::NotASCII); | ||
| 46 | } | 42 | } |
| 47 | 43 | ||
| 48 | - check_length(input.len(), minimum, maximum) | 44 | + check_length(name.len(), minimum, maximum) |
| 49 | } | 45 | } |
| 50 | 46 | ||
| 51 | pub fn validate_username(username: &str) -> Result<(), Error> { | 47 | pub fn validate_username(username: &str) -> Result<(), Error> { |
| 52 | - check( | 48 | + check_name(username, MINIMUM_USERNAME_LENGTH, MAXIMUM_USERNAME_LENGTH) |
| 53 | - username, | 49 | + .map_err(invalid(Field::User)) |
| 54 | - MINIMUM_USERNAME_LENGTH, | ||
| 55 | - MAXIMUM_USERNAME_LENGTH, | ||
| 56 | - true, | ||
| 57 | - ) | ||
| 58 | - .map_err(invalid(Field::User)) | ||
| 59 | } | 50 | } |
| 60 | 51 | ||
| 61 | pub fn validate_password(password: &str) -> Result<(), Error> { | 52 | pub fn validate_password(password: &str) -> Result<(), Error> { |
| 62 | - check( | 53 | + check_length(password.len(), MINIMUM_PASSWORD_LENGTH, MAXIMUM_PASSWORD_LENGTH) |
| 63 | - password, | 54 | + .map_err(invalid(Field::Password)) |
| 64 | - MINIMUM_PASSWORD_LENGTH, | ||
| 65 | - MAXIMUM_PASSWORD_LENGTH, | ||
| 66 | - false, | ||
| 67 | - ) | ||
| 68 | - .map_err(invalid(Field::Password)) | ||
| 69 | } | 55 | } |
| 70 | 56 | ||
| 71 | pub fn validate_community_name(name: &str) -> Result<(), Error> { | 57 | pub fn validate_community_name(name: &str) -> Result<(), Error> { |
| 72 | - check( | 58 | + check_name(name, MINIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_COMMUNITY_NAME_LENGTH) |
| 73 | - name, | 59 | + .map_err(invalid(Field::Community)) |
| 74 | - MINIMUM_COMMUNITY_NAME_LENGTH, | ||
| 75 | - MAXIMUM_COMMUNITY_NAME_LENGTH, | ||
| 76 | - true, | ||
| 77 | - ) | ||
| 78 | - .map_err(invalid(Field::Community)) | ||
| 79 | -} | ||
| 80 | - | ||
| 81 | -pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> { | ||
| 82 | - check(body, MINIMUM_MESSAGE_LENGTH, maximum, false).map_err(invalid(Field::Message)) | ||
| 83 | } | 60 | } |
| 84 | 61 | ||
| 85 | pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> { | 62 | 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 | |||
| 88 | } else { | 65 | } else { |
| 89 | 0 | 66 | 0 |
| 90 | }; | 67 | }; |
| 91 | - check(body, minimum, maximum, false).map_err(invalid(Field::Message)) | 68 | + check_length(body.len(), minimum, maximum).map_err(invalid(Field::Message)) |
| 92 | } | 69 | } |
| 93 | 70 | ||
| 94 | pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { | 71 | pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { |
| @@ -189,12 +166,16 @@ fn check_quota(quota: u64, minimum: u64) -> Result<(), Error> { | |||
| 189 | Ok(()) | 166 | Ok(()) |
| 190 | } | 167 | } |
| 191 | 168 | ||
| 192 | -pub fn validate_announcement(text: &str) -> Result<(), Error> { | 169 | +fn check_line(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { |
| 193 | if text.contains(['\n', '\r']) { | 170 | if text.contains(['\n', '\r']) { |
| 194 | - return Err(invalid(Field::Announcement)(InvalidInput::MultiLine)); | 171 | + return Err(InvalidInput::MultiLine); |
| 195 | } | 172 | } |
| 196 | 173 | ||
| 197 | - check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(invalid(Field::Announcement)) | 174 | + check_text(text, minimum, maximum) |
| 175 | +} | ||
| 176 | + | ||
| 177 | +pub fn validate_announcement(text: &str) -> Result<(), Error> { | ||
| 178 | + check_line(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(invalid(Field::Announcement)) | ||
| 198 | } | 179 | } |
| 199 | 180 | ||
| 200 | pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> { | 181 | pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> { |
| @@ -220,10 +201,8 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> { | |||
| 220 | let Some(reason) = reason else { | 201 | let Some(reason) = reason else { |
| 221 | return Ok(()); | 202 | return Ok(()); |
| 222 | }; | 203 | }; |
| 223 | - if reason.contains(['\n', '\r']) { | 204 | + |
| 224 | - return Err(invalid(Field::Reason)(InvalidInput::MultiLine)); | 205 | + check_line(reason, 1, MAXIMUM_REASON_LENGTH).map_err(invalid(Field::Reason)) |
| 225 | - } | ||
| 226 | - check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(invalid(Field::Reason)) | ||
| 227 | } | 206 | } |
| 228 | 207 | ||
| 229 | pub fn validate_forward(count: usize) -> Result<(), Error> { | 208 | pub fn validate_forward(count: usize) -> Result<(), Error> { |
| @@ -231,11 +210,7 @@ pub fn validate_forward(count: usize) -> Result<(), Error> { | |||
| 231 | } | 210 | } |
| 232 | 211 | ||
| 233 | pub fn validate_status(status: &str) -> Result<(), Error> { | 212 | pub fn validate_status(status: &str) -> Result<(), Error> { |
| 234 | - if status.contains(['\n', '\r']) { | 213 | + check_line(status, 0, MAXIMUM_STATUS_LENGTH).map_err(invalid(Field::Status)) |
| 235 | - return Err(invalid(Field::Status)(InvalidInput::MultiLine)); | ||
| 236 | - } | ||
| 237 | - | ||
| 238 | - check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(invalid(Field::Status)) | ||
| 239 | } | 214 | } |
| 240 | 215 | ||
| 241 | pub fn validate_device(name: &str) -> Result<(), Error> { | 216 | pub fn validate_device(name: &str) -> Result<(), Error> { |
crates/pixel/src/lib.rsmodified+14 -10
| @@ -11,6 +11,10 @@ const BYTES_PER_PIXEL: u32 = 4; | |||
| 11 | const RANGE: YuvRange = YuvRange::Limited; | 11 | const RANGE: YuvRange = YuvRange::Limited; |
| 12 | const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt709; | 12 | const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt709; |
| 13 | 13 | ||
| 14 | +fn blank(width: u32, height: u32) -> Vec<u8> { | ||
| 15 | + vec![0; (width * height * BYTES_PER_PIXEL) as usize] | ||
| 16 | +} | ||
| 17 | + | ||
| 14 | pub struct Bgra<'a> { | 18 | pub struct Bgra<'a> { |
| 15 | pub data: &'a [u8], | 19 | pub data: &'a [u8], |
| 16 | pub width: u32, | 20 | pub width: u32, |
| @@ -49,7 +53,7 @@ pub fn yuv_to_bgra( | |||
| 49 | width, | 53 | width, |
| 50 | height, | 54 | height, |
| 51 | }; | 55 | }; |
| 52 | - let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; | 56 | + let mut out = blank(width, height); |
| 53 | yuv::yuv420_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; | 57 | yuv::yuv420_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; |
| 54 | if width <= max_width { | 58 | if width <= max_width { |
| 55 | return Some((width, height, out)); | 59 | return Some((width, height, out)); |
| @@ -82,7 +86,7 @@ pub fn yuyv_to_bgra(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> { | |||
| 82 | width, | 86 | width, |
| 83 | height, | 87 | height, |
| 84 | }; | 88 | }; |
| 85 | - let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; | 89 | + let mut out = blank(width, height); |
| 86 | yuv::yuyv422_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; | 90 | yuv::yuyv422_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; |
| 87 | Some(out) | 91 | Some(out) |
| 88 | } | 92 | } |
| @@ -103,7 +107,7 @@ pub fn nv12_to_bgra(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> { | |||
| 103 | width, | 107 | width, |
| 104 | height, | 108 | height, |
| 105 | }; | 109 | }; |
| 106 | - let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; | 110 | + let mut out = blank(width, height); |
| 107 | yuv::yuv_nv12_to_bgra( | 111 | yuv::yuv_nv12_to_bgra( |
| 108 | &image, | 112 | &image, |
| 109 | &mut out, | 113 | &mut out, |
| @@ -117,14 +121,14 @@ pub fn nv12_to_bgra(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> { | |||
| 117 | } | 121 | } |
| 118 | 122 | ||
| 119 | pub fn bgra_to_i420(source: &Bgra, width: u32, height: u32) -> Option<I420> { | 123 | pub fn bgra_to_i420(source: &Bgra, width: u32, height: u32) -> Option<I420> { |
| 120 | - let scaled = (source.width, source.height) != (width, height); | 124 | + let resized = if (source.width, source.height) != (width, height) { |
| 121 | - let resized = match scaled { | 125 | + Some(scale(source, width, height)?) |
| 122 | - true => scale(source, width, height)?, | 126 | + } else { |
| 123 | - false => Vec::new(), | 127 | + None |
| 124 | }; | 128 | }; |
| 125 | - let (data, stride) = match scaled { | 129 | + let (data, stride) = match &resized { |
| 126 | - true => (resized.as_slice(), width * BYTES_PER_PIXEL), | 130 | + Some(pixels) => (pixels.as_slice(), width * BYTES_PER_PIXEL), |
| 127 | - false => (source.data, source.stride), | 131 | + None => (source.data, source.stride), |
| 128 | }; | 132 | }; |
| 129 | let mut planes = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420); | 133 | let mut planes = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420); |
| 130 | yuv::bgra_to_yuv420( | 134 | yuv::bgra_to_yuv420( |
crates/server/src/attachment.rsmodified+37 -38
| @@ -15,8 +15,8 @@ use common::{ | |||
| 15 | Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, | 15 | Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User, |
| 16 | }, | 16 | }, |
| 17 | network::{ | 17 | network::{ |
| 18 | - DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, receive_upload_header, | 18 | + DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded, receive_upload_header, |
| 19 | - send_download_status, send_encoded, send_response, | 19 | + send_download_reply, send_response, |
| 20 | }, | 20 | }, |
| 21 | permission, | 21 | permission, |
| 22 | request::{DownloadRequest, UploadHeader}, | 22 | request::{DownloadRequest, UploadHeader}, |
| @@ -37,7 +37,6 @@ use crate::{ | |||
| 37 | community, | 37 | community, |
| 38 | database::{self, DB, new_id}, | 38 | database::{self, DB, new_id}, |
| 39 | error::Error, | 39 | error::Error, |
| 40 | - message, | ||
| 41 | request::{actor_rank, ensure}, | 40 | request::{actor_rank, ensure}, |
| 42 | server_settings, user, | 41 | server_settings, user, |
| 43 | }; | 42 | }; |
| @@ -111,7 +110,7 @@ pub async fn bind( | |||
| 111 | (message_id, attachment_id.as_str(), user_id, community_id), | 110 | (message_id, attachment_id.as_str(), user_id, community_id), |
| 112 | ) | 111 | ) |
| 113 | .await?; | 112 | .await?; |
| 114 | - message::expect_one(bound)?; | 113 | + database::expect_one(bound)?; |
| 115 | } | 114 | } |
| 116 | 115 | ||
| 117 | Ok(()) | 116 | Ok(()) |
| @@ -185,10 +184,10 @@ pub async fn copy( | |||
| 185 | } | 184 | } |
| 186 | 185 | ||
| 187 | pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { | 186 | pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { |
| 188 | - message::ids_where( | 187 | + database::ids( |
| 189 | - "SELECT id FROM attachment WHERE message_id = ?1", | ||
| 190 | - message_id, | ||
| 191 | conn, | 188 | conn, |
| 189 | + "SELECT id FROM attachment WHERE message_id = ?1", | ||
| 190 | + (message_id,), | ||
| 192 | ) | 191 | ) |
| 193 | .await | 192 | .await |
| 194 | } | 193 | } |
| @@ -284,12 +283,7 @@ async fn over_quota( | |||
| 284 | if limit == 0 { | 283 | if limit == 0 { |
| 285 | return Ok(false); | 284 | return Ok(false); |
| 286 | } | 285 | } |
| 287 | - let mut rows = conn.query(sql, (key,)).await?; | 286 | + let used = database::scalar_i64(conn, sql, (key,)).await?; |
| 288 | - let row = rows | ||
| 289 | - .next() | ||
| 290 | - .await? | ||
| 291 | - .ok_or(turso::Error::QueryReturnedNoRows)?; | ||
| 292 | - let used: i64 = row.get(0)?; | ||
| 293 | 287 | ||
| 294 | Ok(used as u64 + size > limit) | 288 | Ok(used as u64 + size > limit) |
| 295 | } | 289 | } |
| @@ -328,10 +322,10 @@ async fn ensure_quota( | |||
| 328 | } | 322 | } |
| 329 | 323 | ||
| 330 | pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { | 324 | pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { |
| 331 | - message::ids_where( | 325 | + database::ids( |
| 332 | - "SELECT id FROM attachment WHERE uploader_id = ?1", | ||
| 333 | - user_id, | ||
| 334 | conn, | 326 | conn, |
| 327 | + "SELECT id FROM attachment WHERE uploader_id = ?1", | ||
| 328 | + (user_id,), | ||
| 335 | ) | 329 | ) |
| 336 | .await | 330 | .await |
| 337 | } | 331 | } |
| @@ -604,17 +598,23 @@ pub async fn download( | |||
| 604 | let request: DownloadRequest = | 598 | let request: DownloadRequest = |
| 605 | receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; | 599 | receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; |
| 606 | 600 | ||
| 607 | - match locate(user, &request, db, directory).await { | 601 | + let located = locate(user, &request, db, directory) |
| 608 | - Ok((path, length)) => { | 602 | + .await |
| 609 | - send_download_status(DownloadStatus::Ok, &mut send_stream).await?; | 603 | + .map_err(CommonError::from); |
| 610 | - send_stream.write_all(&length.to_le_bytes()).await?; | 604 | + send_file(located, &mut send_stream).await |
| 611 | - stream_file(&path, &mut send_stream).await?; | 605 | +} |
| 612 | - } | 606 | + |
| 613 | - Err(error) => { | 607 | +pub async fn send_file( |
| 614 | - let error: CommonError = error.into(); | 608 | + located: Result<(PathBuf, u64), CommonError>, |
| 615 | - send_download_status(DownloadStatus::Error, &mut send_stream).await?; | 609 | + send_stream: &mut SendStream, |
| 616 | - send_encoded(&error, &mut send_stream).await?; | 610 | +) -> Result<(), Error> { |
| 617 | - } | 611 | + let reply = located |
| 612 | + .as_ref() | ||
| 613 | + .map(|(_, length)| *length) | ||
| 614 | + .map_err(Clone::clone); | ||
| 615 | + send_download_reply(reply, send_stream).await?; | ||
| 616 | + if let Ok((path, _)) = located { | ||
| 617 | + stream_file(&path, send_stream).await?; | ||
| 618 | } | 618 | } |
| 619 | send_stream.finish()?; | 619 | send_stream.finish()?; |
| 620 | 620 | ||
| @@ -651,16 +651,19 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { | |||
| 651 | drop(rows); | 651 | drop(rows); |
| 652 | 652 | ||
| 653 | for entry in std::fs::read_dir(directory)? { | 653 | for entry in std::fs::read_dir(directory)? { |
| 654 | - let entry = entry?; | 654 | + let Ok(entry) = entry else { continue }; |
| 655 | let name = entry.file_name().to_string_lossy().into_owned(); | 655 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 656 | let id = name | 656 | let id = name |
| 657 | .strip_suffix(THUMB_SUFFIX) | 657 | .strip_suffix(THUMB_SUFFIX) |
| 658 | .or_else(|| name.strip_suffix(PART_SUFFIX)) | 658 | .or_else(|| name.strip_suffix(PART_SUFFIX)) |
| 659 | .unwrap_or(&name); | 659 | .unwrap_or(&name); |
| 660 | - let stale = entry.metadata()?.modified()? < stale_at; | 660 | + let Ok(modified) = entry.metadata().and_then(|metadata| metadata.modified()) else { |
| 661 | + continue; | ||
| 662 | + }; | ||
| 663 | + let stale = modified < stale_at && id < stale_id.as_str(); | ||
| 661 | 664 | ||
| 662 | if stale && !ids.contains(id) { | 665 | if stale && !ids.contains(id) { |
| 663 | - std::fs::remove_file(entry.path())?; | 666 | + let _ = std::fs::remove_file(entry.path()); |
| 664 | } | 667 | } |
| 665 | } | 668 | } |
| 666 | 669 | ||
| @@ -669,7 +672,7 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> { | |||
| 669 | 672 | ||
| 670 | #[cfg(test)] | 673 | #[cfg(test)] |
| 671 | mod tests { | 674 | mod tests { |
| 672 | - use std::{io::Cursor, path::Path, sync::Mutex}; | 675 | + use std::{io::Cursor, sync::Mutex}; |
| 673 | 676 | ||
| 674 | use common::{ | 677 | use common::{ |
| 675 | model::{AttachmentKind, Rank}, | 678 | model::{AttachmentKind, Rank}, |
| @@ -700,17 +703,13 @@ mod tests { | |||
| 700 | .write_to(&mut png, ImageFormat::Png) | 703 | .write_to(&mut png, ImageFormat::Png) |
| 701 | .unwrap(); | 704 | .unwrap(); |
| 702 | let png = png.into_inner(); | 705 | let png = png.into_inner(); |
| 703 | - let directory = Path::new(concat!( | 706 | + let directory = test::directory(); |
| 704 | - env!("CARGO_MANIFEST_DIR"), | ||
| 705 | - "/../../target/attachment-tests" | ||
| 706 | - )); | ||
| 707 | - std::fs::create_dir_all(directory).unwrap(); | ||
| 708 | let header = UploadHeader { | 707 | let header = UploadHeader { |
| 709 | community_id: community.id.clone(), | 708 | community_id: community.id.clone(), |
| 710 | name: "pixel.png".to_string(), | 709 | name: "pixel.png".to_string(), |
| 711 | size: png.len() as u64, | 710 | size: png.len() as u64, |
| 712 | }; | 711 | }; |
| 713 | - let attachment = store(&user, &header, &mut png.as_slice(), &db, directory) | 712 | + let attachment = store(&user, &header, &mut png.as_slice(), &db, &directory) |
| 714 | .await | 713 | .await |
| 715 | .unwrap(); | 714 | .unwrap(); |
| 716 | 715 | ||
| @@ -742,6 +741,6 @@ mod tests { | |||
| 742 | assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); | 741 | assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height)); |
| 743 | 742 | ||
| 744 | std::fs::remove_file(directory.join(&attachment.id)).unwrap(); | 743 | std::fs::remove_file(directory.join(&attachment.id)).unwrap(); |
| 745 | - std::fs::remove_file(thumb_path(directory, &attachment.id)).unwrap(); | 744 | + std::fs::remove_file(thumb_path(&directory, &attachment.id)).unwrap(); |
| 746 | } | 745 | } |
| 747 | } | 746 | } |
crates/server/src/authentication.rsmodified+2 -4
| @@ -12,7 +12,7 @@ use crate::{database::new_id, error::Error, invite, server_ban, server_settings, | |||
| 12 | const SALT_LENGTH: usize = 16; | 12 | const SALT_LENGTH: usize = 16; |
| 13 | const TOKEN_LENGTH: usize = 32; | 13 | const TOKEN_LENGTH: usize = 32; |
| 14 | 14 | ||
| 15 | -fn random_bytes<const N: usize>() -> Result<[u8; N], Error> { | 15 | +pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N], Error> { |
| 16 | let mut bytes = [0u8; N]; | 16 | let mut bytes = [0u8; N]; |
| 17 | getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; | 17 | getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; |
| 18 | 18 | ||
| @@ -137,9 +137,6 @@ pub async fn register( | |||
| 137 | invite_code: Option<&str>, | 137 | invite_code: Option<&str>, |
| 138 | conn: &mut Connection, | 138 | conn: &mut Connection, |
| 139 | ) -> Result<(User, String), Error> { | 139 | ) -> Result<(User, String), Error> { |
| 140 | - validate_username(username)?; | ||
| 141 | - validate_password(password)?; | ||
| 142 | - | ||
| 143 | let tx = conn.transaction().await?; | 140 | let tx = conn.transaction().await?; |
| 144 | if server_ban::username_banned(username, &tx).await? { | 141 | if server_ban::username_banned(username, &tx).await? { |
| 145 | return Err(CommonError::Banned.into()); | 142 | return Err(CommonError::Banned.into()); |
| @@ -148,6 +145,7 @@ pub async fn register( | |||
| 148 | invite::consume(invite_code.ok_or(CommonError::RegistrationClosed)?, &tx).await?; | 145 | invite::consume(invite_code.ok_or(CommonError::RegistrationClosed)?, &tx).await?; |
| 149 | } | 146 | } |
| 150 | let user = create_account(username, password, &tx).await?; | 147 | let user = create_account(username, password, &tx).await?; |
| 148 | + admit(&user, &tx).await?; | ||
| 151 | let token = open_session(&user.id, &tx).await?; | 149 | let token = open_session(&user.id, &tx).await?; |
| 152 | tx.commit().await?; | 150 | tx.commit().await?; |
| 153 | 151 | ||
crates/server/src/backup.rsmodified+5 -19
| @@ -3,10 +3,7 @@ use std::path::{Path, PathBuf}; | |||
| 3 | use common::{ | 3 | use common::{ |
| 4 | error::Error as CommonError, | 4 | error::Error as CommonError, |
| 5 | model::{AdminAction, BackupInfo, User}, | 5 | model::{AdminAction, BackupInfo, User}, |
| 6 | - network::{ | 6 | + network::{DOWNLOAD_REQUEST_MAX_READ_LENGTH, receive_decoded}, |
| 7 | - DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, send_download_status, | ||
| 8 | - send_encoded, | ||
| 9 | - }, | ||
| 10 | permission, | 7 | permission, |
| 11 | request::Request, | 8 | request::Request, |
| 12 | time, | 9 | time, |
| @@ -123,19 +120,8 @@ pub async fn download( | |||
| 123 | let request: Request = | 120 | let request: Request = |
| 124 | receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; | 121 | receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; |
| 125 | 122 | ||
| 126 | - match locate(user, request, db, directory).await { | 123 | + let located = locate(user, request, db, directory) |
| 127 | - Ok((path, length)) => { | 124 | + .await |
| 128 | - send_download_status(DownloadStatus::Ok, &mut send_stream).await?; | 125 | + .map_err(CommonError::from); |
| 129 | - send_stream.write_all(&length.to_le_bytes()).await?; | 126 | + attachment::send_file(located, &mut send_stream).await |
| 130 | - attachment::stream_file(&path, &mut send_stream).await?; | ||
| 131 | - } | ||
| 132 | - Err(error) => { | ||
| 133 | - let error: CommonError = error.into(); | ||
| 134 | - send_download_status(DownloadStatus::Error, &mut send_stream).await?; | ||
| 135 | - send_encoded(&error, &mut send_stream).await?; | ||
| 136 | - } | ||
| 137 | - } | ||
| 138 | - send_stream.finish()?; | ||
| 139 | - | ||
| 140 | - Ok(()) | ||
| 141 | } | 127 | } |
crates/server/src/certificate.rsmodified+9 -1
| @@ -43,7 +43,15 @@ fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { | |||
| 43 | .map_err(certificate_error)?; | 43 | .map_err(certificate_error)?; |
| 44 | 44 | ||
| 45 | fs::write(certificate_path, certified.cert.pem())?; | 45 | fs::write(certificate_path, certified.cert.pem())?; |
| 46 | - fs::write(key_path, certified.signing_key.serialize_pem())?; | 46 | + let _ = fs::remove_file(key_path); |
| 47 | + let mut options = fs::OpenOptions::new(); | ||
| 48 | + options.write(true).create(true).truncate(true); | ||
| 49 | + #[cfg(unix)] | ||
| 50 | + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); | ||
| 51 | + std::io::Write::write_all( | ||
| 52 | + &mut options.open(key_path)?, | ||
| 53 | + certified.signing_key.serialize_pem().as_bytes(), | ||
| 54 | + )?; | ||
| 47 | 55 | ||
| 48 | Ok(()) | 56 | Ok(()) |
| 49 | } | 57 | } |
crates/server/src/community.rsmodified+14 -25
| @@ -107,22 +107,11 @@ pub async fn create(name: &str, conn: &Connection) -> Result<Community, Error> { | |||
| 107 | }) | 107 | }) |
| 108 | } | 108 | } |
| 109 | 109 | ||
| 110 | -pub async fn create_direct(conn: &Connection) -> Result<String, Error> { | 110 | +pub async fn create_fixed(kind: Kind, conn: &Connection) -> Result<String, Error> { |
| 111 | let id = new_id(); | 111 | let id = new_id(); |
| 112 | conn.execute( | 112 | conn.execute( |
| 113 | "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", | 113 | "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", |
| 114 | - (id.as_str(), Kind::Direct.as_str()), | 114 | + (id.as_str(), kind.as_str()), |
| 115 | - ) | ||
| 116 | - .await?; | ||
| 117 | - | ||
| 118 | - Ok(id) | ||
| 119 | -} | ||
| 120 | - | ||
| 121 | -pub async fn create_notes(conn: &Connection) -> Result<String, Error> { | ||
| 122 | - let id = new_id(); | ||
| 123 | - conn.execute( | ||
| 124 | - "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", | ||
| 125 | - (id.as_str(), Kind::Notes.as_str()), | ||
| 126 | ) | 115 | ) |
| 127 | .await?; | 116 | .await?; |
| 128 | 117 | ||
| @@ -306,17 +295,17 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool | |||
| 306 | } | 295 | } |
| 307 | 296 | ||
| 308 | pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> { | 297 | pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> { |
| 309 | - let mut rows = conn | 298 | + let prefix = match kind(community_id, conn).await? { |
| 310 | - .query( | 299 | + Kind::Group => { |
| 311 | - "SELECT kind = ?2, name FROM community WHERE id = ?1", | 300 | + let mut rows = conn |
| 312 | - (community_id, Kind::Direct.as_str()), | 301 | + .query("SELECT name FROM community WHERE id = ?1", (community_id,)) |
| 313 | - ) | 302 | + .await?; |
| 314 | - .await?; | 303 | + let row = rows.next().await?.ok_or(CommonError::NotFound)?; |
| 315 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | 304 | + return Ok(row.get(0)?); |
| 316 | - let direct: i64 = row.get(0)?; | 305 | + } |
| 317 | - if direct == 0 { | 306 | + Kind::Direct => "DM", |
| 318 | - return Ok(row.get(1)?); | 307 | + Kind::Notes => "Notes", |
| 319 | - } | 308 | + }; |
| 320 | 309 | ||
| 321 | let mut rows = conn | 310 | let mut rows = conn |
| 322 | .query( | 311 | .query( |
| @@ -329,7 +318,7 @@ pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Erro | |||
| 329 | usernames.push(row.get::<String>(0)?); | 318 | usernames.push(row.get::<String>(0)?); |
| 330 | } | 319 | } |
| 331 | 320 | ||
| 332 | - Ok(format!("DM · {}", usernames.join(" & "))) | 321 | + Ok(format!("{prefix} · {}", usernames.join(" & "))) |
| 333 | } | 322 | } |
| 334 | 323 | ||
| 335 | #[cfg(test)] | 324 | #[cfg(test)] |
crates/server/src/database.rsmodified+33 -8
| @@ -1,5 +1,6 @@ | |||
| 1 | use std::time::Duration; | 1 | use std::time::Duration; |
| 2 | 2 | ||
| 3 | +use common::error::Error as CommonError; | ||
| 3 | use turso::Connection; | 4 | use turso::Connection; |
| 4 | 5 | ||
| 5 | use crate::error::Error; | 6 | use crate::error::Error; |
| @@ -320,6 +321,37 @@ pub async fn scalar_i64( | |||
| 320 | Ok(row.get(0)?) | 321 | Ok(row.get(0)?) |
| 321 | } | 322 | } |
| 322 | 323 | ||
| 324 | +pub async fn exists( | ||
| 325 | + conn: &Connection, | ||
| 326 | + sql: &str, | ||
| 327 | + params: impl turso::IntoParams, | ||
| 328 | +) -> Result<bool, Error> { | ||
| 329 | + Ok(scalar_i64(conn, sql, params).await? != 0) | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +pub async fn ids( | ||
| 333 | + conn: &Connection, | ||
| 334 | + sql: &str, | ||
| 335 | + params: impl turso::IntoParams, | ||
| 336 | +) -> Result<Vec<String>, Error> { | ||
| 337 | + let mut rows = conn.query(sql, params).await?; | ||
| 338 | + | ||
| 339 | + let mut ids = Vec::new(); | ||
| 340 | + while let Some(row) = rows.next().await? { | ||
| 341 | + ids.push(row.get(0)?); | ||
| 342 | + } | ||
| 343 | + | ||
| 344 | + Ok(ids) | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +pub fn expect_one(affected: u64) -> Result<(), Error> { | ||
| 348 | + if affected != 1 { | ||
| 349 | + return Err(CommonError::NotFound.into()); | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + Ok(()) | ||
| 353 | +} | ||
| 354 | + | ||
| 323 | async fn migrate(db: &DB) -> Result<(), Error> { | 355 | async fn migrate(db: &DB) -> Result<(), Error> { |
| 324 | let mut conn = connect(db).await?; | 356 | let mut conn = connect(db).await?; |
| 325 | let applied = user_version(&conn).await?; | 357 | let applied = user_version(&conn).await?; |
| @@ -335,14 +367,7 @@ async fn migrate(db: &DB) -> Result<(), Error> { | |||
| 335 | } | 367 | } |
| 336 | 368 | ||
| 337 | async fn user_version(conn: &Connection) -> Result<usize, Error> { | 369 | async fn user_version(conn: &Connection) -> Result<usize, Error> { |
| 338 | - let mut rows = conn.query("PRAGMA user_version", ()).await?; | 370 | + Ok(scalar_i64(conn, "PRAGMA user_version", ()).await? as usize) |
| 339 | - let row = rows | ||
| 340 | - .next() | ||
| 341 | - .await? | ||
| 342 | - .ok_or(turso::Error::QueryReturnedNoRows)?; | ||
| 343 | - let version: i64 = row.get(0)?; | ||
| 344 | - | ||
| 345 | - Ok(version as usize) | ||
| 346 | } | 371 | } |
| 347 | 372 | ||
| 348 | pub fn new_id() -> String { | 373 | pub fn new_id() -> String { |
crates/server/src/direct.rsmodified+1 -1
| @@ -32,7 +32,7 @@ pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result<Openin | |||
| 32 | return Ok(Opening::Existing(community)); | 32 | return Ok(Opening::Existing(community)); |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | - let community_id = community::create_direct(&tx).await?; | 35 | + let community_id = community::create_fixed(community::Kind::Direct, &tx).await?; |
| 36 | user_community::join(me, &community_id, Rank::Member, &tx).await?; | 36 | user_community::join(me, &community_id, Rank::Member, &tx).await?; |
| 37 | user_community::join(other, &community_id, Rank::Member, &tx).await?; | 37 | user_community::join(other, &community_id, Rank::Member, &tx).await?; |
| 38 | tx.execute( | 38 | tx.execute( |
crates/server/src/error.rsmodified+0 -2
| @@ -28,9 +28,7 @@ error_from! { Error { | |||
| 28 | std::net::AddrParseError => Error::Common as common::error::Error, | 28 | std::net::AddrParseError => Error::Common as common::error::Error, |
| 29 | std::io::Error => Error::Common as common::error::Error, | 29 | std::io::Error => Error::Common as common::error::Error, |
| 30 | quinn::ConnectionError => Error::Common as common::error::Error, | 30 | quinn::ConnectionError => Error::Common as common::error::Error, |
| 31 | - quinn::ConnectError => Error::Common as common::error::Error, | ||
| 32 | quinn::ReadError => Error::Common as common::error::Error, | 31 | quinn::ReadError => Error::Common as common::error::Error, |
| 33 | - quinn::ReadToEndError => Error::Common as common::error::Error, | ||
| 34 | quinn::ReadExactError => Error::Common as common::error::Error, | 32 | quinn::ReadExactError => Error::Common as common::error::Error, |
| 35 | quinn::WriteError => Error::Common as common::error::Error, | 33 | quinn::WriteError => Error::Common as common::error::Error, |
| 36 | quinn::ClosedStream => Error::Common as common::error::Error, | 34 | quinn::ClosedStream => Error::Common as common::error::Error, |
crates/server/src/friend.rsmodified+1 -3
| @@ -23,9 +23,7 @@ async fn pair_exists( | |||
| 23 | second: &str, | 23 | second: &str, |
| 24 | conn: &Connection, | 24 | conn: &Connection, |
| 25 | ) -> Result<bool, Error> { | 25 | ) -> Result<bool, Error> { |
| 26 | - let count = database::scalar_i64(conn, sql, (first, second)).await?; | 26 | + database::exists(conn, sql, (first, second)).await |
| 27 | - | ||
| 28 | - Ok(count > 0) | ||
| 29 | } | 27 | } |
| 30 | 28 | ||
| 31 | async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, Error> { | 29 | async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, Error> { |
crates/server/src/invitation.rsmodified+3 -5
| @@ -32,14 +32,12 @@ pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Err | |||
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result<bool, Error> { | 34 | pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result<bool, Error> { |
| 35 | - let count = database::scalar_i64( | 35 | + database::exists( |
| 36 | conn, | 36 | conn, |
| 37 | - "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2", | 37 | + "SELECT EXISTS (SELECT 1 FROM invitation WHERE community_id = ?1 AND user_id = ?2)", |
| 38 | (community_id, user_id), | 38 | (community_id, user_id), |
| 39 | ) | 39 | ) |
| 40 | - .await?; | 40 | + .await |
| 41 | - | ||
| 42 | - Ok(count > 0) | ||
| 43 | } | 41 | } |
| 44 | 42 | ||
| 45 | pub async fn insert( | 43 | pub async fn insert( |
crates/server/src/invite.rsmodified+3 -9
| @@ -5,14 +5,13 @@ use common::{ | |||
| 5 | }; | 5 | }; |
| 6 | use turso::Connection; | 6 | use turso::Connection; |
| 7 | 7 | ||
| 8 | -use crate::{error::Error, user}; | 8 | +use crate::{authentication, error::Error}; |
| 9 | 9 | ||
| 10 | const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | 10 | const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| 11 | const CODE_LENGTH: usize = 8; | 11 | const CODE_LENGTH: usize = 8; |
| 12 | 12 | ||
| 13 | fn generate() -> Result<String, Error> { | 13 | fn generate() -> Result<String, Error> { |
| 14 | - let mut bytes = [0u8; CODE_LENGTH]; | 14 | + let bytes = authentication::random_bytes::<CODE_LENGTH>()?; |
| 15 | - getrandom::fill(&mut bytes).map_err(|error| Error::Hash(format!("random: {error}")))?; | ||
| 16 | 15 | ||
| 17 | Ok(bytes | 16 | Ok(bytes |
| 18 | .iter() | 17 | .iter() |
| @@ -43,16 +42,12 @@ pub async fn create( | |||
| 43 | code, | 42 | code, |
| 44 | uses_left: uses, | 43 | uses_left: uses, |
| 45 | expires_at, | 44 | expires_at, |
| 46 | - created_by: Some(created_by.clone()), | ||
| 47 | }) | 45 | }) |
| 48 | } | 46 | } |
| 49 | 47 | ||
| 50 | pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> { | 48 | pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> { |
| 51 | let mut rows = conn | 49 | let mut rows = conn |
| 52 | - .query( | 50 | + .query("SELECT code, uses_left, expires_at FROM invite_code", ()) |
| 53 | - &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")), | ||
| 54 | - (), | ||
| 55 | - ) | ||
| 56 | .await?; | 51 | .await?; |
| 57 | 52 | ||
| 58 | let mut codes = Vec::new(); | 53 | let mut codes = Vec::new(); |
| @@ -63,7 +58,6 @@ pub async fn list(conn: &Connection) -> Result<Vec<InviteCode>, Error> { | |||
| 63 | code: row.get(0)?, | 58 | code: row.get(0)?, |
| 64 | uses_left: uses_left as u32, | 59 | uses_left: uses_left as u32, |
| 65 | expires_at: expires_at.map(|millis| millis as u64), | 60 | expires_at: expires_at.map(|millis| millis as u64), |
| 66 | - created_by: user::from_row_at(&row, 3)?, | ||
| 67 | }); | 61 | }); |
| 68 | } | 62 | } |
| 69 | 63 | ||
crates/server/src/lib.rsmodified+7 -1
| @@ -41,6 +41,12 @@ const SERVER_CONFIG_FILE_PATH: &str = concat!( | |||
| 41 | "/../../configs/server_config.toml" | 41 | "/../../configs/server_config.toml" |
| 42 | ); | 42 | ); |
| 43 | 43 | ||
| 44 | +fn config_path() -> PathBuf { | ||
| 45 | + std::env::var_os("YUMUSH_CONFIG_DIR") | ||
| 46 | + .map(|dir| PathBuf::from(dir).join("server_config.toml")) | ||
| 47 | + .unwrap_or_else(|| PathBuf::from(SERVER_CONFIG_FILE_PATH)) | ||
| 48 | +} | ||
| 49 | + | ||
| 44 | pub struct ServerConfig { | 50 | pub struct ServerConfig { |
| 45 | pub database_path: String, | 51 | pub database_path: String, |
| 46 | pub server_address: String, | 52 | pub server_address: String, |
| @@ -49,7 +55,7 @@ pub struct ServerConfig { | |||
| 49 | } | 55 | } |
| 50 | 56 | ||
| 51 | fn load_config() -> Result<ServerConfig, Error> { | 57 | fn load_config() -> Result<ServerConfig, Error> { |
| 52 | - let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?; | 58 | + let content = std::fs::read_to_string(config_path())?; |
| 53 | let config = Config::parse(&content)?; | 59 | let config = Config::parse(&content)?; |
| 54 | 60 | ||
| 55 | Ok(ServerConfig { | 61 | Ok(ServerConfig { |
crates/server/src/message.rsmodified+15 -30
| @@ -11,7 +11,7 @@ use common::{ | |||
| 11 | }; | 11 | }; |
| 12 | use turso::{Connection, Row}; | 12 | use turso::{Connection, Row}; |
| 13 | 13 | ||
| 14 | -use crate::{attachment, community, database::new_id, error::Error, user}; | 14 | +use crate::{attachment, community, database, database::new_id, error::Error, user}; |
| 15 | 15 | ||
| 16 | const SEARCH_LIMIT: usize = 200; | 16 | const SEARCH_LIMIT: usize = 200; |
| 17 | 17 | ||
| @@ -256,25 +256,6 @@ async fn insert( | |||
| 256 | Ok(message_id) | 256 | Ok(message_id) |
| 257 | } | 257 | } |
| 258 | 258 | ||
| 259 | -pub fn expect_one(affected: u64) -> Result<(), Error> { | ||
| 260 | - if affected != 1 { | ||
| 261 | - return Err(CommonError::NotFound.into()); | ||
| 262 | - } | ||
| 263 | - | ||
| 264 | - Ok(()) | ||
| 265 | -} | ||
| 266 | - | ||
| 267 | -pub async fn ids_where(sql: &str, value: &str, conn: &Connection) -> Result<Vec<String>, Error> { | ||
| 268 | - let mut rows = conn.query(sql, (value,)).await?; | ||
| 269 | - | ||
| 270 | - let mut ids = Vec::new(); | ||
| 271 | - while let Some(row) = rows.next().await? { | ||
| 272 | - ids.push(row.get(0)?); | ||
| 273 | - } | ||
| 274 | - | ||
| 275 | - Ok(ids) | ||
| 276 | -} | ||
| 277 | - | ||
| 278 | pub async fn ensure_in_community( | 259 | pub async fn ensure_in_community( |
| 279 | message_id: &str, | 260 | message_id: &str, |
| 280 | community_id: &str, | 261 | community_id: &str, |
| @@ -425,7 +406,7 @@ pub async fn close_poll(message_id: &str, conn: &Connection) -> Result<Message, | |||
| 425 | (message_id,), | 406 | (message_id,), |
| 426 | ) | 407 | ) |
| 427 | .await?; | 408 | .await?; |
| 428 | - expect_one(updated)?; | 409 | + database::expect_one(updated)?; |
| 429 | 410 | ||
| 430 | read(message_id, conn).await | 411 | read(message_id, conn).await |
| 431 | } | 412 | } |
| @@ -487,7 +468,7 @@ pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<M | |||
| 487 | (message_id, body), | 468 | (message_id, body), |
| 488 | ) | 469 | ) |
| 489 | .await?; | 470 | .await?; |
| 490 | - expect_one(updated)?; | 471 | + database::expect_one(updated)?; |
| 491 | 472 | ||
| 492 | read(message_id, conn).await | 473 | read(message_id, conn).await |
| 493 | } | 474 | } |
| @@ -501,7 +482,12 @@ pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Erro | |||
| 501 | } | 482 | } |
| 502 | 483 | ||
| 503 | pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { | 484 | pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { |
| 504 | - ids_where("SELECT id FROM message WHERE user_id = ?1", user_id, conn).await | 485 | + database::ids( |
| 486 | + conn, | ||
| 487 | + "SELECT id FROM message WHERE user_id = ?1", | ||
| 488 | + (user_id,), | ||
| 489 | + ) | ||
| 490 | + .await | ||
| 505 | } | 491 | } |
| 506 | 492 | ||
| 507 | pub async fn search( | 493 | pub async fn search( |
| @@ -562,15 +548,14 @@ async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String> | |||
| 562 | 548 | ||
| 563 | let mut rows = conn | 549 | let mut rows = conn |
| 564 | .query( | 550 | .query( |
| 565 | - "SELECT name, kind FROM community WHERE id = ?1", | 551 | + "SELECT name FROM community WHERE id = ?1 AND kind = ?2", |
| 566 | - (community_id.as_str(),), | 552 | + (community_id.as_str(), community::Kind::Group.as_str()), |
| 567 | ) | 553 | ) |
| 568 | .await?; | 554 | .await?; |
| 569 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | 555 | + Ok(match rows.next().await? { |
| 570 | - let name: String = row.get(0)?; | 556 | + Some(row) => Some(row.get(0)?), |
| 571 | - let kind: String = row.get(1)?; | 557 | + None => None, |
| 572 | - | 558 | + }) |
| 573 | - Ok((kind != "direct").then_some(name)) | ||
| 574 | } | 559 | } |
| 575 | 560 | ||
| 576 | async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, Error> { | 561 | async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, Error> { |
crates/server/src/network.rsmodified+52 -59
| @@ -95,7 +95,11 @@ pub struct Services { | |||
| 95 | 95 | ||
| 96 | impl Presence { | 96 | impl Presence { |
| 97 | pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) { | 97 | pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) { |
| 98 | - self.0.lock().unwrap().insert( | 98 | + let mut signed = self.0.lock().unwrap(); |
| 99 | + if connection.close_reason().is_some() { | ||
| 100 | + return; | ||
| 101 | + } | ||
| 102 | + signed.insert( | ||
| 99 | connection.stable_id(), | 103 | connection.stable_id(), |
| 100 | Signed { | 104 | Signed { |
| 101 | user_id: user_id.to_string(), | 105 | user_id: user_id.to_string(), |
| @@ -105,6 +109,14 @@ impl Presence { | |||
| 105 | ); | 109 | ); |
| 106 | } | 110 | } |
| 107 | 111 | ||
| 112 | + pub fn is_online(&self, user_id: &str) -> bool { | ||
| 113 | + self.0 | ||
| 114 | + .lock() | ||
| 115 | + .unwrap() | ||
| 116 | + .values() | ||
| 117 | + .any(|signed| signed.user_id == user_id) | ||
| 118 | + } | ||
| 119 | + | ||
| 108 | pub fn sign_out(&self, connection_id: usize) { | 120 | pub fn sign_out(&self, connection_id: usize) { |
| 109 | self.0.lock().unwrap().remove(&connection_id); | 121 | self.0.lock().unwrap().remove(&connection_id); |
| 110 | } | 122 | } |
| @@ -166,12 +178,9 @@ enum Event { | |||
| 166 | connection: Connection, | 178 | connection: Connection, |
| 167 | send_stream: SendStream, | 179 | send_stream: SendStream, |
| 168 | }, | 180 | }, |
| 169 | - SignedIn { | 181 | + Signed { |
| 170 | - connection_id: usize, | ||
| 171 | - user_id: String, | ||
| 172 | - }, | ||
| 173 | - SignedOut { | ||
| 174 | connection_id: usize, | 182 | connection_id: usize, |
| 183 | + user_id: Option<String>, | ||
| 175 | }, | 184 | }, |
| 176 | Broadcast(Box<Broadcast>), | 185 | Broadcast(Box<Broadcast>), |
| 177 | } | 186 | } |
| @@ -254,12 +263,17 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 254 | )); | 263 | )); |
| 255 | 264 | ||
| 256 | while let Ok(streams) = connection.accept_bi().await { | 265 | while let Ok(streams) = connection.accept_bi().await { |
| 257 | - tokio::spawn(route( | 266 | + let route = route( |
| 258 | connection.clone(), | 267 | connection.clone(), |
| 259 | Arc::clone(&state), | 268 | Arc::clone(&state), |
| 260 | streams, | 269 | streams, |
| 261 | shared.clone(), | 270 | shared.clone(), |
| 262 | - )); | 271 | + ); |
| 272 | + tokio::spawn(async move { | ||
| 273 | + if let Err(error) = route.await { | ||
| 274 | + warn!("stream: {error}"); | ||
| 275 | + } | ||
| 276 | + }); | ||
| 263 | } | 277 | } |
| 264 | 278 | ||
| 265 | shared.services.presence.sign_out(connection.stable_id()); | 279 | shared.services.presence.sign_out(connection.stable_id()); |
| @@ -267,7 +281,6 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 267 | 281 | ||
| 268 | if let Some((user_id, token)) = signed_in(&state) { | 282 | if let Some((user_id, token)) = signed_in(&state) { |
| 269 | let conn = database::connect(&shared.db).await?; | 283 | let conn = database::connect(&shared.db).await?; |
| 270 | - authentication::seen(&user_id, &token, &conn).await?; | ||
| 271 | let mut broadcasts = request::leave_connection_voice( | 284 | let mut broadcasts = request::leave_connection_voice( |
| 272 | &shared.services.voice, | 285 | &shared.services.voice, |
| 273 | &shared.services.share, | 286 | &shared.services.share, |
| @@ -278,6 +291,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 278 | broadcasts | 291 | broadcasts |
| 279 | .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); | 292 | .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); |
| 280 | publish(&shared, broadcasts).await; | 293 | publish(&shared, broadcasts).await; |
| 294 | + authentication::seen(&user_id, &token, &conn).await?; | ||
| 281 | } | 295 | } |
| 282 | 296 | ||
| 283 | Ok(()) | 297 | Ok(()) |
| @@ -285,7 +299,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 285 | 299 | ||
| 286 | async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, shared: Shared) { | 300 | async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, shared: Shared) { |
| 287 | while let Ok(bytes) = connection.read_datagram().await { | 301 | while let Ok(bytes) = connection.read_datagram().await { |
| 288 | - if signed_user_id(&state).is_some() { | 302 | + if matches!(*state.lock().unwrap(), State::Authenticated { .. }) { |
| 289 | shared.services.voice.relay(connection.stable_id(), &bytes); | 303 | shared.services.voice.relay(connection.stable_id(), &bytes); |
| 290 | let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); | 304 | let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); |
| 291 | publish(&shared, broadcasts).await; | 305 | publish(&shared, broadcasts).await; |
| @@ -299,12 +313,13 @@ async fn route( | |||
| 299 | (send_stream, mut receive_stream): (SendStream, RecvStream), | 313 | (send_stream, mut receive_stream): (SendStream, RecvStream), |
| 300 | shared: Shared, | 314 | shared: Shared, |
| 301 | ) -> Result<(), Error> { | 315 | ) -> Result<(), Error> { |
| 302 | - match receive_stream_kind(&mut receive_stream).await? { | 316 | + let kind = receive_stream_kind(&mut receive_stream).await?; |
| 317 | + let user = signed_user(&state); | ||
| 318 | + match kind { | ||
| 303 | StreamKind::Request => { | 319 | StreamKind::Request => { |
| 304 | answer(connection, state, (send_stream, receive_stream), shared).await | 320 | answer(connection, state, (send_stream, receive_stream), shared).await |
| 305 | } | 321 | } |
| 306 | StreamKind::Upload => { | 322 | StreamKind::Upload => { |
| 307 | - let user = signed_user(&state); | ||
| 308 | attachment::upload( | 323 | attachment::upload( |
| 309 | user.as_ref(), | 324 | user.as_ref(), |
| 310 | receive_stream, | 325 | receive_stream, |
| @@ -315,7 +330,6 @@ async fn route( | |||
| 315 | .await | 330 | .await |
| 316 | } | 331 | } |
| 317 | StreamKind::Download => { | 332 | StreamKind::Download => { |
| 318 | - let user = signed_user(&state); | ||
| 319 | attachment::download( | 333 | attachment::download( |
| 320 | user.as_ref(), | 334 | user.as_ref(), |
| 321 | receive_stream, | 335 | receive_stream, |
| @@ -326,7 +340,6 @@ async fn route( | |||
| 326 | .await | 340 | .await |
| 327 | } | 341 | } |
| 328 | StreamKind::Backup => { | 342 | StreamKind::Backup => { |
| 329 | - let user = signed_user(&state); | ||
| 330 | backup::download( | 343 | backup::download( |
| 331 | user.as_ref(), | 344 | user.as_ref(), |
| 332 | receive_stream, | 345 | receive_stream, |
| @@ -362,29 +375,27 @@ async fn answer( | |||
| 362 | 375 | ||
| 363 | if before != after { | 376 | if before != after { |
| 364 | let connection_id = connection.stable_id(); | 377 | let connection_id = connection.stable_id(); |
| 365 | - let (event, presence_user_id) = match after { | 378 | + shared.services.visits.forget(connection_id); |
| 366 | - Some((user_id, token)) => { | 379 | + match &after { |
| 367 | - shared | 380 | + Some((user_id, token)) => shared.services.presence.sign_in(&connection, user_id, token), |
| 368 | - .services | 381 | + None => shared.services.presence.sign_out(connection_id), |
| 369 | - .presence | 382 | + } |
| 370 | - .sign_in(&connection, &user_id, &token); | 383 | + let before_id = before.map(|(user_id, _)| user_id); |
| 371 | - ( | 384 | + let after_id = after.map(|(user_id, _)| user_id); |
| 372 | - Event::SignedIn { | 385 | + let _ = shared |
| 373 | - connection_id, | 386 | + .event_sender |
| 374 | - user_id: user_id.clone(), | 387 | + .send(Event::Signed { |
| 375 | - }, | 388 | + connection_id, |
| 376 | - Some(user_id), | 389 | + user_id: after_id.clone(), |
| 377 | - ) | 390 | + }) |
| 378 | - } | 391 | + .await; |
| 379 | - None => { | 392 | + if let Some(user_id) = &before_id { |
| 380 | - shared.services.presence.sign_out(connection_id); | 393 | + broadcast_presence(&shared, user_id).await; |
| 381 | - let user_id = before.map(|(user_id, _)| user_id); | 394 | + } |
| 382 | - (Event::SignedOut { connection_id }, user_id) | 395 | + if after_id != before_id { |
| 396 | + if let Some(user_id) = &after_id { | ||
| 397 | + broadcast_presence(&shared, user_id).await; | ||
| 383 | } | 398 | } |
| 384 | - }; | ||
| 385 | - let _ = shared.event_sender.send(event).await; | ||
| 386 | - if let Some(user_id) = presence_user_id { | ||
| 387 | - broadcast_presence(&shared, &user_id).await; | ||
| 388 | } | 399 | } |
| 389 | } | 400 | } |
| 390 | 401 | ||
| @@ -422,13 +433,6 @@ fn signed_user(state: &Mutex<State>) -> Option<User> { | |||
| 422 | } | 433 | } |
| 423 | } | 434 | } |
| 424 | 435 | ||
| 425 | -fn signed_user_id(state: &Mutex<State>) -> Option<String> { | ||
| 426 | - match &*state.lock().unwrap() { | ||
| 427 | - State::Anonymous => None, | ||
| 428 | - State::Authenticated { user, .. } => Some(user.id.clone()), | ||
| 429 | - } | ||
| 430 | -} | ||
| 431 | - | ||
| 432 | fn signed_in(state: &Mutex<State>) -> Option<(String, String)> { | 436 | fn signed_in(state: &Mutex<State>) -> Option<(String, String)> { |
| 433 | match &*state.lock().unwrap() { | 437 | match &*state.lock().unwrap() { |
| 434 | State::Anonymous => None, | 438 | State::Anonymous => None, |
| @@ -470,7 +474,7 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) { | |||
| 470 | writer, | 474 | writer, |
| 471 | }); | 475 | }); |
| 472 | } | 476 | } |
| 473 | - Event::SignedIn { | 477 | + Event::Signed { |
| 474 | connection_id, | 478 | connection_id, |
| 475 | user_id, | 479 | user_id, |
| 476 | } => { | 480 | } => { |
| @@ -478,15 +482,7 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) { | |||
| 478 | .iter_mut() | 482 | .iter_mut() |
| 479 | .find(|session| session.connection_id == connection_id) | 483 | .find(|session| session.connection_id == connection_id) |
| 480 | { | 484 | { |
| 481 | - session.user_id = Some(user_id); | 485 | + session.user_id = user_id; |
| 482 | - } | ||
| 483 | - } | ||
| 484 | - Event::SignedOut { connection_id } => { | ||
| 485 | - if let Some(session) = sessions | ||
| 486 | - .iter_mut() | ||
| 487 | - .find(|session| session.connection_id == connection_id) | ||
| 488 | - { | ||
| 489 | - session.user_id = None; | ||
| 490 | } | 486 | } |
| 491 | } | 487 | } |
| 492 | Event::Broadcast(broadcast) => { | 488 | Event::Broadcast(broadcast) => { |
| @@ -506,13 +502,10 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) { | |||
| 506 | 502 | ||
| 507 | match session.event_sender.try_send(Arc::clone(&event)) { | 503 | match session.event_sender.try_send(Arc::clone(&event)) { |
| 508 | Ok(()) => true, | 504 | Ok(()) => true, |
| 509 | - Err(mpsc::error::TrySendError::Full(_)) => { | 505 | + Err(error) => { |
| 510 | - warn!("session buffer is full {user_id}"); | 506 | + warn!("session dropped {user_id}: {error}"); |
| 511 | - session.writer.abort(); | ||
| 512 | - false | ||
| 513 | - } | ||
| 514 | - Err(mpsc::error::TrySendError::Closed(_)) => { | ||
| 515 | session.writer.abort(); | 507 | session.writer.abort(); |
| 508 | + session.connection.close(0u32.into(), b"slow"); | ||
| 516 | false | 509 | false |
| 517 | } | 510 | } |
| 518 | } | 511 | } |
crates/server/src/notes.rsmodified+1 -1
| @@ -19,7 +19,7 @@ pub async fn open(me: &str, conn: &mut Connection) -> Result<Community, Error> { | |||
| 19 | let community_id = match find(me, &tx).await? { | 19 | let community_id = match find(me, &tx).await? { |
| 20 | Some(community_id) => community_id, | 20 | Some(community_id) => community_id, |
| 21 | None => { | 21 | None => { |
| 22 | - let community_id = community::create_notes(&tx).await?; | 22 | + let community_id = community::create_fixed(community::Kind::Notes, &tx).await?; |
| 23 | user_community::join(me, &community_id, Rank::Owner, &tx).await?; | 23 | user_community::join(me, &community_id, Rank::Owner, &tx).await?; |
| 24 | tx.execute( | 24 | tx.execute( |
| 25 | "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)", | 25 | "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)", |
crates/server/src/overview.rsmodified+2 -2
| @@ -13,11 +13,11 @@ pub async fn read( | |||
| 13 | "SELECT | 13 | "SELECT |
| 14 | (SELECT COUNT(*) FROM user), | 14 | (SELECT COUNT(*) FROM user), |
| 15 | (SELECT COUNT(*) FROM user WHERE role = ?1), | 15 | (SELECT COUNT(*) FROM user WHERE role = ?1), |
| 16 | - (SELECT COUNT(*) FROM community WHERE kind != ?2), | 16 | + (SELECT COUNT(*) FROM community WHERE kind = ?2), |
| 17 | (SELECT COALESCE(SUM(size), 0) FROM attachment) | 17 | (SELECT COALESCE(SUM(size), 0) FROM attachment) |
| 18 | + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar) | 18 | + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar) |
| 19 | + (SELECT COALESCE(SUM(length(data)), 0) FROM community_avatar)", | 19 | + (SELECT COALESCE(SUM(length(data)), 0) FROM community_avatar)", |
| 20 | - (Role::Builder.as_str(), Kind::Direct.as_str()), | 20 | + (Role::Builder.as_str(), Kind::Group.as_str()), |
| 21 | ) | 21 | ) |
| 22 | .await?; | 22 | .await?; |
| 23 | let row = rows | 23 | let row = rows |
crates/server/src/report.rsmodified+2 -4
| @@ -17,14 +17,12 @@ pub async fn is_open( | |||
| 17 | message_id: Option<&str>, | 17 | message_id: Option<&str>, |
| 18 | conn: &Connection, | 18 | conn: &Connection, |
| 19 | ) -> Result<bool, Error> { | 19 | ) -> Result<bool, Error> { |
| 20 | - let found = database::scalar_i64( | 20 | + database::exists( |
| 21 | conn, | 21 | conn, |
| 22 | "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", | 22 | "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", |
| 23 | (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), | 23 | (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), |
| 24 | ) | 24 | ) |
| 25 | - .await?; | 25 | + .await |
| 26 | - | ||
| 27 | - Ok(found != 0) | ||
| 28 | } | 26 | } |
| 29 | 27 | ||
| 30 | pub async fn insert( | 28 | pub async fn insert( |
crates/server/src/request.rsmodified+30 -14
| @@ -17,8 +17,8 @@ use common::{ | |||
| 17 | share::{Kind, Share}, | 17 | share::{Kind, Share}, |
| 18 | time::{self, MINUTE_MILLIS}, | 18 | time::{self, MINUTE_MILLIS}, |
| 19 | validate::{ | 19 | validate::{ |
| 20 | - validate_avatar_size, validate_forward, validate_message_body, validate_new_message, | 20 | + validate_avatar_size, validate_forward, validate_new_message, validate_poll, |
| 21 | - validate_poll, validate_reaction, validate_reason, validate_server_settings, validate_vote, | 21 | + validate_reaction, validate_reason, validate_server_settings, validate_vote, |
| 22 | }, | 22 | }, |
| 23 | }; | 23 | }; |
| 24 | use turso::Connection; | 24 | use turso::Connection; |
| @@ -88,23 +88,16 @@ async fn dispatch( | |||
| 88 | let (user, token) = | 88 | let (user, token) = |
| 89 | authentication::register(&username, &password, invite.as_deref(), &mut conn) | 89 | authentication::register(&username, &password, invite.as_deref(), &mut conn) |
| 90 | .await?; | 90 | .await?; |
| 91 | - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; | 91 | + enter(state, user, token, voice, share, connection, &conn).await? |
| 92 | - sign_in(state, user, token, broadcasts) | ||
| 93 | } | 92 | } |
| 94 | Request::Login { username, password } => { | 93 | Request::Login { username, password } => { |
| 95 | limit_logins(rate_limit, connection, &conn).await?; | 94 | limit_logins(rate_limit, connection, &conn).await?; |
| 96 | let (user, token) = authentication::login(&username, &password, &conn).await?; | 95 | let (user, token) = authentication::login(&username, &password, &conn).await?; |
| 97 | - stats::mark_active(&user.id, &conn).await?; | 96 | + enter(state, user, token, voice, share, connection, &conn).await? |
| 98 | - record_address(&user, connection, &conn).await?; | ||
| 99 | - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; | ||
| 100 | - sign_in(state, user, token, broadcasts) | ||
| 101 | } | 97 | } |
| 102 | Request::Resume { token } => { | 98 | Request::Resume { token } => { |
| 103 | let user = authentication::resume(&token, &conn).await?; | 99 | let user = authentication::resume(&token, &conn).await?; |
| 104 | - stats::mark_active(&user.id, &conn).await?; | 100 | + enter(state, user, token, voice, share, connection, &conn).await? |
| 105 | - record_address(&user, connection, &conn).await?; | ||
| 106 | - let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; | ||
| 107 | - sign_in(state, user, token, broadcasts) | ||
| 108 | } | 101 | } |
| 109 | Request::Detach => { | 102 | Request::Detach => { |
| 110 | authenticated(state, &conn).await?; | 103 | authenticated(state, &conn).await?; |
| @@ -347,6 +340,9 @@ async fn dispatch( | |||
| 347 | let mut broadcasts = user_updated(&user, &conn).await?; | 340 | let mut broadcasts = user_updated(&user, &conn).await?; |
| 348 | if permission::is_builder(role) { | 341 | if permission::is_builder(role) { |
| 349 | broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); | 342 | broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); |
| 343 | + } else { | ||
| 344 | + user::set_ghost(&user_id, false, &conn).await?; | ||
| 345 | + presence.disconnect(&user_id); | ||
| 350 | } | 346 | } |
| 351 | (Response::User(user), broadcasts) | 347 | (Response::User(user), broadcasts) |
| 352 | } | 348 | } |
| @@ -438,6 +434,8 @@ async fn dispatch( | |||
| 438 | tx.commit().await?; | 434 | tx.commit().await?; |
| 439 | if me.id == user_id { | 435 | if me.id == user_id { |
| 440 | set_state(state, State::Anonymous); | 436 | set_state(state, State::Anonymous); |
| 437 | + } else { | ||
| 438 | + presence.disconnect(&user_id); | ||
| 441 | } | 439 | } |
| 442 | (Response::User(deleted), broadcasts) | 440 | (Response::User(deleted), broadcasts) |
| 443 | } | 441 | } |
| @@ -733,9 +731,11 @@ async fn dispatch( | |||
| 733 | Request::UpdateMessage { message_id, body } => { | 731 | Request::UpdateMessage { message_id, body } => { |
| 734 | let me = authenticated(state, &conn).await?; | 732 | let me = authenticated(state, &conn).await?; |
| 735 | let existing = message::read(&message_id, &conn).await?; | 733 | let existing = message::read(&message_id, &conn).await?; |
| 734 | + allowed(&me, &existing.community_id, &conn, permission::can_post).await?; | ||
| 736 | ensure(existing.user_id == me.id)?; | 735 | ensure(existing.user_id == me.id)?; |
| 737 | - validate_message_body( | 736 | + validate_new_message( |
| 738 | &body, | 737 | &body, |
| 738 | + 0, | ||
| 739 | server_settings::read(&conn).await?.max_message_length as usize, | 739 | server_settings::read(&conn).await?.max_message_length as usize, |
| 740 | )?; | 740 | )?; |
| 741 | let updated = message::update(&message_id, &body, &conn).await?; | 741 | let updated = message::update(&message_id, &body, &conn).await?; |
| @@ -1847,7 +1847,7 @@ async fn effective_presence( | |||
| 1847 | user_id: &str, | 1847 | user_id: &str, |
| 1848 | conn: &Connection, | 1848 | conn: &Connection, |
| 1849 | ) -> Result<Presence, Error> { | 1849 | ) -> Result<Presence, Error> { |
| 1850 | - if !presence.user_ids().iter().any(|id| id == user_id) { | 1850 | + if !presence.is_online(user_id) { |
| 1851 | return Ok(Presence::Offline); | 1851 | return Ok(Presence::Offline); |
| 1852 | } | 1852 | } |
| 1853 | 1853 | ||
| @@ -2082,6 +2082,22 @@ async fn share_left( | |||
| 2082 | Ok(broadcasts) | 2082 | Ok(broadcasts) |
| 2083 | } | 2083 | } |
| 2084 | 2084 | ||
| 2085 | +async fn enter( | ||
| 2086 | + state: &Mutex<State>, | ||
| 2087 | + user: User, | ||
| 2088 | + token: String, | ||
| 2089 | + voice: &Voice, | ||
| 2090 | + share: &Shares, | ||
| 2091 | + connection: Option<&quinn::Connection>, | ||
| 2092 | + conn: &Connection, | ||
| 2093 | +) -> Result<Outcome, Error> { | ||
| 2094 | + stats::mark_active(&user.id, conn).await?; | ||
| 2095 | + record_address(&user, connection, conn).await?; | ||
| 2096 | + let broadcasts = leave_connection_voice(voice, share, connection, conn).await?; | ||
| 2097 | + | ||
| 2098 | + Ok(sign_in(state, user, token, broadcasts)) | ||
| 2099 | +} | ||
| 2100 | + | ||
| 2085 | fn sign_in(state: &Mutex<State>, user: User, token: String, broadcasts: Vec<Broadcast>) -> Outcome { | 2101 | fn sign_in(state: &Mutex<State>, user: User, token: String, broadcasts: Vec<Broadcast>) -> Outcome { |
| 2086 | set_state( | 2102 | set_state( |
| 2087 | state, | 2103 | state, |
crates/server/src/server_ban.rsmodified+3 -7
| @@ -7,7 +7,6 @@ use turso::Connection; | |||
| 7 | use crate::{ | 7 | use crate::{ |
| 8 | database::{self, new_id}, | 8 | database::{self, new_id}, |
| 9 | error::Error, | 9 | error::Error, |
| 10 | - user, | ||
| 11 | }; | 10 | }; |
| 12 | 11 | ||
| 13 | pub async fn insert( | 12 | pub async fn insert( |
| @@ -30,7 +29,7 @@ pub async fn insert( | |||
| 30 | pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> { | 29 | pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> { |
| 31 | let mut rows = conn | 30 | let mut rows = conn |
| 32 | .query( | 31 | .query( |
| 33 | - &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")), | 32 | + "SELECT id, kind, value, reason FROM server_ban ORDER BY kind, value", |
| 34 | (), | 33 | (), |
| 35 | ) | 34 | ) |
| 36 | .await?; | 35 | .await?; |
| @@ -43,7 +42,6 @@ pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> { | |||
| 43 | kind: ServerBanKind::parse(&text).ok_or(CommonError::Server)?, | 42 | kind: ServerBanKind::parse(&text).ok_or(CommonError::Server)?, |
| 44 | value: row.get(2)?, | 43 | value: row.get(2)?, |
| 45 | reason: row.get(3)?, | 44 | reason: row.get(3)?, |
| 46 | - created_by: user::from_row_at(&row, 4)?, | ||
| 47 | }); | 45 | }); |
| 48 | } | 46 | } |
| 49 | 47 | ||
| @@ -51,14 +49,12 @@ pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> { | |||
| 51 | } | 49 | } |
| 52 | 50 | ||
| 53 | async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, Error> { | 51 | async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, Error> { |
| 54 | - let found = database::scalar_i64( | 52 | + database::exists( |
| 55 | conn, | 53 | conn, |
| 56 | "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", | 54 | "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", |
| 57 | (kind.as_str(), value), | 55 | (kind.as_str(), value), |
| 58 | ) | 56 | ) |
| 59 | - .await?; | 57 | + .await |
| 60 | - | ||
| 61 | - Ok(found != 0) | ||
| 62 | } | 58 | } |
| 63 | 59 | ||
| 64 | pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool, Error> { | 60 | pub async fn username_banned(username: &str, conn: &Connection) -> Result<bool, Error> { |
crates/server/src/server_settings.rsmodified+15 -27
| @@ -1,7 +1,7 @@ | |||
| 1 | use common::model::ServerSettings; | 1 | use common::model::ServerSettings; |
| 2 | use turso::Connection; | 2 | use turso::Connection; |
| 3 | 3 | ||
| 4 | -use crate::error::Error; | 4 | +use crate::{error::Error, user}; |
| 5 | 5 | ||
| 6 | const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute"; | 6 | const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute"; |
| 7 | 7 | ||
| @@ -25,35 +25,23 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> { | |||
| 25 | .next() | 25 | .next() |
| 26 | .await? | 26 | .await? |
| 27 | .ok_or(turso::Error::QueryReturnedNoRows)?; | 27 | .ok_or(turso::Error::QueryReturnedNoRows)?; |
| 28 | - let registration_open: i64 = row.get(1)?; | 28 | + let int = |index: usize| -> Result<i64, Error> { Ok(row.get(index)?) }; |
| 29 | - let max_attachment_bytes: i64 = row.get(2)?; | ||
| 30 | - let maintenance: i64 = row.get(3)?; | ||
| 31 | - let user_quota_bytes: i64 = row.get(4)?; | ||
| 32 | - let community_quota_bytes: i64 = row.get(5)?; | ||
| 33 | - let message_retention_days: i64 = row.get(6)?; | ||
| 34 | - let attachment_retention_days: i64 = row.get(7)?; | ||
| 35 | - let announcement: String = row.get(8)?; | ||
| 36 | - let max_communities_per_user: i64 = row.get(9)?; | ||
| 37 | - let max_message_length: i64 = row.get(10)?; | ||
| 38 | - let max_avatar_bytes: i64 = row.get(11)?; | ||
| 39 | - let messages_per_minute: i64 = row.get(12)?; | ||
| 40 | - let logins_per_minute: i64 = row.get(13)?; | ||
| 41 | 29 | ||
| 42 | Ok(ServerSettings { | 30 | Ok(ServerSettings { |
| 43 | name: row.get(0)?, | 31 | name: row.get(0)?, |
| 44 | - registration_open: registration_open != 0, | 32 | + registration_open: user::bool_at(&row, 1)?, |
| 45 | - max_attachment_bytes: max_attachment_bytes as u64, | 33 | + max_attachment_bytes: int(2)? as u64, |
| 46 | - maintenance: maintenance != 0, | 34 | + maintenance: user::bool_at(&row, 3)?, |
| 47 | - user_quota_bytes: user_quota_bytes as u64, | 35 | + user_quota_bytes: int(4)? as u64, |
| 48 | - community_quota_bytes: community_quota_bytes as u64, | 36 | + community_quota_bytes: int(5)? as u64, |
| 49 | - message_retention_days: message_retention_days as u32, | 37 | + message_retention_days: int(6)? as u32, |
| 50 | - attachment_retention_days: attachment_retention_days as u32, | 38 | + attachment_retention_days: int(7)? as u32, |
| 51 | - announcement, | 39 | + announcement: row.get(8)?, |
| 52 | - max_communities_per_user: max_communities_per_user as u32, | 40 | + max_communities_per_user: int(9)? as u32, |
| 53 | - max_message_length: max_message_length as u32, | 41 | + max_message_length: int(10)? as u32, |
| 54 | - max_avatar_bytes: max_avatar_bytes as u64, | 42 | + max_avatar_bytes: int(11)? as u64, |
| 55 | - messages_per_minute: messages_per_minute as u32, | 43 | + messages_per_minute: int(12)? as u32, |
| 56 | - logins_per_minute: logins_per_minute as u32, | 44 | + logins_per_minute: int(13)? as u32, |
| 57 | }) | 45 | }) |
| 58 | } | 46 | } |
| 59 | 47 | ||
crates/server/src/share.rsmodified+19 -26
| @@ -308,10 +308,9 @@ impl Shares { | |||
| 308 | } | 308 | } |
| 309 | 309 | ||
| 310 | pub fn relay(&self, connection_id: usize, packet: &[u8]) -> Vec<Broadcast> { | 310 | pub fn relay(&self, connection_id: usize, packet: &[u8]) -> Vec<Broadcast> { |
| 311 | - let datagram = Datagram::decode(packet); | 311 | + let (kind, fragment) = match Datagram::decode(packet) { |
| 312 | - let kind = match datagram { | 312 | + Some(Datagram::Video(fragment)) => (fragment.kind, Some(fragment)), |
| 313 | - Some(Datagram::Video(fragment)) => fragment.kind, | 313 | + Some(Datagram::ShareAudio { .. }) => (Kind::Screen, None), |
| 314 | - Some(Datagram::ShareAudio { .. }) => Kind::Screen, | ||
| 315 | _ => return Vec::new(), | 314 | _ => return Vec::new(), |
| 316 | }; | 315 | }; |
| 317 | let mut sharings = self.0.lock().unwrap(); | 316 | let mut sharings = self.0.lock().unwrap(); |
| @@ -325,30 +324,24 @@ impl Shares { | |||
| 325 | return Vec::new(); | 324 | return Vec::new(); |
| 326 | }; | 325 | }; |
| 327 | let bytes = Bytes::from(relay); | 326 | let bytes = Bytes::from(relay); |
| 328 | - match datagram { | 327 | + let Some(fragment) = fragment else { |
| 329 | - Some(Datagram::Video(fragment)) => { | 328 | + for viewer in &sharing.viewers { |
| 330 | - let before = sharing.layers(); | 329 | + let _ = viewer.connection.send_datagram(bytes.clone()); |
| 331 | - for viewer in &mut sharing.viewers { | ||
| 332 | - if fragment.keyframe { | ||
| 333 | - viewer.forward = viewer.forward.on_keyframe(fragment.layer); | ||
| 334 | - } | ||
| 335 | - if viewer.forward.live() == Some(fragment.layer) { | ||
| 336 | - let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 337 | - } | ||
| 338 | - } | ||
| 339 | - | ||
| 340 | - layers_changed(sharer_id, kind, sharing, before) | ||
| 341 | - .into_iter() | ||
| 342 | - .collect() | ||
| 343 | } | 330 | } |
| 344 | - Some(Datagram::ShareAudio { .. }) => { | 331 | + return Vec::new(); |
| 345 | - for viewer in &sharing.viewers { | 332 | + }; |
| 346 | - let _ = viewer.connection.send_datagram(bytes.clone()); | 333 | + let before = sharing.layers(); |
| 347 | - } | 334 | + for viewer in &mut sharing.viewers { |
| 348 | - | 335 | + if fragment.keyframe { |
| 349 | - Vec::new() | 336 | + viewer.forward = viewer.forward.on_keyframe(fragment.layer); |
| 337 | + } | ||
| 338 | + if viewer.forward.live() == Some(fragment.layer) { | ||
| 339 | + let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 350 | } | 340 | } |
| 351 | - _ => Vec::new(), | ||
| 352 | } | 341 | } |
| 342 | + | ||
| 343 | + layers_changed(sharer_id, kind, sharing, before) | ||
| 344 | + .into_iter() | ||
| 345 | + .collect() | ||
| 353 | } | 346 | } |
| 354 | } | 347 | } |
crates/server/src/user.rsmodified+51 -97
| @@ -8,7 +8,10 @@ use common::{ | |||
| 8 | use image::ImageFormat; | 8 | use image::ImageFormat; |
| 9 | use turso::{Connection, Row}; | 9 | use turso::{Connection, Row}; |
| 10 | 10 | ||
| 11 | -use crate::{database::new_id, error::Error}; | 11 | +use crate::{ |
| 12 | + database::{self, new_id}, | ||
| 13 | + error::Error, | ||
| 14 | +}; | ||
| 12 | 15 | ||
| 13 | pub fn user_columns(alias: &str) -> String { | 16 | pub fn user_columns(alias: &str) -> String { |
| 14 | format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") | 17 | 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 | |||
| 46 | from_row(&row) | 49 | from_row(&row) |
| 47 | } | 50 | } |
| 48 | 51 | ||
| 52 | +async fn set(column: &str, params: impl turso::IntoParams, conn: &Connection) -> Result<(), Error> { | ||
| 53 | + conn.execute( | ||
| 54 | + &format!("UPDATE user SET {column} = ?2 WHERE id = ?1"), | ||
| 55 | + params, | ||
| 56 | + ) | ||
| 57 | + .await?; | ||
| 58 | + | ||
| 59 | + Ok(()) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +async fn set_returning( | ||
| 63 | + column: &str, | ||
| 64 | + params: impl turso::IntoParams, | ||
| 65 | + conn: &Connection, | ||
| 66 | +) -> Result<User, Error> { | ||
| 67 | + one( | ||
| 68 | + &format!( | ||
| 69 | + "UPDATE user SET {column} = ?2 WHERE id = ?1 RETURNING {}", | ||
| 70 | + user_columns("user") | ||
| 71 | + ), | ||
| 72 | + params, | ||
| 73 | + conn, | ||
| 74 | + ) | ||
| 75 | + .await | ||
| 76 | +} | ||
| 77 | + | ||
| 49 | pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> { | 78 | pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> { |
| 50 | one( | 79 | one( |
| 51 | &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")), | 80 | &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<User, Error> { | |||
| 71 | } | 100 | } |
| 72 | 101 | ||
| 73 | pub async fn any(conn: &Connection) -> Result<bool, Error> { | 102 | pub async fn any(conn: &Connection) -> Result<bool, Error> { |
| 74 | - let mut rows = conn.query("SELECT EXISTS (SELECT 1 FROM user)", ()).await?; | 103 | + database::exists(conn, "SELECT EXISTS (SELECT 1 FROM user)", ()).await |
| 75 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 76 | - | ||
| 77 | - bool_at(&row, 0) | ||
| 78 | } | 104 | } |
| 79 | 105 | ||
| 80 | pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> { | 106 | pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> { |
| @@ -140,29 +166,13 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result< | |||
| 140 | return Err(CommonError::Taken.into()); | 166 | return Err(CommonError::Taken.into()); |
| 141 | } | 167 | } |
| 142 | 168 | ||
| 143 | - one( | 169 | + set_returning("username", (user_id, username), conn).await |
| 144 | - &format!( | ||
| 145 | - "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", | ||
| 146 | - user_columns("user") | ||
| 147 | - ), | ||
| 148 | - (user_id, username), | ||
| 149 | - conn, | ||
| 150 | - ) | ||
| 151 | - .await | ||
| 152 | } | 170 | } |
| 153 | 171 | ||
| 154 | pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result<User, Error> { | 172 | pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result<User, Error> { |
| 155 | validate_status(status)?; | 173 | validate_status(status)?; |
| 156 | 174 | ||
| 157 | - one( | 175 | + set_returning("status", (user_id, status), conn).await |
| 158 | - &format!( | ||
| 159 | - "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", | ||
| 160 | - user_columns("user") | ||
| 161 | - ), | ||
| 162 | - (user_id, status), | ||
| 163 | - conn, | ||
| 164 | - ) | ||
| 165 | - .await | ||
| 166 | } | 176 | } |
| 167 | 177 | ||
| 168 | pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { | 178 | pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> { |
| @@ -217,15 +227,7 @@ async fn set_avatar_id( | |||
| 217 | avatar_id: Option<&str>, | 227 | avatar_id: Option<&str>, |
| 218 | conn: &Connection, | 228 | conn: &Connection, |
| 219 | ) -> Result<User, Error> { | 229 | ) -> Result<User, Error> { |
| 220 | - one( | 230 | + set_returning("avatar_id", (user_id, avatar_id), conn).await |
| 221 | - &format!( | ||
| 222 | - "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", | ||
| 223 | - user_columns("user") | ||
| 224 | - ), | ||
| 225 | - (user_id, avatar_id), | ||
| 226 | - conn, | ||
| 227 | - ) | ||
| 228 | - .await | ||
| 229 | } | 231 | } |
| 230 | 232 | ||
| 231 | pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error> { | 233 | pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error> { |
| @@ -241,15 +243,7 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error | |||
| 241 | } | 243 | } |
| 242 | 244 | ||
| 243 | pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> { | 245 | pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> { |
| 244 | - one( | 246 | + set_returning("role", (user_id, role.as_str()), conn).await |
| 245 | - &format!( | ||
| 246 | - "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", | ||
| 247 | - user_columns("user") | ||
| 248 | - ), | ||
| 249 | - (user_id, role.as_str()), | ||
| 250 | - conn, | ||
| 251 | - ) | ||
| 252 | - .await | ||
| 253 | } | 247 | } |
| 254 | 248 | ||
| 255 | pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error> { | 249 | pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error> { |
| @@ -270,20 +264,16 @@ pub async fn set_timeout( | |||
| 270 | until: Option<u64>, | 264 | until: Option<u64>, |
| 271 | conn: &Connection, | 265 | conn: &Connection, |
| 272 | ) -> Result<(), Error> { | 266 | ) -> Result<(), Error> { |
| 273 | - conn.execute( | 267 | + set( |
| 274 | - "UPDATE user SET suspended_until = ?2 WHERE id = ?1", | 268 | + "suspended_until", |
| 275 | (user_id, until.map(|until| until as i64)), | 269 | (user_id, until.map(|until| until as i64)), |
| 270 | + conn, | ||
| 276 | ) | 271 | ) |
| 277 | - .await?; | 272 | + .await |
| 278 | - | ||
| 279 | - Ok(()) | ||
| 280 | } | 273 | } |
| 281 | 274 | ||
| 282 | pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), Error> { | 275 | pub async fn set_last_ip(user_id: &str, ip: &str, conn: &Connection) -> Result<(), Error> { |
| 283 | - conn.execute("UPDATE user SET last_ip = ?2 WHERE id = ?1", (user_id, ip)) | 276 | + set("last_ip", (user_id, ip), conn).await |
| 284 | - .await?; | ||
| 285 | - | ||
| 286 | - Ok(()) | ||
| 287 | } | 277 | } |
| 288 | 278 | ||
| 289 | pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, Error> { | 279 | pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, Error> { |
| @@ -296,48 +286,24 @@ pub async fn last_ip(user_id: &str, conn: &Connection) -> Result<Option<String>, | |||
| 296 | } | 286 | } |
| 297 | 287 | ||
| 298 | pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, Error> { | 288 | pub async fn builder_ids(conn: &Connection) -> Result<Vec<String>, Error> { |
| 299 | - let mut rows = conn | 289 | + database::ids( |
| 300 | - .query( | 290 | + conn, |
| 301 | - "SELECT id FROM user WHERE role = ?1", | 291 | + "SELECT id FROM user WHERE role = ?1", |
| 302 | - (Role::Builder.as_str(),), | 292 | + (Role::Builder.as_str(),), |
| 303 | - ) | 293 | + ) |
| 304 | - .await?; | 294 | + .await |
| 305 | - let mut ids = Vec::new(); | ||
| 306 | - while let Some(row) = rows.next().await? { | ||
| 307 | - ids.push(row.get(0)?); | ||
| 308 | - } | ||
| 309 | - | ||
| 310 | - Ok(ids) | ||
| 311 | } | 295 | } |
| 312 | 296 | ||
| 313 | pub async fn set_suspended(user_id: &str, suspended: bool, conn: &Connection) -> Result<(), Error> { | 297 | pub async fn set_suspended(user_id: &str, suspended: bool, conn: &Connection) -> Result<(), Error> { |
| 314 | - conn.execute( | 298 | + set("suspended", (user_id, i64::from(suspended)), conn).await |
| 315 | - "UPDATE user SET suspended = ?2 WHERE id = ?1", | ||
| 316 | - (user_id, i64::from(suspended)), | ||
| 317 | - ) | ||
| 318 | - .await?; | ||
| 319 | - | ||
| 320 | - Ok(()) | ||
| 321 | } | 299 | } |
| 322 | 300 | ||
| 323 | pub async fn set_voice_muted(user_id: &str, muted: bool, conn: &Connection) -> Result<(), Error> { | 301 | pub async fn set_voice_muted(user_id: &str, muted: bool, conn: &Connection) -> Result<(), Error> { |
| 324 | - conn.execute( | 302 | + set("voice_muted", (user_id, i64::from(muted)), conn).await |
| 325 | - "UPDATE user SET voice_muted = ?2 WHERE id = ?1", | ||
| 326 | - (user_id, i64::from(muted)), | ||
| 327 | - ) | ||
| 328 | - .await?; | ||
| 329 | - | ||
| 330 | - Ok(()) | ||
| 331 | } | 303 | } |
| 332 | 304 | ||
| 333 | pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), Error> { | 305 | pub async fn set_ghost(user_id: &str, ghost: bool, conn: &Connection) -> Result<(), Error> { |
| 334 | - conn.execute( | 306 | + set("ghost", (user_id, i64::from(ghost)), conn).await |
| 335 | - "UPDATE user SET ghost = ?2 WHERE id = ?1", | ||
| 336 | - (user_id, i64::from(ghost)), | ||
| 337 | - ) | ||
| 338 | - .await?; | ||
| 339 | - | ||
| 340 | - Ok(()) | ||
| 341 | } | 307 | } |
| 342 | 308 | ||
| 343 | pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> { | 309 | pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> { |
| @@ -366,13 +332,7 @@ pub async fn update_presence( | |||
| 366 | presence: Presence, | 332 | presence: Presence, |
| 367 | conn: &Connection, | 333 | conn: &Connection, |
| 368 | ) -> Result<(), Error> { | 334 | ) -> Result<(), Error> { |
| 369 | - conn.execute( | 335 | + set("presence", (user_id, presence.as_str()), conn).await |
| 370 | - "UPDATE user SET presence = ?2 WHERE id = ?1", | ||
| 371 | - (user_id, presence.as_str()), | ||
| 372 | - ) | ||
| 373 | - .await?; | ||
| 374 | - | ||
| 375 | - Ok(()) | ||
| 376 | } | 336 | } |
| 377 | 337 | ||
| 378 | pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> { | 338 | pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> { |
| @@ -394,13 +354,7 @@ pub async fn set_password_hash( | |||
| 394 | password_hash: &str, | 354 | password_hash: &str, |
| 395 | conn: &Connection, | 355 | conn: &Connection, |
| 396 | ) -> Result<(), Error> { | 356 | ) -> Result<(), Error> { |
| 397 | - conn.execute( | 357 | + set("password_hash", (user_id, password_hash), conn).await |
| 398 | - "UPDATE user SET password_hash = ?2 WHERE id = ?1", | ||
| 399 | - (user_id, password_hash), | ||
| 400 | - ) | ||
| 401 | - .await?; | ||
| 402 | - | ||
| 403 | - Ok(()) | ||
| 404 | } | 358 | } |
| 405 | 359 | ||
| 406 | pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> { | 360 | pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> { |
crates/server/src/user_community.rsmodified+49 -39
| @@ -1,10 +1,12 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | + | ||
| 1 | use common::{ | 3 | use common::{ |
| 2 | error::Error as CommonError, | 4 | error::Error as CommonError, |
| 3 | - model::{Ban, Member, Rank, Unread}, | 5 | + model::{Ban, Member, Rank, Unread, mentions}, |
| 4 | }; | 6 | }; |
| 5 | use turso::{Connection, Row}; | 7 | use turso::{Connection, Row}; |
| 6 | 8 | ||
| 7 | -use crate::{community, error::Error, user}; | 9 | +use crate::{community, database, error::Error, user}; |
| 8 | 10 | ||
| 9 | fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> { | 11 | fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> { |
| 10 | let text: String = row.get(index)?; | 12 | let text: String = row.get(index)?; |
| @@ -91,26 +93,47 @@ pub async fn unreads( | |||
| 91 | username: &str, | 93 | username: &str, |
| 92 | conn: &Connection, | 94 | conn: &Connection, |
| 93 | ) -> Result<Vec<Unread>, Error> { | 95 | ) -> Result<Vec<Unread>, Error> { |
| 94 | - let mention = format!("@{}", username.to_lowercase()); | ||
| 95 | let mut rows = conn | 96 | let mut rows = conn |
| 96 | .query( | 97 | .query( |
| 97 | - "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", | 98 | + "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", |
| 98 | - (user_id, mention.as_str()), | 99 | + (user_id,), |
| 99 | ) | 100 | ) |
| 100 | .await?; | 101 | .await?; |
| 101 | 102 | ||
| 102 | let mut unreads = Vec::new(); | 103 | let mut unreads = Vec::new(); |
| 103 | while let Some(row) = rows.next().await? { | 104 | while let Some(row) = rows.next().await? { |
| 104 | let messages: i64 = row.get(1)?; | 105 | let messages: i64 = row.get(1)?; |
| 105 | - let mentions: i64 = row.get(2)?; | ||
| 106 | unreads.push(Unread { | 106 | unreads.push(Unread { |
| 107 | community_id: row.get(0)?, | 107 | community_id: row.get(0)?, |
| 108 | messages: messages as u32, | 108 | messages: messages as u32, |
| 109 | - mentions: mentions as u32, | 109 | + mentions: 0, |
| 110 | - last_read: row.get::<Option<String>>(3)?, | 110 | + last_read: row.get::<Option<String>>(2)?, |
| 111 | }); | 111 | }); |
| 112 | } | 112 | } |
| 113 | 113 | ||
| 114 | + let mention = format!("@{}", username.to_lowercase()); | ||
| 115 | + let mut rows = conn | ||
| 116 | + .query( | ||
| 117 | + "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", | ||
| 118 | + (user_id, mention.as_str()), | ||
| 119 | + ) | ||
| 120 | + .await?; | ||
| 121 | + | ||
| 122 | + let mut mention_counts: HashMap<String, u32> = HashMap::new(); | ||
| 123 | + while let Some(row) = rows.next().await? { | ||
| 124 | + let body: String = row.get(1)?; | ||
| 125 | + if mentions(&body, username) { | ||
| 126 | + *mention_counts.entry(row.get::<String>(0)?).or_default() += 1; | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + for unread in &mut unreads { | ||
| 131 | + unread.mentions = mention_counts | ||
| 132 | + .get(&unread.community_id) | ||
| 133 | + .copied() | ||
| 134 | + .unwrap_or_default(); | ||
| 135 | + } | ||
| 136 | + | ||
| 114 | Ok(unreads) | 137 | Ok(unreads) |
| 115 | } | 138 | } |
| 116 | 139 | ||
| @@ -134,32 +157,23 @@ pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member | |||
| 134 | } | 157 | } |
| 135 | 158 | ||
| 136 | pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, Error> { | 159 | pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, Error> { |
| 137 | - let mut rows = conn | 160 | + let count = database::scalar_i64( |
| 138 | - .query( | 161 | + conn, |
| 139 | - "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", | 162 | + "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", |
| 140 | - (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), | 163 | + (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), |
| 141 | - ) | 164 | + ) |
| 142 | - .await?; | 165 | + .await?; |
| 143 | - let row = rows.next().await?.ok_or(CommonError::Server)?; | ||
| 144 | - let count: i64 = row.get(0)?; | ||
| 145 | 166 | ||
| 146 | Ok(count as usize) | 167 | Ok(count as usize) |
| 147 | } | 168 | } |
| 148 | 169 | ||
| 149 | pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { | 170 | pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> { |
| 150 | - let mut rows = conn | 171 | + database::ids( |
| 151 | - .query( | 172 | + conn, |
| 152 | - "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", | 173 | + "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2", |
| 153 | - (user_id, Rank::Owner.as_str()), | 174 | + (user_id, Rank::Owner.as_str()), |
| 154 | - ) | 175 | + ) |
| 155 | - .await?; | 176 | + .await |
| 156 | - | ||
| 157 | - let mut community_ids = Vec::new(); | ||
| 158 | - while let Some(row) = rows.next().await? { | ||
| 159 | - community_ids.push(row.get(0)?); | ||
| 160 | - } | ||
| 161 | - | ||
| 162 | - Ok(community_ids) | ||
| 163 | } | 177 | } |
| 164 | 178 | ||
| 165 | pub async fn ban( | 179 | pub async fn ban( |
| @@ -192,16 +206,12 @@ pub async fn is_banned( | |||
| 192 | community_id: &str, | 206 | community_id: &str, |
| 193 | conn: &Connection, | 207 | conn: &Connection, |
| 194 | ) -> Result<bool, Error> { | 208 | ) -> Result<bool, Error> { |
| 195 | - let mut rows = conn | 209 | + database::exists( |
| 196 | - .query( | 210 | + conn, |
| 197 | - "SELECT COUNT(*) FROM ban WHERE user_id = ?1 AND community_id = ?2", | 211 | + "SELECT EXISTS (SELECT 1 FROM ban WHERE user_id = ?1 AND community_id = ?2)", |
| 198 | - (user_id, community_id), | 212 | + (user_id, community_id), |
| 199 | - ) | 213 | + ) |
| 200 | - .await?; | 214 | + .await |
| 201 | - let row = rows.next().await?.ok_or(CommonError::NotFound)?; | ||
| 202 | - let count: i64 = row.get(0)?; | ||
| 203 | - | ||
| 204 | - Ok(count > 0) | ||
| 205 | } | 215 | } |
| 206 | 216 | ||
| 207 | pub async fn bans(community_id: &str, conn: &Connection) -> Result<Vec<Ban>, Error> { | 217 | pub async fn bans(community_id: &str, conn: &Connection) -> Result<Vec<Ban>, Error> { |
crates/server/src/voice.rsmodified+24 -44
| @@ -59,6 +59,14 @@ impl Room { | |||
| 59 | .any(|participant| !participant.ghost) | 59 | .any(|participant| !participant.ghost) |
| 60 | } | 60 | } |
| 61 | 61 | ||
| 62 | + fn user_ids(&self, keep: impl Fn(&Participant) -> bool) -> Vec<String> { | ||
| 63 | + self.participants | ||
| 64 | + .iter() | ||
| 65 | + .filter(|participant| keep(participant)) | ||
| 66 | + .map(|participant| participant.user_id.clone()) | ||
| 67 | + .collect() | ||
| 68 | + } | ||
| 69 | + | ||
| 62 | fn admit(&mut self) { | 70 | fn admit(&mut self) { |
| 63 | if self.occupied() { | 71 | if self.occupied() { |
| 64 | self.outcome = Outcome::Answered; | 72 | self.outcome = Outcome::Answered; |
| @@ -159,12 +167,7 @@ impl Voice { | |||
| 159 | .lock() | 167 | .lock() |
| 160 | .unwrap() | 168 | .unwrap() |
| 161 | .get(community_id) | 169 | .get(community_id) |
| 162 | - .map(|room| { | 170 | + .map(|room| room.user_ids(|_| true)) |
| 163 | - room.participants | ||
| 164 | - .iter() | ||
| 165 | - .map(|participant| participant.user_id.clone()) | ||
| 166 | - .collect() | ||
| 167 | - }) | ||
| 168 | .unwrap_or_default() | 171 | .unwrap_or_default() |
| 169 | } | 172 | } |
| 170 | 173 | ||
| @@ -178,7 +181,7 @@ impl Voice { | |||
| 178 | 181 | ||
| 179 | pub fn leave_connection(&self, connection_id: usize) -> Option<Left> { | 182 | pub fn leave_connection(&self, connection_id: usize) -> Option<Left> { |
| 180 | let mut rooms = self.0.lock().unwrap(); | 183 | let mut rooms = self.0.lock().unwrap(); |
| 181 | - let user_id = find(&rooms, connection_id)?.user_id.clone(); | 184 | + let user_id = find(&rooms, connection_id)?.1.user_id.clone(); |
| 182 | 185 | ||
| 183 | leave_locked(&mut rooms, &user_id) | 186 | leave_locked(&mut rooms, &user_id) |
| 184 | } | 187 | } |
| @@ -201,13 +204,7 @@ impl Voice { | |||
| 201 | .lock() | 204 | .lock() |
| 202 | .unwrap() | 205 | .unwrap() |
| 203 | .get(community_id) | 206 | .get(community_id) |
| 204 | - .map(|room| { | 207 | + .map(|room| room.user_ids(|participant| !participant.ghost)) |
| 205 | - room.participants | ||
| 206 | - .iter() | ||
| 207 | - .filter(|participant| !participant.ghost) | ||
| 208 | - .map(|participant| participant.user_id.clone()) | ||
| 209 | - .collect() | ||
| 210 | - }) | ||
| 211 | .unwrap_or_default() | 208 | .unwrap_or_default() |
| 212 | } | 209 | } |
| 213 | 210 | ||
| @@ -217,19 +214,11 @@ impl Voice { | |||
| 217 | .unwrap() | 214 | .unwrap() |
| 218 | .iter() | 215 | .iter() |
| 219 | .map(|(community_id, room)| { | 216 | .map(|(community_id, room)| { |
| 220 | - let user_ids = room | 217 | + ( |
| 221 | - .participants | 218 | + community_id.clone(), |
| 222 | - .iter() | 219 | + room.user_ids(|_| true), |
| 223 | - .map(|participant| participant.user_id.clone()) | 220 | + room.user_ids(|participant| participant.ghost), |
| 224 | - .collect(); | 221 | + ) |
| 225 | - let ghost_ids = room | ||
| 226 | - .participants | ||
| 227 | - .iter() | ||
| 228 | - .filter(|participant| participant.ghost) | ||
| 229 | - .map(|participant| participant.user_id.clone()) | ||
| 230 | - .collect(); | ||
| 231 | - | ||
| 232 | - (community_id.clone(), user_ids, ghost_ids) | ||
| 233 | }) | 222 | }) |
| 234 | .collect() | 223 | .collect() |
| 235 | } | 224 | } |
| @@ -251,18 +240,7 @@ impl Voice { | |||
| 251 | return; | 240 | return; |
| 252 | }; | 241 | }; |
| 253 | let rooms = self.0.lock().unwrap(); | 242 | let rooms = self.0.lock().unwrap(); |
| 254 | - let Some(room) = rooms.values().find(|room| { | 243 | + let Some((room, sender)) = find(&rooms, connection_id) else { |
| 255 | - room.participants | ||
| 256 | - .iter() | ||
| 257 | - .any(|participant| participant.connection.stable_id() == connection_id) | ||
| 258 | - }) else { | ||
| 259 | - return; | ||
| 260 | - }; | ||
| 261 | - let Some(sender) = room | ||
| 262 | - .participants | ||
| 263 | - .iter() | ||
| 264 | - .find(|participant| participant.connection.stable_id() == connection_id) | ||
| 265 | - else { | ||
| 266 | return; | 244 | return; |
| 267 | }; | 245 | }; |
| 268 | if sender.muted { | 246 | if sender.muted { |
| @@ -294,11 +272,13 @@ impl Voice { | |||
| 294 | } | 272 | } |
| 295 | } | 273 | } |
| 296 | 274 | ||
| 297 | -fn find(rooms: &Rooms, connection_id: usize) -> Option<&Participant> { | 275 | +fn find(rooms: &Rooms, connection_id: usize) -> Option<(&Room, &Participant)> { |
| 298 | - rooms | 276 | + rooms.values().find_map(|room| { |
| 299 | - .values() | 277 | + room.participants |
| 300 | - .flat_map(|room| &room.participants) | 278 | + .iter() |
| 301 | - .find(|participant| participant.connection.stable_id() == connection_id) | 279 | + .find(|participant| participant.connection.stable_id() == connection_id) |
| 280 | + .map(|sender| (room, sender)) | ||
| 281 | + }) | ||
| 302 | } | 282 | } |
| 303 | 283 | ||
| 304 | fn left(community_id: &str, participant: Participant, call: Option<CallEnd>) -> Left { | 284 | fn left(community_id: &str, participant: Participant, call: Option<CallEnd>) -> Left { |
crates/spectrum/src/lib.rsmodified+4 -6
| @@ -39,13 +39,11 @@ impl Analyzer { | |||
| 39 | } | 39 | } |
| 40 | 40 | ||
| 41 | pub fn bands(&self, samples: &[f32]) -> Vec<f32> { | 41 | pub fn bands(&self, samples: &[f32]) -> Vec<f32> { |
| 42 | - let offset = WINDOW.saturating_sub(samples.len()); | ||
| 43 | let mut buffer = vec![Complex::default(); WINDOW]; | 42 | let mut buffer = vec![Complex::default(); WINDOW]; |
| 44 | - for (index, sample) in samples.iter().rev().take(WINDOW).enumerate() { | 43 | + let tail = &samples[samples.len().saturating_sub(WINDOW)..]; |
| 45 | - let at = WINDOW - 1 - index; | 44 | + let start = WINDOW - tail.len(); |
| 46 | - if at >= offset { | 45 | + for (index, sample) in tail.iter().enumerate() { |
| 47 | - buffer[at].re = sample * self.hann[at]; | 46 | + buffer[start + index].re = sample * self.hann[start + index]; |
| 48 | - } | ||
| 49 | } | 47 | } |
| 50 | self.fft.process(&mut buffer); | 48 | self.fft.process(&mut buffer); |
| 51 | self.edges | 49 | self.edges |