diff --git a/.gitignore b/.gitignore index b765c78..20296a8 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ Cargo.lock configs/server_config.toml *.pem yumush.db* +attachments/ +backups/ diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 36e0773..21af393 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -8,7 +8,7 @@ common.workspace = true tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } -gpui-kit = "0.11.0" +gpui-kit = { version = "0.11.0", features = ["syntect"] } ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } @@ -33,6 +33,7 @@ rtrb = "0.4.1" [target.'cfg(target_os = "linux")'.dependencies] pipewire = { version = "0.10.1", features = ["v0_3_49"] } +ksni = "0.3.7" [target.'cfg(target_os = "windows")'.dependencies] wasapi = "0.27.0" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 1e98497..c799b7f 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -3,33 +3,40 @@ use std::{ fmt::Display, hash::{DefaultHasher, Hash, Hasher}, sync::Arc, + time::Duration, }; use common::{ constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, error::Error, event::Event, - model::{Community, CommunityKind, Rank, ServerSettings, User}, + model::{ + BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, ServerSettings, + Unread, User, mentions, + }, time::created_at_ms, }; use gpui_kit::{ - AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight, - Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, - KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful, + Anchor, Animation, AnimationElement, AnimationExt, AnyElement, AnyWindowHandle, App, + AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, + ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, KeyUpEvent, + ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful, StatefulInteractiveElement, Styled, WeakEntity, Window, actions, base::Selectable, component::{ - ActiveTheme, Theme, WindowExt, + ActiveTheme, Sizable, Theme, WindowExt, input::{Input, InputEvent, InputState}, notification::Notification, + spinner::Spinner, }, - div, hsla, img, px, rems, rgb, + div, ease_out_quint, hsla, img, px, rems, rgb, }; use jiff::{Timestamp, tz::TimeZone}; use tokio::sync::mpsc; use crate::{ accounts::{self, Accounts}, + mutes, network::{NetworkEvent, NetworkHandle}, settings::{Look, Scale, Settings, ThemeChoice}, }; @@ -42,12 +49,15 @@ mod composer; mod forward; mod media_view; mod message_actions; +mod poll; mod profile; mod settings_page; mod sidebar; mod snippet; mod social; +mod voice_note; mod voice_settings; +mod voice_stats; use auth::Auth; use chat::{Chat, View}; @@ -99,7 +109,7 @@ impl Palette { return self; }; let (id, avatar_id) = match &community.kind { - CommunityKind::Group => (&community.id, &community.avatar_id), + CommunityKind::Group | CommunityKind::Notes => (&community.id, &community.avatar_id), CommunityKind::Direct { peer } => (&peer.id, &peer.avatar_id), }; let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) { @@ -250,7 +260,9 @@ pub fn avatar( pub fn community_name(community: &Community) -> &str { match &community.kind { CommunityKind::Group => &community.name, - CommunityKind::Direct { peer } => &peer.username, + CommunityKind::Direct { peer } if community.name.is_empty() => &peer.username, + CommunityKind::Direct { .. } => &community.name, + CommunityKind::Notes => "Notes", } } @@ -272,6 +284,7 @@ pub fn community_icon( None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)), }, CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars), + CommunityKind::Notes => badge(palette, &community.id, "Notes", size, font).rounded(px(4.)), } } @@ -314,6 +327,42 @@ pub fn millis_time(millis: u64, format: &str) -> String { .to_string() } +const MOTION_TRAVEL: f32 = 6.; + +pub fn motion() -> Animation { + Animation::new(Duration::from_millis(160)).with_easing(ease_out_quint()) +} + +pub fn pop_in( + id: impl Into, + element: E, + anchor: Anchor, +) -> AnimationElement { + let travel = match anchor.is_bottom() { + true => MOTION_TRAVEL, + false => -MOTION_TRAVEL, + }; + + element.with_animation(id, motion(), move |element, delta| { + element.top(px(travel * (1. - delta))).opacity(delta) + }) +} + +pub fn swap_in( + id: impl Into, + element: E, + forward: bool, +) -> AnimationElement { + let travel = match forward { + true => MOTION_TRAVEL, + false => -MOTION_TRAVEL, + }; + + element.with_animation(id, motion(), move |element, delta| { + element.left(px(travel * (1. - delta))).opacity(delta) + }) +} + pub fn hoverable(id: impl Into, element: Div, palette: Palette) -> Stateful
{ hoverable_with(id, element, palette.hover) } @@ -429,11 +478,41 @@ pub fn rank_tag(rank: Option, palette: Palette) -> Option
{ ) } +pub fn presence_color(presence: Presence, palette: Palette) -> Hsla { + match presence { + Presence::Online => palette.ok, + Presence::Busy => palette.danger, + Presence::Offline => palette.muted, + } +} + +pub fn presence_avatar( + avatar: impl IntoElement, + presence: Presence, + size: Pixels, + palette: Palette, +) -> Div { + let dot = if size > px(20.) { px(10.) } else { px(8.) }; + + div().relative().flex_shrink_0().child(avatar).child( + div() + .absolute() + .right(px(-2.)) + .bottom(px(-2.)) + .size(dot) + .rounded_full() + .border_2() + .border_color(palette.window) + .bg(presence_color(presence, palette)), + ) +} + pub fn bind_keys(cx: &mut App) { cx.bind_keys([ KeyBinding::new(FIND_KEY, FocusFind, None), KeyBinding::new("escape", CloseSettings, None), ]); + composer::bind_keys(cx); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -443,19 +522,83 @@ enum Route { Chat, } +#[derive(Debug, Clone, PartialEq)] +enum Connection { + Connecting, + Connected, + Lost { error: String, attempts: u32 }, +} + +impl Connection { + fn is_connected(&self) -> bool { + matches!(self, Self::Connected) + } + + fn lost(&mut self, error: &Error) { + let attempts = match self { + Self::Lost { attempts, .. } => *attempts + 1, + _ => 1, + }; + *self = Self::Lost { + error: reason(error), + attempts, + }; + } +} + +fn reason(error: &Error) -> String { + let text = error.to_string(); + let lower = text.to_lowercase(); + if lower.contains("timed out") || lower.contains("unreachable") { + "Server unreachable".into() + } else if lower.contains("certificate") || lower.contains("tls") { + "Certificate error".into() + } else if lower.contains("refused") { + "Connection refused".into() + } else { + text + } +} + +fn connection_notice(connection: &Connection, palette: Palette) -> Option
{ + let (label, color) = match connection { + Connection::Connecting => ("Connecting…".to_string(), palette.muted), + Connection::Connected => return None, + Connection::Lost { error, attempts } => { + (format!("Reconnecting… {error} ({attempts})"), palette.alert) + } + }; + Some( + div() + .h(px(22.)) + .flex() + .items_center() + .justify_center() + .gap(px(6.)) + .text_size(text(11.)) + .text_color(color) + .child(Spinner::new().xsmall().color(color)) + .child(label), + ) +} + pub struct Yumush { user: Option, current_route: Route, auth: Auth, chat: Chat, network: NetworkHandle, - connected: bool, + connection: Connection, server: Option, dismissed_announcement: Option, settings: Settings, accounts: Accounts, voice: VoiceControls, focus: gpui_kit::FocusHandle, + window: Option, + deferred: Vec, + backups: Vec, + pending_backup_delete: Option, } impl Yumush { @@ -468,31 +611,30 @@ impl Yumush { ) -> Self { network.set_voice_settings(settings.voice.clone()); - cx.spawn_in(window, async move |this, cx| { + cx.spawn(async move |this, cx| { while let Some(event) = network_event_receiver.recv().await { - let updated = this.update_in(cx, |yumush, window, cx| { - yumush.handle_network_event(event, window, cx); - }); - - if updated.is_err() { + let Ok(handle) = this.read_with(cx, |yumush, _| yumush.window) else { + break; + }; + let mut event = Some(event); + if let Some(handle) = handle { + let _ = handle.update(cx, |_, window, cx| { + if let Some(event) = event.take() { + let _ = this.update(cx, |yumush, cx| { + yumush.handle_network_event(event, Some(window), cx) + }); + } + }); + } + if let Some(event) = event + && this + .update(cx, |yumush, cx| { + yumush.handle_network_event(event, None, cx) + }) + .is_err() + { break; } - } - }) - .detach(); - - cx.observe_window_appearance(window, |yumush, window, cx| { - if yumush.settings.theme == ThemeChoice::System { - Theme::sync_system_appearance(Some(window), cx); - sync_theme(cx); - } - cx.notify(); - }) - .detach(); - - cx.observe_window_activation(window, |yumush, window, _| { - if !window.is_window_active() { - yumush.network.set_talking(false); } }) .detach(); @@ -506,15 +648,63 @@ impl Yumush { auth: Auth::new(window, cx), chat: Chat::new(window, cx), network, - connected: false, + connection: Connection::Connecting, server: None, dismissed_announcement: None, settings, accounts: accounts::load(), voice, + window: None, + deferred: Vec::new(), + backups: Vec::new(), + pending_backup_delete: None, } } + pub fn tray_state(&self) -> crate::tray::TrayState { + let groups = self.chat.unread_total(true); + let direct = self.chat.unread_total(false); + crate::tray::TrayState { + messages: groups.messages + direct.messages, + mentions: groups.mentions + direct.mentions, + } + } + + pub fn attach_window(&mut self, window: &mut Window, cx: &mut Context) { + self.window = Some(window.window_handle()); + + cx.observe_window_appearance(window, |yumush, window, cx| { + if yumush.settings.theme == ThemeChoice::System { + Theme::sync_system_appearance(Some(window), cx); + sync_theme(cx); + } + cx.notify(); + }) + .detach(); + + cx.observe_window_activation(window, |yumush, window, cx| { + if window.is_window_active() { + yumush.read_selected(cx); + } else { + yumush.network.set_talking(false); + } + }) + .detach(); + + for event in std::mem::take(&mut self.deferred) { + self.handle_network_event(event, Some(window), cx); + } + } + + pub fn window(&self) -> Option { + self.window + } + + pub fn detach_window(&mut self) -> bool { + self.window = None; + self.settings.close_to_tray + } + pub(super) fn enter_session( &mut self, user: User, @@ -524,6 +714,7 @@ impl Yumush { ) { self.accounts.sign_in(&user, token); self.request_user_avatar(&user, cx); + self.chat.muted = mutes::load(&user.id); self.user = Some(user); self.change_page(Route::Chat, window, cx); self.load_communities(window, cx); @@ -540,7 +731,7 @@ impl Yumush { let Some(account) = self.accounts.get(&user_id).cloned() else { return; }; - if !self.connected { + if !self.connection.is_connected() { window.push_notification(Notification::error("Not connected"), cx); return; } @@ -584,6 +775,17 @@ impl Yumush { cx.notify(); } + pub(super) fn toggle_community_mute(&mut self, community_id: String, cx: &mut Context) { + let Some(me) = self.user.as_ref().map(|me| me.id.clone()) else { + return; + }; + if !self.chat.muted.remove(&community_id) { + self.chat.muted.insert(community_id); + } + mutes::save(&me, &self.chat.muted); + cx.notify(); + } + fn logout(&mut self, window: &mut Window, cx: &mut Context) { let Some(user) = self.user.take() else { return; @@ -667,6 +869,33 @@ impl Yumush { self.user.as_ref().and_then(|me| self.chat.my_rank(me)) } + pub fn community_badge( + &self, + community: &Community, + size: Pixels, + font: Rems, + palette: Palette, + ) -> Div { + let icon = community_icon(palette, community, size, font, &self.chat.avatars); + match &community.kind { + CommunityKind::Direct { peer } => { + presence_avatar(icon, self.presence_of(&peer.id), size, palette) + } + CommunityKind::Group | CommunityKind::Notes => icon, + } + } + + pub fn presence_of(&self, user_id: &str) -> Presence { + if self.is_me(user_id) && !self.connection.is_connected() { + return Presence::Offline; + } + self.chat + .presences + .get(user_id) + .copied() + .unwrap_or(Presence::Offline) + } + pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context) { if self.chat.avatars.contains_key(avatar_id) || self.chat.avatar_requests.contains(avatar_id) @@ -724,13 +953,114 @@ impl Yumush { user_id, muted: true, } if self.is_me(user_id) => self.force_mute(cx), + Event::Typing { .. } => { + cx.spawn(async move |this, cx| { + cx.background_executor().timer(chat::TYPING_TTL).await; + let _ = this.update(cx, |_, cx| cx.notify()); + }) + .detach(); + } _ => {} } - self.chat.apply_event(event); + self.chat + .apply_event(event, self.user.as_ref().map(|user| user.id.as_str())); + self.request_authors(cx); self.request_social_avatars(cx); self.request_media(cx); } + fn mark_read(&mut self, community_id: &str, message_id: &str, cx: &mut Context) { + self.chat.mark_read(community_id, message_id); + let network = self.network.clone(); + let community_id = community_id.to_string(); + let message_id = message_id.to_string(); + + cx.spawn(async move |_, _| { + let _ = network.mark_read(&community_id, &message_id).await; + }) + .detach(); + } + + fn read_selected(&mut self, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let Some(message_id) = self.chat.messages.last().map(|message| message.id.clone()) else { + return; + }; + if self + .chat + .unread + .get(&community_id) + .is_some_and(|unread| unread.messages > 0) + { + self.mark_read(&community_id, &message_id, cx); + } + } + + fn count_message(&mut self, message: &Message, active: bool, cx: &mut Context) { + let Some(me) = self.user.as_ref() else { + return; + }; + if message.user_id == me.id { + return; + } + if active && self.chat.is_selected(&message.community_id) { + self.mark_read(&message.community_id, &message.id, cx); + return; + } + let unread = self + .chat + .unread + .entry(message.community_id.clone()) + .or_insert_with(|| Unread { + community_id: message.community_id.clone(), + messages: 0, + mentions: 0, + last_read: None, + }); + unread.messages += 1; + if mentions(&message.body, &me.username) { + unread.mentions += 1; + } + } + + fn should_notify(&self, message: &Message, active: bool) -> bool { + let Some(me) = self.user.as_ref() else { + return false; + }; + let viewing = active && self.chat.is_selected(&message.community_id); + + message.user_id != me.id + && message.call.is_none() + && !self.chat.muted.contains(&message.community_id) + && self.presence_of(&me.id) == Presence::Online + && !viewing + } + + fn starts_call(&self, community_id: &str, user_id: &str) -> bool { + !self.is_me(user_id) + && self.chat.voice_ids(community_id).is_empty() + && self.is_direct(community_id) + } + + fn ends_call(&self, community_id: &str, user_id: &str) -> bool { + !self.is_me(user_id) + && self.chat.in_voice(community_id) + && self.is_direct(community_id) + && self + .chat + .voice_ids(community_id) + .iter() + .all(|id| id == user_id || self.is_me(id)) + } + + pub(super) fn is_direct(&self, community_id: &str) -> bool { + self.chat.communities().iter().any(|community| { + community.id == community_id && matches!(community.kind, CommunityKind::Direct { .. }) + }) + } + fn is_me(&self, user_id: &str) -> bool { self.user.as_ref().is_some_and(|me| me.id == user_id) } @@ -792,20 +1122,70 @@ impl Yumush { fn handle_network_event( &mut self, event: NetworkEvent, - window: &mut Window, + window: Option<&mut Window>, cx: &mut Context, ) { + let active = window + .as_ref() + .is_some_and(|window| window.is_window_active()); + if let NetworkEvent::Pushed(pushed) = &event + && let Event::MessageCreated(message) = pushed.as_ref() + && self.should_notify(message, active) + { + self.network.play_notification(); + } + + if let NetworkEvent::Pushed(pushed) = &event + && let Event::MessageCreated(message) = pushed.as_ref() + { + self.count_message(message, active, cx); + } + + if let NetworkEvent::Pushed(pushed) = &event + && let Event::MessageCreated(message) = pushed.as_ref() + && message.call == Some(CallLog::Declined) + && self.chat.in_voice(&message.community_id) + { + self.end_voice(cx); + } + + if let NetworkEvent::Pushed(pushed) = &event + && let Event::VoiceJoined { + community_id, + user_id, + } = pushed.as_ref() + && self.starts_call(community_id, user_id) + { + self.chat.ringing.insert(community_id.clone()); + } + + if let NetworkEvent::Pushed(pushed) = &event + && let Event::VoiceLeft { + community_id, + user_id, + } = pushed.as_ref() + && self.ends_call(community_id, user_id) + { + self.end_voice(cx); + } + + let Some(window) = window else { + self.handle_hidden(event, cx); + return; + }; + match event { NetworkEvent::Connected => { - self.connected = true; + self.connection = Connection::Connected; self.load_server_settings(window, cx); if self.user.is_some() { self.reload(window, cx); + self.rejoin_voice(window, cx); } else if let Some(active) = self.accounts.active.clone() { self.switch_account(active, window, cx); } } - NetworkEvent::Disconnected(_) => self.connected = false, + NetworkEvent::Disconnected(error) => self.connection.lost(&error), NetworkEvent::SessionLost => { if let Some(user) = &self.user { self.accounts.forget(&user.id.clone()); @@ -860,6 +1240,33 @@ impl Yumush { }, } + self.update_ringing(cx); + cx.notify(); + } + + fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context) { + match event { + NetworkEvent::Connected => { + self.connection = Connection::Connected; + self.deferred.push(NetworkEvent::Connected); + } + NetworkEvent::Disconnected(error) => self.connection.lost(&error), + NetworkEvent::SessionLost => self.deferred.push(NetworkEvent::SessionLost), + NetworkEvent::Pushed(event) => match *event { + Event::MemberLeft { .. } + | Event::Removed { .. } + | Event::CommunityDeleted { .. } + | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)), + Event::Announcement { text } => { + if let Some(settings) = self.server.as_mut() { + settings.announcement = text; + } + } + event => self.apply_pushed(event, cx), + }, + } + + self.update_ringing(cx); cx.notify(); } } @@ -951,8 +1358,13 @@ impl Render for Yumush { Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(), Route::Chat => self.chat_page(cx).into_any_element(), }; + let banner = (route == Route::Chat) + .then(|| connection_notice(&self.connection, palette)) + .flatten(); div() + .flex() + .flex_col() .size_full() .bg(palette.window) .text_color(palette.text) @@ -977,6 +1389,7 @@ impl Render for Yumush { .on_modifiers_changed(cx.listener(|this, event: &ModifiersChangedEvent, _, cx| { this.voice_modifiers(event, cx); })) - .child(page) + .children(banner) + .child(div().flex_1().min_h_0().child(page)) } } diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index de9c2b7..3d14c29 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -1,4 +1,5 @@ use super::{ + Tooltip as _, settings_page::{segment, segment_track}, text, }; @@ -11,8 +12,8 @@ use gpui_kit::{ use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon}; use crate::gui::{ - Palette, Route, Yumush, badge, clickable, hoverable, new_input, notify_error, palette, - primary_button, + Palette, Route, Yumush, badge, clickable, connection_notice, hoverable, new_input, + notify_error, palette, primary_button, }; pub struct Auth { @@ -186,7 +187,8 @@ impl Yumush { .child(field(palette, &self.auth.username_input)) .child(password_field(palette, &self.auth.password_input)) .children(invite) - .child(action_button), + .child(action_button) + .children(connection_notice(&self.connection, palette)), ) } } @@ -237,6 +239,7 @@ impl Yumush { }); }, ) + .tip("Forget") .size(px(22.)) .flex() .items_center() diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 7b98ae6..2f4f4de 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -1,4 +1,5 @@ mod access; +mod backups; mod communities; mod log; mod messages; diff --git a/crates/client/src/gui/builder/backups.rs b/crates/client/src/gui/builder/backups.rs new file mode 100644 index 0000000..4e32e9c --- /dev/null +++ b/crates/client/src/gui/builder/backups.rs @@ -0,0 +1,210 @@ +use common::model::BackupInfo; +use gpui_kit::{ + Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, + component::Icon, div, prelude::FluentBuilder as _, px, +}; + +use super::ui::{accent_button, card, card_header, list_row}; +use crate::gui::{ + DATE, Palette, Tooltip, Yumush, clickable, entity_action, millis_time, notify_error, storage, + text, +}; + +fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette: Palette) -> Div { + let export_name = info.name.clone(); + let export = clickable( + format!("export_backup_{}", info.name), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.export_backup(&export_name, window, cx) + }), + ) + .tip("Export") + .size(px(26.)) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Download).w(px(14.)).h(px(14.))); + + let delete_name = info.name.clone(); + let delete = clickable( + format!("delete_backup_{}", info.name), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_backup(&delete_name, window, cx) + }), + ) + .tip(if pending { "Confirm" } else { "Delete" }) + .size(px(26.)) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.danger) + .when(pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) + .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.))); + + list_row() + .child( + Icon::new(IconName::HardDrive) + .w(px(16.)) + .h(px(16.)) + .flex_shrink_0() + .text_color(palette.muted), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(text(13.)) + .text_color(palette.text) + .child(info.name.clone()), + ) + .child( + div() + .flex_shrink_0() + .text_size(text(12.)) + .text_color(palette.muted) + .child(millis_time(info.created_ms, DATE)), + ) + .child( + div() + .w(px(72.)) + .flex_shrink_0() + .flex() + .justify_end() + .text_size(text(12.)) + .text_color(palette.muted) + .child(storage(info.size_bytes)), + ) + .child(export) + .child(delete) +} + +impl Yumush { + pub(super) fn backups_card(&self, entity: &Entity, palette: Palette) -> Div { + let create = accent_button( + "create_backup", + "Create", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.create_backup(window, cx) + }), + ) + .into_any_element(); + let rows: Vec
= self + .backups + .iter() + .map(|info| { + let pending = self.pending_backup_delete.as_deref() == Some(info.name.as_str()); + backup_row(info, pending, entity, palette) + }) + .collect(); + let body = if rows.is_empty() { + div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child("No backups") + } else { + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) + }; + + card(palette) + .child(card_header("Backups", vec![create], palette)) + .child(body) + } + + pub(super) fn load_backups(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let backups = match network.backups().await { + Ok(backups) => backups, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.backups = backups; + cx.notify(); + }); + }) + .detach(); + } + + fn create_backup(&self, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.create_backup().await { + Ok(_) => { + let _ = + this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context) { + if self.pending_backup_delete.as_deref() != Some(name) { + self.pending_backup_delete = Some(name.to_string()); + cx.notify(); + return; + } + self.pending_backup_delete = None; + let network = self.network.clone(); + let name = name.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_backup(&name).await { + Ok(()) => { + let _ = + this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + fn export_backup(&self, name: &str, window: &mut Window, cx: &mut Context) { + let directory = dirs::download_dir().unwrap_or_else(std::env::temp_dir); + let target = cx.prompt_for_new_path(&directory, Some(name)); + let network = self.network.clone(); + let name = name.to_string(); + + cx.spawn_in(window, async move |this, cx| { + let Ok(Ok(Some(target))) = target.await else { + return; + }; + if let Err(error) = network.download_backup(&name, target).await { + notify_error(&this, cx, error); + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs index 6659a9e..e6727cc 100644 --- a/crates/client/src/gui/builder/communities.rs +++ b/crates/client/src/gui/builder/communities.rs @@ -1,4 +1,4 @@ -use common::model::{Community, CommunitySummary, Member, Rank}; +use common::model::{Community, CommunityKind, CommunitySummary, Member, Rank}; use gpui_kit::{ AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px, @@ -10,7 +10,7 @@ use super::{ }; use crate::gui::{ Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text, - entity_action, notify_error, text, + entity_action, notify_error, profile::user_link, text, }; fn rows_body(rows: Vec
, empty: &str, palette: Palette) -> Div { @@ -226,6 +226,57 @@ impl Yumush { .detach(); } + pub(super) fn jump_to( + &mut self, + community_id: String, + voice: bool, + window: &mut Window, + cx: &mut Context, + ) { + if let Some(community) = self + .chat + .communities() + .iter() + .find(|community| community.id == community_id) + .cloned() + { + self.enter(community, voice, window, cx); + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.read_community(&community_id).await { + Ok(community) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.enter(community, voice, window, cx) + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + fn enter( + &mut self, + community: Community, + voice: bool, + window: &mut Window, + cx: &mut Context, + ) { + let community_id = community.id.clone(); + if self.chat.joined(&community_id) { + let direct = matches!(community.kind, CommunityKind::Direct { .. }); + self.go_to_community(community_id.clone(), direct, window, cx); + } else { + self.open_builder_community(community, window, cx); + } + if voice && !self.chat.in_voice(&community_id) { + self.toggle_voice(community_id, window, cx); + } + } + pub(super) fn open_builder_community( &mut self, community: Community, @@ -295,19 +346,29 @@ impl Yumush { .flex() .items_center() .gap(px(8.)) - .child(avatar( - palette, - &member.user, - px(20.), - text(10.), - &self.chat.avatars, - )) .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(member.user.username.clone()), + div().flex_1().min_w_0().flex().child(user_link( + format!("transfer_user_{}", member.user.id), + Some(&member.user), + entity, + div() + .flex() + .items_center() + .gap(px(8.)) + .child(avatar( + palette, + &member.user, + px(20.), + text(10.), + &self.chat.avatars, + )) + .child( + div() + .min_w_0() + .truncate() + .child(member.user.username.clone()), + ), + )), ) .child(plain_button( format!("transfer_to_{}", member.user.id), diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index 676f993..0a0d5df 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -76,6 +76,9 @@ fn builder_log_text(entry: &AdminLogEntry) -> String { AdminAction::GhostVoice { seconds } => { format!("{actor} listened in {community} as ghost for {seconds}s") } + AdminAction::BackupCreated { name } => format!("{actor} created backup {name}"), + AdminAction::BackupDeleted { name } => format!("{actor} deleted backup {name}"), + AdminAction::BackupDownloaded { name } => format!("{actor} exported backup {name}"), } } @@ -146,6 +149,9 @@ fn action_icon(action: &AdminAction) -> IconName { | AdminAction::GhostDisabled | AdminAction::GhostVisit | AdminAction::GhostVoice { .. } => IconName::Eye, + AdminAction::BackupCreated { .. } + | AdminAction::BackupDeleted { .. } + | AdminAction::BackupDownloaded { .. } => IconName::HardDrive, } } diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs index 344d34c..736d349 100644 --- a/crates/client/src/gui/builder/messages.rs +++ b/crates/client/src/gui/builder/messages.rs @@ -11,13 +11,11 @@ use crate::gui::{ auth::field, avatar, community_settings::{search_text, user_name}, - entity_action, id_time, notify_error, text, + entity_action, id_time, notify_error, + profile::user_link, + text, }; -fn fixed(width: f32, control: impl IntoElement) -> Div { - div().w(px(width)).flex_shrink_0().child(control) -} - fn message_hit_row( hit: &MessageHit, pending: bool, @@ -27,6 +25,17 @@ fn message_hit_row( palette: Palette, ) -> Div { let message_id = hit.message.id.clone(); + let community_id = hit.message.community_id.clone(); + let open = icon_button( + format!("open_message_{}", hit.message.id), + IconName::MessageSquare, + "Open chat", + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.jump_to(community_id.clone(), false, window, cx) + }), + ); let delete = icon_button( format!("delete_message_{}", hit.message.id), IconName::Trash, @@ -43,7 +52,7 @@ fn message_hit_row( let purge = hit.author.as_ref().map(|author| { let user_id = author.id.clone(); icon_button( - format!("purge_message_user_{}", author.id), + format!("purge_message_user_{}", hit.message.id), IconName::UserX, if purge_pending { "Confirm purge" @@ -62,7 +71,12 @@ fn message_hit_row( }); list_row() - .child(picture) + .child(user_link( + format!("hit_picture_{}", hit.message.id), + hit.author.as_ref(), + entity, + picture, + )) .child( div() .flex_1() @@ -76,15 +90,17 @@ fn message_hit_row( .items_center() .gap(px(6.)) .min_w_0() - .child( + .child(user_link( + format!("hit_author_{}", hit.message.id), + hit.author.as_ref(), + entity, div() - .min_w_0() .truncate() .text_size(text(13.)) .font_weight(FontWeight::MEDIUM) .text_color(palette.text) .child(user_name(&hit.author).to_string()), - ) + )) .child( div() .min_w_0() @@ -115,6 +131,7 @@ fn message_hit_row( .items_center() .gap(px(4.)) .flex_shrink_0() + .child(open) .child(delete) .children(purge), ) @@ -139,15 +156,18 @@ impl Yumush { .child( div() .flex() + .flex_wrap() .items_center() .gap(px(8.)) - .child(fixed(180., field(palette, &self.chat.builder_message_user))) - .child(fixed( - 180., - field(palette, &self.chat.builder_message_community), - )) - .child(fixed(150., field(palette, &self.chat.builder_message_from))) - .child(fixed(150., field(palette, &self.chat.builder_message_to))) + .children( + [ + &self.chat.builder_message_user, + &self.chat.builder_message_community, + &self.chat.builder_message_from, + &self.chat.builder_message_to, + ] + .map(|input| div().flex_1().min_w(px(140.)).child(field(palette, input))), + ) .child(accent_button( "search_messages", "Search", diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index 377a380..09e7136 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -16,6 +16,7 @@ use crate::{ Palette, Yumush, avatar, badge, clickable, community_settings::user_name, entity_action, id_time, notify_error, + profile::user_link, settings_page::{segment, segment_track}, text, }, @@ -235,26 +236,37 @@ impl Yumush { .flex() .items_center() .gap(px(8.)) - .child(target_avatar) - .child( + .child(user_link( + format!("report_target_{}", report.id), + report.target.as_ref(), + entity, div() - .font_weight(FontWeight::MEDIUM) - .truncate() - .child(user_name(&report.target).to_string()), - ) + .flex() + .items_center() + .gap(px(8.)) + .child(target_avatar) + .child( + div() + .font_weight(FontWeight::MEDIUM) + .truncate() + .child(user_name(&report.target).to_string()), + ), + )) .child(pill( status_label(report.status), status_color(report.status, palette), palette, )) - .child( + .child(user_link( + format!("report_reporter_{}", report.id), + report.reporter.as_ref(), + entity, div() - .min_w_0() .text_size(text(11.)) .text_color(palette.muted) .truncate() .child(format!("reported by {}", user_name(&report.reporter))), - ); + )); let meta = div() .flex_shrink_0() .text_size(text(11.)) diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index 97d68b5..6b225e9 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -256,7 +256,11 @@ impl Yumush { .child(card_header("Attachments", vec![controls], palette)) .child(body); - vec![usage.into_any_element(), attachments.into_any_element()] + vec![ + usage.into_any_element(), + attachments.into_any_element(), + self.backups_card(entity, palette).into_any_element(), + ] } pub(super) fn load_storage(&self, window: &mut Window, cx: &mut Context) { @@ -264,6 +268,7 @@ impl Yumush { return; } self.search_attachments(window, cx); + self.load_backups(window, cx); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs index ac57e8a..37bea0e 100644 --- a/crates/client/src/gui/builder/ui.rs +++ b/crates/client/src/gui/builder/ui.rs @@ -53,6 +53,95 @@ pub(super) fn icon_button( .child(Icon::new(icon).w(px(14.)).h(px(14.))) } +pub(super) fn action_button( + id: String, + icon: IconName, + label: &'static str, + tip: &'static str, + color: Hsla, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + clickable(id, palette, action) + .tip(tip) + .h(px(28.)) + .px(px(10.)) + .flex() + .items_center() + .gap(px(6.)) + .rounded(px(6.)) + .text_size(text(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(color) + .child(Icon::new(icon).w(px(14.)).h(px(14.))) + .child(label) +} + +pub(super) fn confirm_button( + id: String, + icon: IconName, + label: &'static str, + tip: &'static str, + pending: bool, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + action_button( + id, + icon, + if pending { "Confirm" } else { label }, + if pending { + "Click again to confirm" + } else { + tip + }, + palette.danger, + palette, + action, + ) + .when(pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) +} + +pub(super) fn action_group( + title: &'static str, + palette: Palette, + children: Vec, +) -> Option
{ + if children.is_empty() { + return None; + } + + Some( + div() + .flex() + .items_start() + .gap(px(12.)) + .child( + div() + .w(px(88.)) + .h(px(28.)) + .flex_shrink_0() + .flex() + .items_center() + .text_size(text(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.muted) + .child(title), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(4.)) + .child(div().flex().flex_wrap().gap(px(4.)).children(children)), + ), + ) +} + pub(super) fn danger_button( id: String, label: &'static str, diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 4de01e6..7589661 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -15,11 +15,14 @@ use gpui_kit::{ px, }; -use super::ui::{accent_button, card, danger_button, pill, plain_button}; +use super::ui::{ + accent_button, action_button, action_group, card, confirm_button, pill, plain_button, +}; use crate::{ gui::{ DATE, DAY, Palette, Tooltip as _, Yumush, auth::field, avatar, clickable, - community_settings::search_text, entity_action, id_time, millis_time, notify_error, text, + community_settings::search_text, entity_action, id_time, millis_time, notify_error, + profile::user_link, text, }, network::NetworkHandle, }; @@ -45,10 +48,6 @@ fn status(label: &str, color: gpui_kit::Hsla, palette: Palette) -> Div { div().flex_shrink_0().child(pill(label, color, palette)) } -fn divider(palette: Palette) -> Div { - div().w(px(1.)).h(px(16.)).mx(px(4.)).bg(palette.border) -} - impl Yumush { pub(super) fn submit_new_user(&mut self, window: &mut Window, cx: &mut Context) { let username = self.chat.new_username.read(cx).text().to_string(); @@ -419,6 +418,7 @@ impl Yumush { .px(px(14.)) .py(px(10.)) .flex() + .flex_wrap() .items_center() .gap(px(8.)) .border_b_1() @@ -426,19 +426,19 @@ impl Yumush { .child( div() .flex_1() - .min_w_0() + .min_w(px(160.)) .child(Input::new(&self.chat.builder_search)), ) .child( div() - .w(px(160.)) - .flex_shrink_0() + .flex_1() + .min_w(px(120.)) .child(field(palette, &self.chat.new_username)), ) .child( div() - .w(px(160.)) - .flex_shrink_0() + .flex_1() + .min_w(px(120.)) .child(field(palette, &self.chat.new_password)), ) .child(accent_button( @@ -549,9 +549,12 @@ impl Yumush { ) -> Div { let revoke_user_id = user_id.to_string(); let session_id = session.id.clone(); - let revoke_button = plain_button( + let revoke_button = action_button( format!("revoke_session_{}", session.id), + IconName::LogOut, "Revoke", + "End this session", + palette.muted, palette, entity_action(entity, move |yumush, window, cx| { yumush.revoke_builder_session(&revoke_user_id, &session_id, window, cx) @@ -564,15 +567,21 @@ impl Yumush { }; div() - .h(px(36.)) - .pl(px(40.)) - .pr(px(12.)) + .w_full() + .h(px(28.)) .flex() .items_center() .gap(px(8.)) + .child( + Icon::new(IconName::Monitor) + .w(px(14.)) + .h(px(14.)) + .text_color(palette.muted), + ) .child( div() .flex_1() + .text_size(text(12.)) .min_w_0() .truncate() .child(device.to_string()), @@ -685,40 +694,65 @@ impl Yumush { let seen = seen_text(account.last_seen); let next_role = if builder { Role::User } else { Role::Builder }; - let role_button = plain_button( + let tone = palette.text; + let role_button = action_button( format!("role_{}", user.id), + if builder { + IconName::ShieldOff + } else { + IconName::Shield + }, if builder { "Remove builder" } else { "Make builder" }, + if builder { + "Revoke admin tools" + } else { + "Grant admin tools" + }, + tone, palette, entity_action(entity, move |yumush, window, cx| { yumush.set_builder_role(&role_id, next_role, window, cx) }), ); - let suspend_button = plain_button( + let suspend_button = action_button( format!("suspend_user_{}", user.id), + IconName::CirclePause, if suspended { "Unsuspend" } else { "Suspend" }, + if suspended { + "Allow sign in again" + } else { + "Block sign in until lifted" + }, + tone, palette, entity_action(entity, move |yumush, window, cx| { yumush.suspend_builder_user(&suspend_id, !suspended, window, cx) }), ); - let sessions_button = plain_button( + let sessions_button = action_button( format!("sessions_user_{}", user.id), + IconName::LogOut, "Sign out", + "End every session", + tone, palette, entity_action(entity, move |yumush, window, cx| { yumush.revoke_builder_sessions(&sessions_id, window, cx) }), ); - let password_button = plain_button( + let password_button = action_button( format!("password_user_{}", user.id), - "Reset password", + IconName::KeyRound, + "Password", + "Set a new password", + tone, palette, entity_action(entity, move |yumush, _, cx| { yumush.toggle_builder_password(&password_id, cx) @@ -732,7 +766,7 @@ impl Yumush { yumush.toggle_builder_sessions(&sessions_list_id, window, cx) }), ) - .tip("Actions") + .tip("Manage") .size(px(28.)) .flex_shrink_0() .flex() @@ -743,45 +777,59 @@ impl Yumush { .when(expanded, |this| this.bg(palette.hover)) .child(Icon::new(IconName::Ellipsis).w(px(16.)).h(px(16.))); - let rename_button = plain_button( + let rename_button = action_button( format!("rename_user_{}", user.id), + IconName::Pencil, "Rename", + "Change username", + tone, palette, entity_action(entity, move |yumush, _, cx| { yumush.toggle_builder_rename(&rename_id, cx) }), ); - let timeout_button = plain_button( + let timeout_button = action_button( format!("timeout_user_{}", user.id), + IconName::Timer, "Timeout", + "Block sign in for a while", + tone, palette, entity_action(entity, move |yumush, _, cx| { yumush.toggle_builder_timeout(&timeout_id, cx) }), ); - let ban_button = plain_button( + let ban_button = action_button( format!("ban_user_{}", user.id), + IconName::Ban, "Ban", + "Ban username or IP from the server", + tone, palette, entity_action(entity, move |yumush, _, cx| { yumush.toggle_builder_ban(&ban_id, cx) }), ); - let profile_button = plain_button( + let profile_button = action_button( format!("profile_user_{}", user.id), + IconName::Eraser, "Clear profile", + "Remove avatar and status", + palette.danger, palette, entity_action(entity, move |yumush, window, cx| { yumush.clear_builder_profile(&profile_id, window, cx) }), ); - let purge_button = danger_button( + let purge_button = confirm_button( format!("purge_user_{}", user.id), + IconName::MessageSquareX, "Purge", + "Delete all their messages", pending_purge, palette, entity_action(entity, move |yumush, window, cx| { @@ -789,9 +837,11 @@ impl Yumush { }), ); - let delete_button = danger_button( + let delete_button = confirm_button( format!("delete_user_{}", user.id), + IconName::UserX, "Delete", + "Delete the account", pending_delete, palette, entity_action(entity, move |yumush, window, cx| { @@ -805,12 +855,11 @@ impl Yumush { .flex() .items_center() .gap(px(10.)) - .child(avatar( - palette, - user, - px(28.), - text(11.), - &self.chat.avatars, + .child(user_link( + format!("builder_user_avatar_{}", user.id), + Some(user), + entity, + avatar(palette, user, px(28.), text(11.), &self.chat.avatars), )) .child( div() @@ -825,15 +874,17 @@ impl Yumush { .flex() .items_center() .gap(px(6.)) - .child( + .child(user_link( + format!("builder_user_name_{}", user.id), + Some(user), + entity, div() - .min_w_0() .truncate() .text_size(text(13.)) .font_weight(FontWeight::MEDIUM) .text_color(palette.text) .child(user.username.clone()), - ) + )) .when(builder, |this| { this.child(status("Builder", palette.accent, palette)) }) @@ -865,46 +916,61 @@ impl Yumush { let timeout_open = self.chat.pending_builder_timeout.as_deref() == Some(open_id); let ban_open = self.chat.pending_builder_ban.as_deref() == Some(open_id); - let actions = div() - .px(px(14.)) - .flex() - .flex_wrap() - .items_center() - .gap(px(6.)) - .children(manage.then_some(rename_button)) - .children(manage.then_some(password_button)) - .children(can_role.then_some(role_button)) - .children(manage.then(|| divider(palette))) - .children(manage.then_some(timeout_button)) - .children(manage.then_some(suspend_button)) - .children(manage.then_some(ban_button)) - .children(manage.then_some(sessions_button)) - .children(manage.then(|| divider(palette))) - .children(manage.then_some(profile_button)) - .children(manage.then_some(purge_button)) - .children(can_delete.then_some(delete_button)); + let account_actions = [ + manage.then(|| rename_button.into_any_element()), + manage.then(|| password_button.into_any_element()), + can_role.then(|| role_button.into_any_element()), + ]; + let moderation_actions = [ + manage.then(|| timeout_button.into_any_element()), + manage.then(|| suspend_button.into_any_element()), + manage.then(|| ban_button.into_any_element()), + manage.then(|| sessions_button.into_any_element()), + ]; + let danger_actions = [ + manage.then(|| profile_button.into_any_element()), + manage.then(|| purge_button.into_any_element()), + can_delete.then(|| delete_button.into_any_element()), + ]; + let sessions: Vec = sessions + .iter() + .map(|session| { + self.builder_session_row(&user.id, session, entity, palette) + .into_any_element() + }) + .collect(); div() .flex() .flex_col() - .gap(px(6.)) - .pt(px(4.)) - .pb(px(10.)) + .gap(px(8.)) + .px(px(14.)) + .py(px(10.)) .bg(palette.window) .border_t_1() .border_color(palette.border) - .child(actions) + .children(action_group( + "Account", + palette, + account_actions.into_iter().flatten().collect(), + )) .children( password_open.then(|| self.builder_password_row(&user.id, entity, palette)), ) .children(rename_open.then(|| self.builder_rename_row(&user.id, entity, palette))) + .children(action_group( + "Moderation", + palette, + moderation_actions.into_iter().flatten().collect(), + )) .children(timeout_open.then(|| self.builder_timeout_row(&user.id, entity, palette))) .children(ban_open.then(|| self.builder_ban_row(&user.id, entity, palette))) - .children( - sessions.iter().map(|session| { - self.builder_session_row(&user.id, session, entity, palette) - }), - ) + .children(action_group( + "Danger", + palette, + danger_actions.into_iter().flatten().collect(), + )) + .children(action_group("Sessions", palette, sessions)) }); div().flex().flex_col().child(row).children(panel) diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs index badc3e3..28c1ea4 100644 --- a/crates/client/src/gui/builder/voice.rs +++ b/crates/client/src/gui/builder/voice.rs @@ -11,7 +11,7 @@ use gpui_kit::{ use super::ui::{card, card_header, icon_button, list_card, pill}; use crate::{ - gui::{Palette, Yumush, avatar, entity_action, notify_error, text}, + gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text}, network::NetworkHandle, }; @@ -134,8 +134,25 @@ impl Yumush { .find(|summary| summary.community.id == id) .map(|summary| summary.community.voice_enabled); + let joined = self.chat.in_voice(&id); + let join_id = id.clone(); let mut actions = vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()]; + if !joined { + actions.push( + icon_button( + format!("room_join_{id}"), + IconName::Headphones, + "Join", + palette.ok, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.jump_to(join_id.clone(), true, window, cx) + }), + ) + .into_any_element(), + ); + } if let Some(enabled) = voice { actions.push( icon_button( @@ -194,21 +211,31 @@ impl Yumush { .flex() .items_center() .gap(px(10.)) - .child(avatar( - palette, - user, - px(24.), - text(10.), - &self.chat.avatars, - )) .child( - div() - .flex_1() - .min_w_0() - .truncate() - .text_size(text(13.)) - .text_color(palette.text) - .child(user.username.clone()), + div().flex_1().min_w_0().flex().child(user_link( + format!("voice_user_{id}"), + Some(user), + entity, + div() + .flex() + .items_center() + .gap(px(10.)) + .child(avatar( + palette, + user, + px(24.), + text(10.), + &self.chat.avatars, + )) + .child( + div() + .min_w_0() + .truncate() + .text_size(text(13.)) + .text_color(palette.text) + .child(user.username.clone()), + ), + )), ) .children(muted.then(|| pill("Muted", palette.danger, palette))) .children(ghost.then(|| pill("Ghost", palette.muted, palette))) diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 22083da..ff96209 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,34 +1,37 @@ use super::text; use crate::gui::CLOCK; use std::{ - collections::{HashMap, HashSet}, + collections::{HashMap, HashSet, VecDeque}, sync::Arc, - time::Duration, + time::{Duration, Instant}, }; use crate::gui::social::InviteLookup; +use crate::gui::voice_stats::SAMPLE_HISTORY; use crate::gui::{ FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, builder::{BuilderTab, Transfer}, - clickable, community_icon, community_name, - community_settings::{BanSort, LogSort}, + clickable, community_name, + community_settings::{BanSort, LogSort, search_text}, composer::{self, Composer}, entity_action, hoverable, id_time, media_view::{self, Media}, - message_actions, new_input, notify_error, palette, primary_button, + message_actions, new_input, notify_error, palette, poll, pop_in, presence_avatar, + primary_button, profile::profile_popover, rank_tag, sidebar::SidebarTab, snippet, + voice_note::{self, VoiceNote}, }; use common::{ constant::MESSAGE_PAGE_LIMIT, event::Event, model::{ - ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, Community, CommunityKind, - CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, - Member, Message, MessageHit, Overview, Rank, Report, ReportStatus, ServerBan, SessionInfo, - Usage, User, VoiceRoom, + ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, CallLog, Community, + CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, + LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, + ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, }, permission, }; @@ -96,6 +99,13 @@ pub enum ReportTarget { User(String), } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CardMenu { + Main, + Accounts, + Presence, +} + pub struct Chat { pub(super) communities: Vec, pub(super) selected_community_id: Option, @@ -103,15 +113,29 @@ pub struct Chat { pub(super) ghost: bool, members: Vec, pub(super) messages: Vec, + pub(super) pins: Vec, history: History, - pub(super) unread: HashSet, + pub(super) unread: HashMap, + pub(super) unread_anchor: Option<(String, u32)>, + unseen: u32, + pub(super) muted: HashSet, pub(super) message_input: Entity, pub(super) search_input: Entity, + pub(super) community_search: Entity, + pub(super) community_hits: Vec, pub(super) found: Option, pub(super) invite: InviteLookup, pub(super) tab: SidebarTab, + pub(super) sidebar_collapsed: bool, pub(super) composer: Composer, + pub(super) drafts: HashMap, + pub(super) poll_question: Entity, + pub(super) poll_options: Vec>, + pub(super) poll_multiple: bool, + pub(super) poll_expanded: bool, scroll: ScrollHandle, + pub(super) jump: Option, + highlight: Option<(String, Instant)>, pub(super) view: View, pub(super) username_input: Entity, pub(super) community_name_input: Entity, @@ -131,6 +155,9 @@ pub struct Chat { pub(super) friends: Friends, pub(super) invitations: Vec, pub(super) pending_user_delete: Option, + pub(super) card_menu: CardMenu, + pub(super) presences: HashMap, + pub(super) slowed_until: Option, pub(super) pending_builder_delete: Option, pub(super) builder_users: Vec, pub(super) pending_builder_password: Option, @@ -202,17 +229,34 @@ pub struct Chat { pub(super) server_muted: HashSet, pub(super) builder_voice_rooms: Vec, pub(super) voice_task: Option>, + pub(super) voice_samples: VecDeque, + pub(super) ringing: HashSet, + pub(super) ring_task: Option>, pub(super) media: Media, + pub(super) typing: HashMap>, + pub(super) typing_sent: HashMap, } +const RING_LIMIT: usize = 15; +const RING_INTERVAL: Duration = Duration::from_secs(2); +const VOICE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1); +const DELETE_CONFIRM: Duration = Duration::from_secs(3); +pub const TYPING_SEND_INTERVAL: Duration = Duration::from_secs(3); +pub const TYPING_TTL: Duration = Duration::from_secs(5); +const HIGHLIGHT_TTL: Duration = Duration::from_secs(2); + impl Chat { pub fn new(window: &mut Window, cx: &mut Context) -> Self { let message_input = new_input("Message", window, cx); - cx.subscribe_in(&message_input, window, |this, input, event, window, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - this.submit_composer(input, window, cx); - } - }) + cx.subscribe_in( + &message_input, + window, + |this, input, event, window, cx| match event { + InputEvent::PressEnter { .. } => this.submit_composer(input, window, cx), + InputEvent::Change => this.send_typing(cx), + _ => {} + }, + ) .detach(); let username_input = editable_input("Username...", Yumush::save_username, window, cx); @@ -232,6 +276,14 @@ impl Chat { ) .detach(); + let community_search = new_input("Search messages", window, cx); + cx.subscribe_in(&community_search, window, |this, _, event, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + this.search_community(window, cx); + } + }) + .detach(); + let ban_search = new_input("Search...", window, cx); let log_search = new_input("Search...", window, cx); let builder_search = new_input("Search...", window, cx); @@ -306,14 +358,30 @@ impl Chat { friends: Friends::default(), invitations: vec![], messages: vec![], + pins: vec![], + poll_question: new_input("Question", window, cx), + poll_options: vec![ + new_input("Option", window, cx), + new_input("Option", window, cx), + ], + poll_multiple: false, + poll_expanded: false, history: History::End, scroll: ScrollHandle::new(), - unread: HashSet::new(), + jump: None, + highlight: None, + unread: HashMap::new(), + unread_anchor: None, + unseen: 0, + muted: HashSet::new(), message_input, search_input, + community_search, + community_hits: vec![], found: None, invite: InviteLookup::Idle, tab: SidebarTab::Communities, + sidebar_collapsed: false, view: View::Chat, username_input, community_name_input, @@ -325,6 +393,9 @@ impl Chat { user_requests: HashSet::new(), delete_step: DeleteStep::Idle, pending_user_delete: None, + card_menu: CardMenu::Main, + presences: HashMap::new(), + slowed_until: None, pending_builder_delete: None, builder_users: vec![], builder_tab: BuilderTab::Overview, @@ -391,21 +462,35 @@ impl Chat { report: None, report_reason, voice: HashMap::new(), + drafts: HashMap::new(), voice_state: VoiceState::Off, speaking: HashSet::new(), server_muted: HashSet::new(), builder_voice_rooms: Vec::new(), voice_task: None, + voice_samples: VecDeque::new(), + ringing: HashSet::new(), + ring_task: None, + typing: HashMap::new(), + typing_sent: HashMap::new(), media: Media::default(), composer: Composer::Compose { reply: None }, } } - pub(super) fn has_unread(&self, direct: bool) -> bool { - self.communities.iter().any(|community| { - self.unread.contains(&community.id) - && matches!(community.kind, CommunityKind::Direct { .. }) == direct - }) + pub(super) fn unread_total(&self, group: bool) -> Unread { + self.communities + .iter() + .filter(|community| { + !self.muted.contains(&community.id) + && matches!(community.kind, CommunityKind::Group) == group + }) + .filter_map(|community| self.unread.get(&community.id)) + .fold(Unread::default(), |total, unread| Unread { + messages: total.messages + unread.messages, + mentions: total.mentions + unread.mentions, + ..total + }) } pub fn focus(&self, window: &mut Window, cx: &mut Context) { @@ -422,18 +507,25 @@ impl Chat { .update(cx, |input, cx| input.focus(window, cx)); } - pub fn apply_event(&mut self, event: Event) { + pub fn slow_seconds(&self) -> Option { + let remaining = self.slowed_until?.saturating_sub(common::time::now_ms()); + (remaining > 0).then(|| remaining.div_ceil(1000)) + } + + pub fn apply_event(&mut self, event: Event, me: Option<&str>) { match event { Event::MessageCreated(message) => { + if let Some(users) = self.typing.get_mut(&message.community_id) { + users.remove(&message.user_id); + } if self.is_selected(&message.community_id) { - self.insert_messages([message]); - } else { - self.unread.insert(message.community_id); + self.insert_messages([message], me); } } Event::MessageUpdated(message) => { if self.is_selected(&message.community_id) { - self.insert_messages([message]); + self.update_pin(&message); + self.insert_messages([message], me); } } Event::MessageDeleted(message) => { @@ -479,6 +571,9 @@ impl Chat { self.messages.retain(|message| message.user_id != user_id); } Event::UserUpdated(user) => self.update_member(&user), + Event::PresenceChanged { user_id, presence } => { + self.presences.insert(user_id, presence); + } Event::VoiceJoined { community_id, user_id, @@ -494,6 +589,9 @@ impl Chat { } => { if let Some(ids) = self.voice.get_mut(&community_id) { ids.retain(|id| *id != user_id); + if ids.is_empty() { + self.ringing.remove(&community_id); + } } } Event::VoiceMuted { user_id, muted } => { @@ -503,6 +601,15 @@ impl Chat { self.server_muted.remove(&user_id); } } + Event::Typing { + community_id, + user_id, + } => { + self.typing + .entry(community_id) + .or_default() + .insert(user_id, Instant::now()); + } Event::ReportCreated | Event::Announcement { .. } => {} } } @@ -511,9 +618,38 @@ impl Chat { self.selected_community_id.as_deref() == Some(community_id) } + pub fn typing_label(&self) -> Option { + let community_id = self.selected_community_id.as_ref()?; + let names: Vec<&str> = self + .typing + .get(community_id)? + .iter() + .filter(|(_, at)| at.elapsed() < TYPING_TTL) + .map(|(user_id, _)| { + self.author(user_id) + .map_or("Someone", |user| user.username.as_str()) + }) + .collect(); + match names.as_slice() { + [] => None, + [name] => Some(format!("{name} is typing…")), + names => Some(format!("{} people are typing…", names.len())), + } + } + fn select(&mut self, community_id: Option) { - if let Some(community_id) = &community_id { - self.unread.remove(community_id); + if community_id != self.selected_community_id { + self.unread_anchor = community_id + .as_ref() + .and_then(|community_id| self.unread.get(community_id)) + .filter(|unread| unread.messages > 0) + .and_then(|unread| { + unread + .last_read + .clone() + .map(|last_read| (last_read, unread.messages)) + }); + self.unseen = 0; } if self.opened.as_ref().map(|opened| &opened.id) != community_id.as_ref() { self.opened = None; @@ -528,12 +664,16 @@ impl Chat { self.logs.clear(); self.pending_user_delete = None; self.messages.clear(); + self.jump = None; + self.pins.clear(); + self.poll_expanded = false; + self.community_hits.clear(); self.history = History::End; self.media.leave(); self.composer = Composer::Compose { reply: None }; } - fn joined(&self, community_id: &str) -> bool { + pub fn joined(&self, community_id: &str) -> bool { self.communities .iter() .any(|community| community.id == community_id) @@ -559,7 +699,13 @@ impl Chat { &self.communities } - fn insert_messages(&mut self, messages: impl IntoIterator) { + pub fn notes(&self) -> Option<&Community> { + self.communities + .iter() + .find(|community| matches!(community.kind, CommunityKind::Notes)) + } + + fn insert_messages(&mut self, messages: impl IntoIterator, me: Option<&str>) { let newest = self.messages.last().map(|message| message.id.clone()); for message in messages { self.messages.retain(|existing| existing.id != message.id); @@ -567,13 +713,96 @@ impl Chat { } self.messages.sort_by(|left, right| left.id.cmp(&right.id)); if self.messages.last().map(|message| &message.id) != newest.as_ref() { - self.scroll.scroll_to_bottom(); + let mine = self + .messages + .last() + .is_some_and(|message| Some(message.user_id.as_str()) == me); + if newest.is_none() { + match self.unread_divider(me) { + Some(index) => self.scroll_to_index(index), + None => self.scroll.scroll_to_bottom(), + } + } else if mine || !self.away() { + self.jump_to_bottom(); + } else { + self.unseen += 1; + } } + self.reveal_jump(); } - fn add_page(&mut self, page: Vec) { + fn reveal_jump(&mut self) { + let Some(message_id) = self.jump.as_ref() else { + return; + }; + let Some(position) = self + .messages + .iter() + .position(|message| &message.id == message_id) + else { + return; + }; + self.scroll_to_index(position); + self.highlight = self + .jump + .take() + .map(|message_id| (message_id, Instant::now())); + } + + fn scroll_to_index(&self, position: usize) { + let spacer = 1; + let older = usize::from(self.history == History::More); + self.scroll.scroll_to_item(spacer + older + position); + } + + fn away(&self) -> bool { + self.scroll.max_offset().y + self.scroll.offset().y > self.scroll.bounds().size.height + } + + pub(super) fn jump_to_bottom(&mut self) { + self.scroll.scroll_to_bottom(); + self.unseen = 0; + } + + pub(super) fn settle_scroll(&mut self) { + if !self.away() { + self.unseen = 0; + } + } + + fn unread_covered(&self) -> bool { + match (&self.unread_anchor, self.messages.first()) { + (Some((anchor, _)), Some(first)) => self.history == History::End || first.id <= *anchor, + _ => true, + } + } + + fn unread_divider(&self, me: Option<&str>) -> Option { + let (anchor, _) = self.unread_anchor.as_ref()?; + if !self.unread_covered() { + return None; + } + self.messages + .iter() + .position(|message| message.id > *anchor && Some(message.user_id.as_str()) != me) + } + + pub(super) fn mark_read(&mut self, community_id: &str, message_id: &str) { + let unread = self + .unread + .entry(community_id.to_string()) + .or_insert_with(|| Unread { + community_id: community_id.to_string(), + ..Default::default() + }); + unread.messages = 0; + unread.mentions = 0; + unread.last_read = Some(message_id.to_string()); + } + + fn add_page(&mut self, page: Vec, me: Option<&str>) { self.history = History::of_page(page.len()); - self.insert_messages(page); + self.insert_messages(page, me); } fn insert_member(&mut self, member: Member) { @@ -659,6 +888,21 @@ impl Chat { self.member(user_id).and_then(|user| self.rank_of(user)) } + pub fn can_pin(&self, me: &User) -> bool { + let direct = self + .selected_community() + .is_some_and(|community| matches!(community.kind, CommunityKind::Direct { .. })); + permission::can_pin(self.my_rank(me), direct) + } + + fn update_pin(&mut self, message: &Message) { + self.pins.retain(|pin| pin.id != message.id); + if message.pinned { + self.pins.push(message.clone()); + self.pins.sort_by(|left, right| right.id.cmp(&left.id)); + } + } + pub fn can_delete(&self, message: &Message, me: &User) -> bool { permission::can_delete_message( self.my_rank(me), @@ -681,7 +925,7 @@ impl Chat { .iter_mut() .filter_map(|community| match &mut community.kind { CommunityKind::Direct { peer } => Some(peer), - CommunityKind::Group => None, + CommunityKind::Group | CommunityKind::Notes => None, }); let known = self .friends @@ -739,11 +983,14 @@ impl Chat { pub fn reset(&mut self) { self.communities.clear(); + self.presences.clear(); + self.slowed_until = None; self.friends = Friends::default(); self.invitations.clear(); self.found = None; self.select(None); self.unread.clear(); + self.muted.clear(); self.builder_users.clear(); self.builder_tab = BuilderTab::Overview; self.builder_overview = None; @@ -778,6 +1025,8 @@ impl Chat { self.voice.clear(); self.server_muted.clear(); self.builder_voice_rooms.clear(); + self.ringing.clear(); + self.ring_task = None; self.set_voice_off(); } @@ -788,6 +1037,14 @@ impl Chat { } } + pub fn voice_room(&self) -> Option<&Community> { + let community_id = self.voice_community()?; + self.communities + .iter() + .chain(self.opened.as_ref()) + .find(|community| community.id == community_id) + } + pub fn in_voice(&self, community_id: &str) -> bool { self.voice_community() == Some(community_id) } @@ -819,6 +1076,7 @@ impl Chat { self.voice_state = VoiceState::Off; self.speaking.clear(); self.voice_task = None; + self.voice_samples.clear(); } } @@ -947,6 +1205,7 @@ impl Yumush { .bg(palette.panel) .overflow_hidden() .children(self.announcement_banner(entity, palette)) + .children(self.call_banner(entity, palette)) .map(|panel| match self.chat.view { View::Settings => panel.child(self.settings_page(entity, palette, cx)), View::Builder => panel.child(self.builder_page(entity, palette, cx)), @@ -956,7 +1215,9 @@ impl Yumush { View::Chat => match self.chat.selected_community_id { Some(_) => panel .child(self.header(entity, themed)) - .child(self.message_list(entity, themed)) + .children(self.unread_bar(entity, themed)) + .children(self.poll_banner(entity, themed)) + .child(self.message_area(entity, themed)) .child(self.composer(entity, themed)), None => panel.child(empty_state(palette)), }, @@ -1003,9 +1264,10 @@ impl Yumush { .gap(px(8.)) .border_b_2() .border_color(palette.accent) - .children(community.map(|community| { - community_icon(palette, community, px(20.), text(10.), &self.chat.avatars) - })) + .children( + community + .map(|community| self.community_badge(community, px(20.), text(10.), palette)), + ) .child( div() .font_weight(FontWeight::SEMIBOLD) @@ -1018,11 +1280,124 @@ impl Yumush { .then(|| self.voice_stack(entity, palette)) .flatten(), ) + .children(self.calling_hint(palette)) .children(self.voice_button(entity, palette)) - .children(group.then(|| members_popover(entity, &self.chat, palette))) + .children( + community + .is_some_and(|community| self.chat.joined(&community.id)) + .then(|| message_actions::search_popover(&self.chat, entity, palette)), + ) + .children( + (community.is_some() && !self.chat.pins.is_empty()) + .then(|| message_actions::pins_popover(&self.chat, entity, palette)), + ) + .children(group.then(|| members_popover(entity, self, palette))) + } + + fn message_area(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .relative() + .child(self.message_list(entity, palette)) + .children(self.jump_bottom(entity, palette)) + } + + fn unread_bar(&self, entity: &Entity, palette: Palette) -> Option { + let (anchor, count) = self.chat.unread_anchor.clone()?; + if self.chat.unread_covered() { + return None; + } + Some( + div() + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .px(px(12.)) + .py(px(6.)) + .bg(palette.accent) + .text_color(palette.on_accent) + .child(format!("{count} new messages")) + .child( + div() + .flex() + .gap(px(8.)) + .child( + clickable( + "jump_unread", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.go_to_message(anchor.clone(), window, cx) + }), + ) + .child("↑"), + ) + .child( + clickable( + "dismiss_unread", + palette, + entity_action(entity, |yumush, _, cx| { + yumush.chat.unread_anchor = None; + cx.notify(); + }), + ) + .child("×"), + ), + ), + ) + } + + fn jump_bottom(&self, entity: &Entity, palette: Palette) -> Option { + if !self.chat.away() { + return None; + } + let unseen = self.chat.unseen; + Some( + clickable( + "jump_bottom", + palette, + entity_action(entity, |yumush, _, cx| { + yumush.chat.jump_to_bottom(); + cx.notify(); + }), + ) + .absolute() + .right(px(16.)) + .bottom(px(12.)) + .size(px(36.)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child(Icon::new(IconName::ArrowDown).w(px(16.)).h(px(16.))) + .children((unseen > 0).then(|| { + div() + .absolute() + .top(px(-6.)) + .right(px(-6.)) + .children(super::sidebar::badge( + palette, + false, + Some(&Unread { + messages: unseen, + ..Default::default() + }), + )) + })), + ) } fn message_list(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + let divider = self + .chat + .unread_divider(self.user.as_ref().map(|user| user.id.as_str())); + let entity_scroll = entity.clone(); div() .id("chat_messages") .track_scroll(&self.chat.scroll) @@ -1034,6 +1409,15 @@ impl Yumush { .px(px(24.)) .py(px(20.)) .gap(px(2.)) + .on_scroll(move |_, window, _| { + let entity = entity_scroll.clone(); + window.on_next_frame(move |_, cx| { + entity.update(cx, |yumush, cx| { + yumush.chat.settle_scroll(); + cx.notify(); + }) + }); + }) .child(div().flex_1()) .children((self.chat.history == History::More).then(|| older_button(entity, palette))) .children( @@ -1041,10 +1425,12 @@ impl Yumush { .messages .iter() .enumerate() - .map(|(index, message)| { + .flat_map(|(index, message)| { let first = index == 0 || self.chat.messages[index - 1].user_id != message.user_id; - render_message( + let divider = (divider == Some(index)) + .then(|| new_divider(palette).into_any_element()); + divider.into_iter().chain([render_message( message, first, index > 0, @@ -1052,7 +1438,7 @@ impl Yumush { self.user.as_ref(), entity, palette, - ) + )]) }), ) } @@ -1071,10 +1457,30 @@ impl Yumush { let bar = composer::mode_bar(&self.chat, entity, palette); let entity = entity.clone(); - div() - .p(px(16.)) + if let VoiceNote::Recording { + started, levels, .. + } = &self.chat.media.voice_note + { + return div() + .p(px(16.)) + .children(pending) + .child(voice_note::recording_row( + *started, levels, &entity, palette, + )) + .into_any_element(); + } + + composer::format_actions(&self.chat.message_input, div().p(px(16.))) .children(pending) .children(bar) + .children(self.chat.typing_label().map(|label| { + div() + .pl(px(4.)) + .pb(px(4.)) + .text_size(text(12.)) + .text_color(palette.muted) + .child(label) + })) .child( div() .min_h(px(40.)) @@ -1101,6 +1507,8 @@ impl Yumush { .text_color(palette.muted) .child(Icon::new(IconName::Plus).w(px(16.)).h(px(16.))), ) + .child(composer::format_popover(palette)) + .child(composer::poll_popover(&self.chat, &entity, palette)) .child( Input::new(&self.chat.message_input) .appearance(false) @@ -1108,6 +1516,7 @@ impl Yumush { .flex_1() .min_w_0(), ) + .child(voice_note::mic_button(&entity, palette)) .child( primary_button("send_button", palette, move |window, cx| { entity @@ -1132,9 +1541,12 @@ impl Yumush { cx: &mut Context, ) { self.stop_playing(cx); - self.chat.select(Some(community_id)); + self.save_draft(cx); + self.chat.select(Some(community_id.clone())); + self.restore_draft(&community_id, window, cx); self.chat.focus(window, cx); self.load_members(window, cx); + self.load_pins(window, cx); self.load_voice(window, cx); self.load_latest_messages(window, cx); cx.notify(); @@ -1173,8 +1585,13 @@ impl Yumush { return; } }; + let unreads = network.unreads().await.unwrap_or_default(); let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.unread = unreads + .into_iter() + .map(|unread| (unread.community_id.clone(), unread)) + .collect(); yumush.chat.replace_communities(communities); yumush.request_social_avatars(cx); @@ -1194,6 +1611,60 @@ impl Yumush { .detach(); } + fn search_community(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let text = search_text(&self.chat.community_search, cx); + if text.is_empty() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let hits = match network.search_community(community_id.clone(), text).await { + Ok(hits) => hits, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + if yumush.chat.is_selected(&community_id) { + yumush.chat.community_hits = hits; + cx.notify(); + } + }); + }) + .detach(); + } + + fn load_pins(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let pins = match network.pins(&community_id).await { + Ok(pins) => pins, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + if yumush.chat.is_selected(&community_id) { + yumush.chat.pins = pins; + cx.notify(); + } + }); + }) + .detach(); + } + fn load_members(&self, window: &mut Window, cx: &mut Context) { let Some(community_id) = self.chat.selected_community_id.clone() else { return; @@ -1216,7 +1687,7 @@ impl Yumush { } yumush.chat.members = members; yumush.load_bans(window, cx); - yumush.request_authors(window, cx); + yumush.request_authors(cx); cx.notify(); } }); @@ -1224,7 +1695,7 @@ impl Yumush { .detach(); } - fn request_authors(&mut self, window: &mut Window, cx: &mut Context) { + pub(super) fn request_authors(&mut self, cx: &mut Context) { let missing = self.chat.missing_authors(); if missing.is_empty() { return; @@ -1232,7 +1703,7 @@ impl Yumush { self.chat.user_requests.extend(missing.iter().cloned()); let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { + cx.spawn(async move |this, cx| { for user_id in missing { let Ok(user) = network.read_user(&user_id).await else { continue; @@ -1278,6 +1749,32 @@ impl Yumush { .detach(); } + pub(super) fn go_to_message( + &mut self, + message_id: String, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.jump = Some(message_id); + self.chat.reveal_jump(); + if self.chat.jump.is_none() { + Self::fade_highlight(cx); + } else if self.chat.history == History::More { + self.load_older_messages(window, cx); + } else { + self.chat.jump = None; + } + cx.notify(); + } + + fn fade_highlight(cx: &mut Context) { + cx.spawn(async move |this, cx| { + cx.background_executor().timer(HIGHLIGHT_TTL).await; + let _ = this.update(cx, |_, cx| cx.notify()); + }) + .detach(); + } + fn load_latest_messages(&self, window: &mut Window, cx: &mut Context) { self.load_messages(None, window, cx); } @@ -1294,6 +1791,7 @@ impl Yumush { return; }; let network = self.network.clone(); + let latest = before.is_none() && window.is_window_active(); cx.spawn_in(window, async move |this, cx| { let page = match network @@ -1309,9 +1807,25 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { if yumush.chat.is_selected(&community_id) { - yumush.chat.add_page(page); + let newest = page.last().map(|message| message.id.clone()); + let seeking = yumush.chat.jump.is_some(); + yumush + .chat + .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str())); + if seeking { + if yumush.chat.jump.is_none() { + Self::fade_highlight(cx); + } else if yumush.chat.history == History::More { + yumush.load_older_messages(window, cx); + } else { + yumush.chat.jump = None; + } + } + if let Some(message_id) = newest.filter(|_| latest) { + yumush.mark_read(&community_id, &message_id, cx); + } yumush.request_media(cx); - yumush.request_authors(window, cx); + yumush.request_authors(cx); cx.notify(); } }); @@ -1319,6 +1833,31 @@ impl Yumush { .detach(); } + pub(super) fn request_message_delete( + &mut self, + message_id: String, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_message_delete.as_ref() == Some(&message_id) { + self.chat.pending_message_delete = None; + self.delete_message(&message_id, window, cx); + } else { + self.chat.pending_message_delete = Some(message_id.clone()); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(DELETE_CONFIRM).await; + let _ = this.update(cx, |yumush, cx| { + if yumush.chat.pending_message_delete.as_ref() == Some(&message_id) { + yumush.chat.pending_message_delete = None; + cx.notify(); + } + }); + }) + .detach(); + } + cx.notify(); + } + pub(super) fn delete_message( &self, message_id: &str, @@ -1382,7 +1921,12 @@ impl Yumush { .detach(); } - fn toggle_voice(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { + pub(super) fn toggle_voice( + &mut self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { if self.chat.in_voice(&community_id) { self.end_voice(cx); return; @@ -1393,6 +1937,17 @@ impl Yumush { if was_in { self.chat.set_voice_off(); } + self.join_voice(community_id, (muted, deafened), was_in, window, cx); + } + + fn join_voice( + &mut self, + community_id: String, + (muted, deafened): (bool, bool), + was_in: bool, + window: &mut Window, + cx: &mut Context, + ) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { @@ -1404,7 +1959,7 @@ impl Yumush { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { - let muted = muted || yumush.mic_locked(); + let muted = muted || yumush.mic_locked() || yumush.hidden_in(&community_id); yumush.network.set_muted(muted); yumush.chat.voice.insert(community_id.clone(), participants); yumush.chat.voice_state = VoiceState::In { @@ -1441,6 +1996,28 @@ impl Yumush { .detach(); } + pub(super) fn rejoin_voice(&mut self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.voice_community().map(str::to_string) else { + return; + }; + let flags = self.chat.voice_flags().unwrap_or((false, false)); + self.chat.set_voice_off(); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let Ok(participants) = network.voice_participants(&community_id).await else { + return; + }; + let _ = this.update_in(cx, |yumush, window, cx| { + if participants.iter().any(|id| !yumush.is_me(id)) { + yumush.join_voice(community_id, flags, false, window, cx); + } + cx.notify(); + }); + }) + .detach(); + } + pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context) { if self.chat.in_voice(community_id) { self.end_voice(cx); @@ -1454,7 +2031,17 @@ impl Yumush { } pub(super) fn mic_locked(&self) -> bool { - self.is_server_muted() || self.chat.ghost + self.is_server_muted() + } + + fn hidden_in(&self, community_id: &str) -> bool { + self.chat.ghost || !self.chat.joined(community_id) + } + + fn hidden_in_voice(&self) -> bool { + self.chat + .voice_community() + .is_some_and(|community_id| self.hidden_in(community_id)) } pub(super) fn force_mute(&mut self, cx: &mut Context) { @@ -1465,17 +2052,83 @@ impl Yumush { cx.notify(); } - fn toggle_mute(&mut self, cx: &mut Context) { + fn toggle_mute(&mut self, window: &mut Window, cx: &mut Context) { if self.mic_locked() { return; } + let Some((muted, _)) = self.chat.voice_flags() else { + return; + }; + if muted && self.hidden_in_voice() { + self.confirm_ghost_speak(window, cx); + return; + } + self.set_muted(!muted, cx); + } + + fn set_muted(&mut self, value: bool, cx: &mut Context) { if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { - *muted = !*muted; - self.network.set_muted(*muted); + *muted = value; + self.network.set_muted(value); } cx.notify(); } + fn confirm_ghost_speak(&mut self, window: &mut Window, cx: &mut Context) { + let entity = cx.entity(); + window.open_dialog(cx, move |dialog, _, cx| { + let palette = entity.read(cx).themed(cx); + let speak = entity.clone(); + + dialog.title("Speak as ghost?").child( + div() + .flex() + .flex_col() + .gap(px(14.)) + .child( + div() + .text_size(text(13.)) + .text_color(palette.muted) + .child("Everyone in the call will hear you."), + ) + .child( + div() + .flex() + .justify_end() + .gap(px(8.)) + .child( + clickable("ghost_speak_cancel", palette, |window, cx| { + window.close_dialog(cx) + }) + .h(px(30.)) + .px(px(14.)) + .flex() + .items_center() + .rounded(px(8.)) + .text_color(palette.muted) + .child("Cancel"), + ) + .child( + primary_button( + "ghost_speak_confirm", + palette, + move |window, cx| { + window.close_dialog(cx); + speak.update(cx, |yumush, cx| yumush.set_muted(false, cx)); + }, + ) + .h(px(30.)) + .px(px(14.)) + .flex() + .items_center() + .rounded(px(8.)) + .child("Speak"), + ), + ), + ) + }); + } + fn toggle_deafen(&mut self, cx: &mut Context) { if let VoiceState::In { deafened, .. } = &mut self.chat.voice_state { *deafened = !*deafened; @@ -1488,15 +2141,30 @@ impl Yumush { let network = self.network.clone(); self.chat.voice_task = Some(cx.spawn(async move |this, cx| { + let mut sampled = Instant::now(); loop { cx.background_executor() .timer(Duration::from_millis(150)) .await; let speaking = network.speaking(); + let sample = (sampled.elapsed() >= VOICE_SAMPLE_INTERVAL) + .then(|| network.voice_sample()) + .flatten(); + if sample.is_some() { + sampled = Instant::now(); + } let polling = this.update(cx, |yumush, cx| { if yumush.chat.voice_community().is_none() { return false; } + if let Some(sample) = sample { + let samples = &mut yumush.chat.voice_samples; + samples.push_back(sample); + while samples.len() > SAMPLE_HISTORY { + samples.pop_front(); + } + cx.notify(); + } yumush.update_speaking(speaking, cx); true }); @@ -1525,10 +2193,15 @@ impl Yumush { fn voice_button(&self, entity: &Entity, palette: Palette) -> Option { let community_id = self.chat.selected_community_id.clone()?; + let direct = self.is_direct(&community_id); let in_voice = self.chat.in_voice(&community_id); if !in_voice && (!permission::can_join_voice(self.actor_rank()) - || !self.chat.voice_enabled(&community_id)) + || !(self.is_builder() || self.chat.voice_enabled(&community_id)) + || self + .chat + .notes() + .is_some_and(|notes| notes.id == community_id)) { return None; } @@ -1544,14 +2217,21 @@ impl Yumush { } else { clickable("voice_button", palette, on_click) }; + let button = if direct && in_voice { + button.bg(palette.danger) + } else { + button + }; + let (icon, tip) = match (direct, in_voice) { + (true, false) => (IconName::Phone, "Call"), + (true, true) => (IconName::PhoneOff, "Hang up"), + (false, false) => (IconName::Headphones, "Join voice"), + (false, true) => (IconName::Headphones, "Leave voice"), + }; Some( button - .tip(if in_voice { - "Leave voice" - } else { - "Join voice" - }) + .tip(tip) .size(px(28.)) .flex() .items_center() @@ -1562,10 +2242,159 @@ impl Yumush { } else { palette.accent }) - .child(Icon::new(IconName::Headphones).w(px(14.)).h(px(14.))), + .child(Icon::new(icon).w(px(14.)).h(px(14.))), ) } + fn calling_hint(&self, palette: Palette) -> Option
{ + let community = self.chat.selected_community()?; + let direct = self.is_direct(&community.id); + let alone = self.chat.in_voice(&community.id) + && self + .chat + .voice_ids(&community.id) + .iter() + .all(|id| self.is_me(id)); + + (direct && alone).then(|| { + div() + .text_color(palette.muted) + .text_size(text(11.)) + .child("Calling…") + }) + } + + fn call_banner(&self, entity: &Entity, palette: Palette) -> Option
{ + let (community_id, caller) = self.incoming_call()?; + let accept_id = community_id.clone(); + + Some( + div() + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .px(px(12.)) + .py(px(6.)) + .bg(palette.accent) + .text_color(palette.on_accent) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(Icon::new(IconName::PhoneIncoming).w(px(14.)).h(px(14.))) + .child(format!("{} is calling", caller.username)), + ) + .child( + div() + .flex() + .gap(px(6.)) + .child( + primary_button( + "accept_call", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.accept_call(accept_id.clone(), window, cx) + }), + ) + .bg(palette.ok) + .px(px(8.)) + .rounded(px(4.)) + .child("Accept"), + ) + .child( + clickable( + "decline_call", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.decline_call(community_id.clone(), window, cx) + }), + ) + .bg(palette.danger) + .text_color(palette.on_accent) + .px(px(8.)) + .rounded(px(4.)) + .child("Decline"), + ), + ), + ) + } + + fn incoming_call(&self) -> Option<(String, User)> { + self.chat.communities().iter().find_map(|community| { + let CommunityKind::Direct { peer } = &community.kind else { + return None; + }; + let calling = self.user.is_some() + && self + .chat + .voice_ids(&community.id) + .iter() + .any(|id| !self.is_me(id)); + let ringing = calling + && !self.chat.in_voice(&community.id) + && self.chat.ringing.contains(&community.id); + ringing.then(|| (community.id.clone(), peer.clone())) + }) + } + + fn ring_allowed(&self, community_id: &str) -> bool { + self.user + .as_ref() + .is_some_and(|me| self.presence_of(&me.id) == Presence::Online) + && !self.chat.muted.contains(community_id) + } + + pub(super) fn update_ringing(&mut self, cx: &mut Context) { + if self.incoming_call().is_none() { + self.chat.ring_task = None; + return; + } + if self.chat.ring_task.is_some() { + return; + } + + self.chat.ring_task = Some(cx.spawn(async move |this, cx| { + for _ in 0..RING_LIMIT { + let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { + Some((community_id, _)) => { + if yumush.ring_allowed(&community_id) { + yumush.network.play_ring(); + } + true + } + None => false, + }); + if !matches!(ringing, Ok(true)) { + break; + } + cx.background_executor().timer(RING_INTERVAL).await; + } + })); + } + + fn accept_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { + self.chat.ringing.remove(&community_id); + self.select_community(community_id.clone(), window, cx); + self.toggle_voice(community_id, window, cx); + self.update_ringing(cx); + } + + fn decline_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { + self.chat.ringing.remove(&community_id); + self.update_ringing(cx); + cx.notify(); + + let network = self.network.clone(); + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.decline_call(&community_id).await { + notify_error(&this, cx, error); + } + }) + .detach(); + } + fn voice_stack(&self, entity: &Entity, palette: Palette) -> Option { let community_id = self.chat.selected_community_id.as_deref()?; let users: Vec<&User> = self @@ -1618,7 +2447,7 @@ impl Yumush { IconName::Mic }; let deafen_icon = if deafened { - IconName::VolumeX + IconName::HeadphoneOff } else { IconName::Headphones }; @@ -1628,10 +2457,14 @@ impl Yumush { .flex() .items_center() .child( - clickable("mic_button", palette, move |_, cx| { - mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(cx)) + clickable("mic_button", palette, move |window, cx| { + mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx)) + }) + .tip(match (muted, self.hidden_in_voice()) { + (true, true) => "Speak as ghost", + (true, false) => "Unmute", + (false, _) => "Mute", }) - .tip(if muted { "Unmute" } else { "Mute" }) .size(px(26.)) .flex() .items_center() @@ -1672,14 +2505,15 @@ impl Yumush { } } -fn members_popover(entity: &Entity, chat: &Chat, palette: Palette) -> impl IntoElement { +fn members_popover(entity: &Entity, yumush: &Yumush, palette: Palette) -> impl IntoElement { + let chat = &yumush.chat; let entity = entity.clone(); let voice: Vec = chat .selected_community_id .as_deref() .map(|community_id| chat.voice_ids(community_id).to_vec()) .unwrap_or_default(); - let members: Vec<(User, Option, bool, bool)> = chat + let members: Vec<(User, Option, bool, bool, Presence)> = chat .members .iter() .map(|member| { @@ -1688,6 +2522,7 @@ fn members_popover(entity: &Entity, chat: &Chat, palette: Palette) -> im chat.rank_of(&member.user), voice.contains(&member.user.id), chat.server_muted.contains(&member.user.id), + yumush.presence_of(&member.user.id), ) }) .collect(); @@ -1698,78 +2533,111 @@ fn members_popover(entity: &Entity, chat: &Chat, palette: Palette) -> im .appearance(false) .trigger(MembersTrigger { palette, - members: members.iter().map(|(user, _, _, _)| user.clone()).collect(), + members: members + .iter() + .map(|(user, _, _, _, _)| user.clone()) + .collect(), avatars: avatars.clone(), }) .content(move |_, _, _| { let entity = entity.clone(); - div() - .w(px(200.)) - .p(px(4.)) - .flex() - .flex_col() - .rounded(px(8.)) - .border_1() - .border_color(palette.border) - .bg(palette.panel) - .children(members.iter().map(|(user, rank, in_voice, muted)| { - profile_popover( - format!("member_{}", user.id), - Anchor::TopRight, - user, - &entity, - hoverable( - format!("member_trigger_{}", user.id), - div() - .h(px(30.)) - .px(px(8.)) - .flex() - .items_center() - .gap(px(8.)) - .rounded(px(6.)) - .child(avatar(palette, user, px(18.), text(9.), &avatars)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child( - div() - .flex() - .items_center() - .gap(px(6.)) - .child(user.username.clone()) - .children(rank_tag(*rank, palette)) - .children(in_voice.then(|| { - Icon::new(IconName::Headphones) - .w(px(12.)) - .h(px(12.)) - .text_color(palette.muted) - })) - .children(muted.then(|| { - Icon::new(IconName::MicOff) - .w(px(12.)) - .h(px(12.)) - .text_color(palette.danger) - })), - ) - .children((!user.status.is_empty()).then(|| { - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(user.status.clone()) - })), - ), - palette, - ), - ) - })) + pop_in( + "members_list", + div() + .w(px(200.)) + .p(px(4.)) + .flex() + .flex_col() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .children( + members + .iter() + .map(|(user, rank, in_voice, muted, presence)| { + profile_popover( + format!("member_{}", user.id), + Anchor::TopRight, + user, + &entity, + hoverable( + format!("member_trigger_{}", user.id), + div() + .h(px(30.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .child(presence_avatar( + avatar(palette, user, px(18.), text(9.), &avatars), + *presence, + px(18.), + palette, + )) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(user.username.clone()) + .children(rank_tag(*rank, palette)) + .children(in_voice.then(|| { + Icon::new(IconName::Headphones) + .w(px(12.)) + .h(px(12.)) + .text_color(palette.muted) + })) + .children(muted.then(|| { + Icon::new(IconName::MicOff) + .w(px(12.)) + .h(px(12.)) + .text_color(palette.danger) + })), + ) + .children((!user.status.is_empty()).then( + || { + div() + .text_size(text(11.)) + .text_color(palette.muted) + .truncate() + .child(user.status.clone()) + }, + )), + ), + palette, + ), + ) + }), + ), + Anchor::TopRight, + ) }) } +fn new_divider(palette: Palette) -> impl IntoElement { + div() + .flex() + .items_center() + .gap(px(8.)) + .my(px(6.)) + .child(div().flex_1().h(px(1.)).bg(palette.accent)) + .child( + div() + .text_size(text(10.)) + .text_color(palette.accent) + .child("New"), + ) +} + fn older_button(entity: &Entity, palette: Palette) -> impl IntoElement { let entity = entity.clone(); @@ -1786,6 +2654,55 @@ fn older_button(entity: &Entity, palette: Palette) -> impl IntoElement { .child("↑") } +fn call_duration(seconds: u64) -> String { + let (hours, minutes, seconds) = (seconds / 3600, seconds % 3600 / 60, seconds % 60); + if hours > 0 { + format!("{hours}h {minutes}m") + } else if minutes > 0 { + format!("{minutes}m {seconds}s") + } else { + format!("{seconds}s") + } +} + +fn render_call( + message: &Message, + call: CallLog, + chat: &Chat, + me: Option<&User>, + palette: Palette, +) -> AnyElement { + let mine = me.is_some_and(|me| me.id == message.user_id); + let author = chat + .author(&message.user_id) + .map_or("unknown", |user| user.username.as_str()); + let who = if mine { "You" } else { author }; + let (icon, color) = match call { + CallLog::Started | CallLog::Ended { .. } => (IconName::Phone, palette.ok), + CallLog::Declined => (IconName::PhoneOff, palette.danger), + CallLog::Missed => (IconName::PhoneMissed, palette.danger), + }; + let label = match call { + CallLog::Started => format!("{who} started a call"), + CallLog::Declined => format!("{who} declined the call"), + CallLog::Missed if mine => "You called, no answer".to_string(), + CallLog::Missed => format!("Missed call from {author}"), + CallLog::Ended { seconds } => format!("Call ended · {}", call_duration(seconds)), + }; + + div() + .id(format!("message_row_{}", message.id)) + .flex() + .items_center() + .gap(px(6.)) + .pl(px(28.)) + .text_size(text(12.)) + .text_color(palette.muted) + .child(Icon::new(icon).w(px(14.)).h(px(14.)).text_color(color)) + .child(label) + .into_any_element() +} + fn render_message( message: &Message, first: bool, @@ -1795,6 +2712,9 @@ fn render_message( entity: &Entity, palette: Palette, ) -> AnyElement { + if let Some(call) = message.call { + return render_call(message, call, chat, me, palette); + } let author = chat.author(&message.user_id); let username = author .map(|user| user.username.as_str()) @@ -1817,97 +2737,139 @@ fn render_message( }) .child(username.to_string()), ); + let mentioned = me.is_some_and(|me| mentions(&message.body, &me.username)); let group = format!("message_{}", message.id); let selecting = matches!(chat.composer, Composer::Select { .. }); let selected = matches!(&chat.composer, Composer::Select { ids } if ids.contains(&message.id)); - - let row = - div() - .id(format!("message_row_{}", message.id)) - .group(group.clone()) - .flex() - .flex_col() - .min_w_0() - .when(first && spaced, |this| this.mt(px(14.))) - .when(first, |this| { - let author = match author { - Some(user) => profile_popover( - format!("author_{}", message.id), - Anchor::TopLeft, - user, - entity, - name.cursor_pointer(), - ) - .into_any_element(), - None => name.into_any_element(), - }; - - this.child( - div() - .flex() - .items_center() - .gap(px(8.)) - .mb(px(2.)) - .child(author) - .child( - div() - .text_size(text(12.)) - .text_color(palette.muted) - .child(id_time(&message.id, CLOCK)), - ), + let highlighted = chat + .highlight + .as_ref() + .is_some_and(|(id, at)| id == &message.id && at.elapsed() < HIGHLIGHT_TTL); + + let row = div() + .id(format!("message_row_{}", message.id)) + .group(group.clone()) + .flex() + .flex_col() + .min_w_0() + .when(first && spaced && !selecting, |this| this.mt(px(14.))) + .when(highlighted, |this| this.bg(palette.accent.opacity(0.2))) + .when(mentioned, |this| { + this.bg(palette.accent.opacity(0.08)) + .border_l_2() + .border_color(palette.accent) + }) + .when(first, |this| { + let author = match author { + Some(user) => profile_popover( + format!("author_{}", message.id), + Anchor::TopLeft, + user, + entity, + name.cursor_pointer(), ) - }) - .child( + .into_any_element(), + None => name.into_any_element(), + }; + + this.child( div() - .pl(px(28.)) .flex() .items_center() .gap(px(8.)) + .mb(px(2.)) + .child(author) .child( div() - .max_w(px(720.)) - .flex() - .flex_col() - .gap(px(6.)) - .children(message_actions::quote_line(message, chat, palette)) - .when(!message.body.is_empty(), |this| { - this.child( - div() - .flex() - .flex_wrap() - .items_baseline() - .gap(px(4.)) - .line_height(relative(1.55)) - .text_color(palette.body) - .child(message.body.clone()) - .when(message.edited, |this| { - this.child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .child("(edited)"), + .text_size(text(12.)) + .text_color(palette.muted) + .child(id_time(&message.id, CLOCK)), + ), + ) + }) + .child( + div() + .relative() + .pl(px(28.)) + .min_w_0() + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .min_w_0() + .max_w(px(720.)) + .flex() + .flex_col() + .gap(px(6.)) + .children(message_actions::quote_line(message, chat, palette)) + .when(!message.body.is_empty(), |this| { + this.child( + div() + .min_w_0() + .flex() + .flex_wrap() + .items_baseline() + .gap(px(4.)) + .line_height(relative(1.55)) + .text_color(palette.body) + .child( + div().min_w_0().child( + gpui_kit::component::text::TextView::markdown( + format!("message-body-{}", message.id), + hard_breaks(&message.body), ) - }), - ) - }) - .children(media_view::attachments( - &message.attachments, - &chat.media, + .selectable(true), + ), + ) + .when(message.edited, |this| { + this.child( + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child("(edited)"), + ) + }), + ) + }) + .children(media_view::attachments( + &message.attachments, + &chat.media, + entity, + palette, + )) + .children(snippet::snippet_card(message, chat, entity, palette)) + .children(message.poll.as_ref().map(|poll| { + poll::poll_card( + poll, + poll::PollMode::Live(message), + me, + chat, entity, palette, - )) - .children(snippet::snippet_card(message, chat, entity, palette)) - .children(media_view::embeds(message, &chat.media, palette)), - ) - .child(div().flex_1()) - .children((!selecting).then(|| { - message_actions::actions(message, chat, me, entity, palette, group) - })), - ) - .children( - (chat.report == Some(ReportTarget::Message(message.id.clone()))) - .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)), - ); + ) + })) + .children(media_view::embeds(message, &chat.media, palette)) + .children( + (!message.reactions.is_empty()) + .then(|| message_actions::reactions(message, me, entity, palette)), + ), + ) + .children(message.pinned.then(|| message_actions::pin_mark(palette))) + .children((!selecting).then(|| { + div() + .absolute() + .right_0() + .top(px(-18.)) + .child(message_actions::actions( + message, chat, me, entity, palette, group, + )) + })), + ) + .children( + (chat.report == Some(ReportTarget::Message(message.id.clone()))) + .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)), + ); if !selecting { return row.into_any_element(); @@ -1915,20 +2877,34 @@ fn render_message( let message_id = message.id.clone(); let select_entity = entity.clone(); - let row = row - .flex_1() - .cursor_pointer() - .when(selected, |this| this.bg(palette.hover)) - .on_click(move |_, _, cx| { - select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx)); - }); + let mark_line = if first { + div().h(px(20.)) + } else { + div().line_height(relative(1.55)).child("\u{200b}") + }; div() + .id(format!("select_row_{}", message.id)) + .when(first && spaced, |this| this.mt(px(14.))) .flex() .items_start() .gap(px(8.)) - .child(message_actions::selection_mark(selected, palette)) - .child(row) + .px(px(6.)) + .rounded(px(6.)) + .cursor_pointer() + .hover(|style| style.bg(palette.hover.opacity(0.5))) + .when(selected, |this| this.bg(palette.hover)) + .on_click(move |_, _, cx| { + select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx)); + }) + .child( + mark_line + .flex_shrink_0() + .flex() + .items_center() + .child(message_actions::selection_mark(selected, palette)), + ) + .child(row.flex_1()) .into_any_element() } @@ -1951,3 +2927,21 @@ fn editable_input( .detach(); input } + +fn hard_breaks(body: &str) -> String { + let mut fenced = false; + let lines: Vec = body + .lines() + .map(|line| { + if line.trim_start().starts_with("```") { + fenced = !fenced; + return line.to_string(); + } + match fenced || line.trim().is_empty() { + true => line.to_string(), + false => format!("{line} "), + } + }) + .collect(); + lines.join("\n") +} diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index 93a6b7f..13de0e4 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -26,6 +26,7 @@ use super::{ Palette, Yumush, avatar, chat::{DeleteStep, View}, clickable, community_icon, entity_action, id_time, notify_error, + profile::user_link, settings_page::{ Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file, row, section, text_row, @@ -701,14 +702,24 @@ fn ban_row( .flex() .items_center() .gap(px(8.)) - .child(avatar(palette, user, px(20.), text(10.), avatars)) + .child(user_link( + format!("ban_avatar_{user_id}"), + Some(user), + &entity, + avatar(palette, user, px(20.), text(10.), avatars), + )) .child( div() .flex_1() .min_w_0() .flex() .flex_col() - .child(user.username.clone()) + .child(user_link( + format!("ban_name_{user_id}"), + Some(user), + &entity, + div().truncate().child(user.username.clone()), + )) .children(ban.reason.clone().map(|reason| { div() .text_size(text(11.)) diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index f0b5432..d3e9c1e 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -1,16 +1,46 @@ use super::text; +use std::time::{Duration, Instant}; + use common::{ - constant::MAXIMUM_FORWARD_MESSAGES, - validate::{validate_message_body, validate_new_message}, + constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS}, + error::Error, + model::Attachment, + time::now_ms, + validate::{validate_message_body, validate_new_message, validate_poll}, }; use gpui_kit::{ - AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, + KeyBinding, ParentElement, Styled, Window, actions, assets::IconName, - component::{Icon, WindowExt, input::InputState, notification::Notification}, + component::{ + Icon, WindowExt, + checkbox::Checkbox, + input::{Input, InputState}, + notification::Notification, + popover::Popover, + text::TextView, + }, div, px, }; -use super::{Palette, Tooltip as _, Yumush, chat::Chat, clickable, notify_error, primary_button}; +use super::{ + Palette, Tooltip as _, Trigger, Yumush, + chat::{Chat, TYPING_SEND_INTERVAL}, + clickable, hoverable, new_input, notify_error, pop_in, primary_button, +}; + +actions!(composer, [Bold, Italic, Code, Strike]); + +pub const CONTEXT: &str = "MessageComposer"; + +const FORMAT_ROWS: [(&str, &str); 6] = [ + ("**bold**", "Ctrl+B"), + ("*italic*", "Ctrl+I"), + ("`code`", "Ctrl+E"), + ("~~strike~~", "Ctrl+Shift+X"), + ("> quote", ""), + ("- list", ""), +]; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Composer { @@ -19,7 +49,13 @@ pub enum Composer { Select { ids: Vec }, } +const SLOW_TICK: Duration = Duration::from_secs(1); + pub fn mode_bar(chat: &Chat, entity: &Entity, palette: Palette) -> Option { + if let Some(seconds) = chat.slow_seconds() { + return Some(slow_bar(seconds, palette).into_any_element()); + } + match &chat.composer { Composer::Compose { reply: Some(message_id), @@ -110,6 +146,13 @@ fn reply_bar( .child(cancel_button(entity, palette)) } +fn slow_bar(seconds: u64, palette: Palette) -> impl IntoElement { + bar(palette) + .text_color(palette.danger) + .child(Icon::new(IconName::Hourglass).w(px(12.)).h(px(12.))) + .child(format!("Slow down, you can send again in {seconds}s")) +} + fn edit_bar(entity: &Entity, palette: Palette) -> impl IntoElement { bar(palette) .child(Icon::new(IconName::Pencil).w(px(12.)).h(px(12.))) @@ -155,6 +198,35 @@ impl Yumush { } } + pub(super) fn send_typing(&mut self, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + if self + .chat + .message_input + .read(cx) + .text() + .to_string() + .is_empty() + || self + .chat + .typing_sent + .get(&community_id) + .is_some_and(|at| at.elapsed() < TYPING_SEND_INTERVAL) + { + return; + } + self.chat + .typing_sent + .insert(community_id.clone(), Instant::now()); + let network = self.network.clone(); + cx.spawn(async move |_, _| { + let _ = network.typing(&community_id).await; + }) + .detach(); + } + fn create_message( &mut self, reply: Option, @@ -171,6 +243,9 @@ impl Yumush { .map(|attachment| attachment.id.clone()) .collect(); + if self.chat.slow_seconds().is_some() { + return; + } let maximum = self.max_message_length(); if let Err(error) = validate_new_message(&body, attachments.len(), maximum) { window.push_notification(Notification::error(error.to_string()), cx); @@ -181,13 +256,24 @@ impl Yumush { return; }; let network = self.network.clone(); + let restore = input.clone(); + let pending = self.chat.media.pending.clone(); + self.chat.drafts.remove(&community_id); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network + match network .create_message(&community_id, &body, attachments, reply) .await { - notify_error(&this, cx, error); + Ok(_) => {} + Err(Error::RateLimited { + retry_after_seconds, + }) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.slow_down(retry_after_seconds, &restore, body, pending, window, cx) + }); + } + Err(error) => notify_error(&this, cx, error), } }) .detach(); @@ -197,6 +283,39 @@ impl Yumush { self.chat.composer = Composer::Compose { reply: None }; } + fn slow_down( + &mut self, + seconds: u64, + input: &Entity, + body: String, + pending: Vec, + window: &mut Window, + cx: &mut Context, + ) { + if input.read(cx).text().len() == 0 { + input.update(cx, |state, cx| state.set_value(body, window, cx)); + } + if self.chat.media.pending.is_empty() { + self.chat.media.pending = pending; + } + self.chat.slowed_until = Some(now_ms() + seconds * 1000); + cx.notify(); + + cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(SLOW_TICK).await; + let slowed = this.update(cx, |yumush, cx| { + cx.notify(); + yumush.chat.slow_seconds().is_some() + }); + if !matches!(slowed, Ok(true)) { + break; + } + } + }) + .detach(); + } + fn update_message( &mut self, message_id: String, @@ -223,6 +342,35 @@ impl Yumush { cx.notify(); } + pub(super) fn save_draft(&mut self, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let text = self.chat.message_input.read(cx).text().to_string(); + if text.is_empty() || !matches!(self.chat.composer, Composer::Compose { .. }) { + self.chat.drafts.remove(&community_id); + } else { + self.chat.drafts.insert(community_id, text); + } + } + + pub(super) fn restore_draft( + &mut self, + community_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let text = self + .chat + .drafts + .get(community_id) + .cloned() + .unwrap_or_default(); + self.chat + .message_input + .update(cx, |input, cx| input.set_value(text, window, cx)); + } + pub(super) fn reply( &mut self, message_id: String, @@ -294,3 +442,260 @@ impl Yumush { cx.notify(); } } + +pub fn bind_keys(cx: &mut App) { + let scope = format!("{CONTEXT} > Input"); + cx.bind_keys([ + KeyBinding::new("ctrl-b", Bold, Some(scope.as_str())), + KeyBinding::new("ctrl-i", Italic, Some(scope.as_str())), + KeyBinding::new("ctrl-e", Code, Some(scope.as_str())), + KeyBinding::new("ctrl-shift-x", Strike, Some(scope.as_str())), + ]); +} + +pub fn format_actions(input: &Entity, row: Div) -> Div { + let (bold, italic, code, strike) = (input.clone(), input.clone(), input.clone(), input.clone()); + row.key_context(CONTEXT) + .on_action(move |_: &Bold, window, cx| wrap(&bold, "**", window, cx)) + .on_action(move |_: &Italic, window, cx| wrap(&italic, "*", window, cx)) + .on_action(move |_: &Code, window, cx| wrap(&code, "`", window, cx)) + .on_action(move |_: &Strike, window, cx| wrap(&strike, "~~", window, cx)) +} + +fn wrap(input: &Entity, mark: &str, window: &mut Window, cx: &mut App) { + input.update(cx, |state, cx| { + let start = state.selected_range().start + mark.len(); + let selected = state.selected_text().to_string(); + state.replace(format!("{mark}{selected}{mark}"), window, cx); + state.set_selected_range(start..start + selected.len(), cx); + }); +} + +pub fn format_popover(palette: Palette) -> impl IntoElement { + Popover::new("format_popover") + .anchor(Anchor::BottomLeft) + .appearance(false) + .trigger(Trigger::new(hoverable( + "format_trigger", + div() + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Type).w(px(14.)).h(px(14.))), + palette, + ))) + .content(move |_, _, _| { + pop_in( + "format_list", + div() + .w(px(340.)) + .p(px(8.)) + .flex() + .flex_col() + .gap(px(6.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .text_size(text(12.)) + .children(FORMAT_ROWS.map(|(syntax, shortcut)| { + div() + .flex() + .items_center() + .gap(px(12.)) + .child(div().w(px(100.)).text_color(palette.muted).child(syntax)) + .child(div().flex_1().child(TextView::markdown(syntax, syntax))) + .child(div().text_color(palette.muted).child(shortcut)) + })), + Anchor::BottomLeft, + ) + }) +} + +fn poll_field(input: &Entity, palette: Palette) -> impl IntoElement { + div() + .h(px(30.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .child( + Input::new(input) + .appearance(false) + .text_color(palette.text) + .flex_1() + .min_w_0(), + ) +} + +pub fn poll_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { + let question = chat.poll_question.clone(); + let options = chat.poll_options.clone(); + let multiple = chat.poll_multiple; + let entity = entity.clone(); + + Popover::new("poll_popover") + .anchor(Anchor::BottomLeft) + .appearance(false) + .trigger(Trigger::new(hoverable( + "poll_trigger", + div() + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))), + palette, + ))) + .content(move |_, _, cx| { + let popover = cx.entity(); + let toggle = entity.clone(); + let add = entity.clone(); + let submit = entity.clone(); + pop_in( + "poll_form", + div() + .w(px(300.)) + .p(px(8.)) + .flex() + .flex_col() + .gap(px(6.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .text_size(text(12.)) + .child(poll_field(&question, palette)) + .children(options.iter().enumerate().map(|(index, option)| { + let remove = entity.clone(); + div() + .flex() + .items_center() + .gap(px(6.)) + .child(div().flex_1().min_w_0().child(poll_field(option, palette))) + .children((options.len() > MINIMUM_POLL_OPTIONS).then(|| { + clickable(format!("poll_remove_{index}"), palette, move |_, cx| { + remove.update(cx, |yumush, cx| { + yumush.remove_poll_option(index, cx) + }); + }) + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))) + })) + })) + .child( + div() + .flex() + .items_center() + .justify_between() + .child( + Checkbox::new("poll_multiple") + .label("Multiple answers") + .checked(multiple) + .on_click(move |_, _, cx| { + toggle.update(cx, |yumush, cx| { + yumush.chat.poll_multiple = !yumush.chat.poll_multiple; + cx.notify(); + }) + }), + ) + .children((options.len() < MAXIMUM_POLL_OPTIONS).then(|| { + clickable("poll_add", palette, move |window, cx| { + add.update(cx, |yumush, cx| yumush.add_poll_option(window, cx)); + }) + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Plus).w(px(14.)).h(px(14.))) + })), + ) + .child( + primary_button("poll_create", palette, move |window, cx| { + if submit.update(cx, |yumush, cx| yumush.send_poll(window, cx)) { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + } + }) + .h(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .child("Create"), + ), + Anchor::BottomLeft, + ) + }) +} + +impl Yumush { + pub(super) fn add_poll_option(&mut self, window: &mut Window, cx: &mut Context) { + if self.chat.poll_options.len() < MAXIMUM_POLL_OPTIONS { + let input = new_input("Option", window, cx); + self.chat.poll_options.push(input); + cx.notify(); + } + } + + pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context) { + if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS { + self.chat.poll_options.remove(index); + cx.notify(); + } + } + + pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context) -> bool { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return false; + }; + let question = self.chat.poll_question.read(cx).text().to_string(); + let options: Vec = self + .chat + .poll_options + .iter() + .map(|input| input.read(cx).text().to_string()) + .collect(); + if let Err(error) = validate_poll(&question, &options) { + window.push_notification(Notification::error(error.to_string()), cx); + return false; + } + let multiple = self.chat.poll_multiple; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network + .create_poll(&community_id, &question, options, multiple) + .await + { + notify_error(&this, cx, error); + } + }) + .detach(); + + self.chat + .poll_question + .update(cx, |state, cx| state.set_value("", window, cx)); + self.chat.poll_options.truncate(MINIMUM_POLL_OPTIONS); + for input in &self.chat.poll_options { + input.update(cx, |state, cx| state.set_value("", window, cx)); + } + self.chat.poll_multiple = false; + cx.notify(); + true + } +} diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index 225ef0c..47469ce 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -10,9 +10,7 @@ use gpui_kit::{ div, px, }; -use super::{ - Yumush, clickable, community_icon, community_name, composer::Composer, notify_error, palette, -}; +use super::{Yumush, clickable, community_name, composer::Composer, notify_error, palette}; pub struct Forward { yumush: Entity, @@ -82,13 +80,7 @@ impl Render for Forward { .items_center() .gap(px(8.)) .rounded(px(6.)) - .child(community_icon( - palette, - community, - px(16.), - text(9.), - &yumush.chat.avatars, - )) + .child(yumush.community_badge(community, px(16.), text(9.), palette)) .child( div() .flex_1() diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index 9370bc7..77bdcb9 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -22,10 +22,13 @@ use gpui_kit::{ px, }; -use super::{Palette, Tooltip as _, Yumush, clickable, notify_error, storage}; +use super::{ + Palette, Tooltip as _, Yumush, clickable, notify_error, storage, + voice_note::{VoiceNote, bars}, +}; use crate::{ embed::{self, Embed, EmbedKind}, - media::Player, + media::{Player, voice_note as note}, }; const FRAME_TICK: Duration = Duration::from_millis(16); @@ -58,8 +61,10 @@ pub struct Playing { #[derive(Default)] pub struct Media { pub pending: Vec, - uploading: usize, + pub(super) uploading: usize, + pub(super) voice_note: VoiceNote, thumbnails: HashMap>, + waveforms: HashMap, embeds: HashMap, requested: HashSet, playing: Option, @@ -73,6 +78,7 @@ impl Media { pub fn leave(&mut self) { self.pending.clear(); self.playing = None; + self.voice_note = VoiceNote::Idle; } } @@ -124,7 +130,7 @@ fn cache_path(attachment: &Attachment) -> Option { Some(directory.join(format!("{}{extension}", attachment.id))) } -fn time_text(time: Duration) -> String { +pub fn time_text(time: Duration) -> String { let seconds = time.as_secs(); format!("{}:{:02}", seconds / 60, seconds % 60) } @@ -139,6 +145,7 @@ impl Yumush { let mut thumbnails = Vec::new(); let mut links = Vec::new(); let mut avatars = Vec::new(); + let mut voices = Vec::new(); for message in &self.chat.messages { let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages); for item in forwarded.clone() { @@ -156,6 +163,11 @@ impl Yumush { { thumbnails.push(attachment.id.clone()); } + if note::is_voice_note(attachment) + && self.chat.media.requested.insert(attachment.id.clone()) + { + voices.push(attachment.clone()); + } } for url in embed::urls(&message.body) { if self.chat.media.requested.insert(url.clone()) { @@ -184,6 +196,28 @@ impl Yumush { .detach(); } + for attachment in voices { + let fetched = self.fetch_file(&attachment, cx); + let attachment_id = attachment.id.clone(); + cx.spawn(async move |this, cx| { + let Ok(path) = fetched.await else { + return; + }; + let Some(waveform) = cx + .background_executor() + .spawn(async move { note::waveform(&path) }) + .await + else { + return; + }; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.waveforms.insert(attachment_id, waveform); + cx.notify(); + }); + }) + .detach(); + } + for url in links { cx.spawn(async move |this, cx| { let fetched = cx @@ -394,14 +428,7 @@ impl Yumush { let SliderEvent::Release(value) = event else { return; }; - if let Some(Playing { - state: PlayState::Ready { player, .. }, - .. - }) = &yumush.chat.media.playing - { - player.seek(Duration::from_secs_f32(value.start().max(0.))); - } - cx.notify(); + yumush.seek_playing(value.start(), cx); }); let tick = cx.spawn_in(window, async move |this, cx| { loop { @@ -459,6 +486,17 @@ impl Yumush { cx.notify(); } + fn seek_playing(&mut self, seconds: f32, cx: &mut Context) { + if let Some(Playing { + state: PlayState::Ready { player, .. }, + .. + }) = &self.chat.media.playing + { + player.seek(Duration::from_secs_f32(seconds.max(0.))); + } + cx.notify(); + } + pub(super) fn stop_playing(&mut self, cx: &mut Context) { if let Some(Playing { state: PlayState::Ready { @@ -646,6 +684,7 @@ fn player_view( yumush.play(attachment, window, cx) }), ); + let voice = note::is_voice_note(attachment); let detail = match state { Some(PlayState::Loading) => "…".to_string(), Some(PlayState::Ready { player, .. }) => format!( @@ -653,14 +692,29 @@ fn player_view( time_text(player.position()), time_text(player.info().duration.unwrap_or_default()) ), + None if voice => media + .waveforms + .get(&attachment.id) + .map_or("…".to_string(), |waveform| time_text(waveform.duration)), None => storage(attachment.size), }; let controls = card(palette) .child(toggle) - .child(name_block(attachment, detail, palette)) + .when(voice, |this| { + this.child(waveform_view(attachment, media, entity, state, palette)) + .child( + div() + .text_size(text(12.)) + .text_color(palette.muted) + .child(detail.clone()), + ) + }) + .when(!voice, |this| { + this.child(name_block(attachment, detail, palette)) + }) .when_some( match state { - Some(PlayState::Ready { seek, .. }) => Some(seek), + Some(PlayState::Ready { seek, .. }) if !voice => Some(seek), _ => None, }, |this, seek| this.child(div().w(px(140.)).child(Slider::new(seek))), @@ -693,6 +747,42 @@ fn player_view( .child(controls) } +fn waveform_view( + attachment: &Attachment, + media: &Media, + entity: &Entity, + state: Option<&PlayState>, + palette: Palette, +) -> impl IntoElement { + let levels = media + .waveforms + .get(&attachment.id) + .map_or(&[][..], |waveform| waveform.peaks.as_slice()); + match state { + Some(PlayState::Ready { player, .. }) => { + let duration = player + .info() + .duration + .unwrap_or_default() + .as_secs_f32() + .max(0.1); + let progress = player.position().as_secs_f32() / duration; + let entity = entity.clone(); + bars(levels, progress, palette, move |index, _, cx| { + entity.update(cx, |yumush, cx| { + yumush.seek_playing(index as f32 / note::BARS as f32 * duration, cx) + }) + }) + } + _ => { + let play = on_attachment(entity, attachment, |yumush, attachment, window, cx| { + yumush.play(attachment, window, cx) + }); + bars(levels, 0., palette, move |_, window, cx| play(window, cx)) + } + } +} + pub fn embeds(message: &Message, media: &Media, palette: Palette) -> Vec { embed::urls(&message.body) .into_iter() diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index 0d5dd7e..ecf2b06 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -1,20 +1,150 @@ use super::text; -use common::model::{Message, User}; +use common::{ + constant::REACTIONS, + model::{Message, User}, +}; use gpui_kit::{ - Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window, + Anchor, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, + Stateful, Styled, Window, assets::IconName, - component::{Icon, input::InputState}, - div, px, + component::{Icon, input::InputState, popover::Popover}, + div, + prelude::FluentBuilder as _, + px, }; use super::{ - Palette, Tooltip as _, Yumush, + CLOCK, Palette, Tooltip as _, Trigger, Yumush, auth::field, avatar, chat::{Chat, ReportTarget}, - clickable, entity_action, notify_error, primary_button, + clickable, entity_action, hoverable, id_time, notify_error, pop_in, primary_button, sidebar, }; +pub fn reactions( + message: &Message, + me: Option<&User>, + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let me_id = me.map(|me| me.id.clone()); + + div() + .flex() + .flex_wrap() + .gap(px(4.)) + .children(message.reactions.iter().map(|reaction| { + let mine = me_id + .as_ref() + .is_some_and(|id| reaction.user_ids.contains(id)); + let entity = entity.clone(); + let message_id = message.id.clone(); + let emoji = reaction.emoji.clone(); + let chip_emoji = reaction.emoji.clone(); + let count = reaction.user_ids.len(); + + clickable( + format!("reaction_{}_{}", message.id, reaction.emoji), + palette, + move |window, cx| { + let message_id = message_id.clone(); + let emoji = emoji.clone(); + entity.update(cx, |yumush, cx| { + yumush.toggle_reaction(message_id, emoji, window, cx) + }); + }, + ) + .flex() + .items_center() + .gap(px(4.)) + .h(px(22.)) + .px(px(6.)) + .rounded_full() + .border_1() + .border_color(if mine { palette.accent } else { palette.border }) + .bg(if mine { + palette.accent.opacity(0.15) + } else { + palette.panel + }) + .text_size(text(12.)) + .child(chip_emoji) + .child(div().text_color(palette.muted).child(count.to_string())) + })) +} + +pub fn react_popover( + message: &Message, + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let message_id = message.id.clone(); + let entity = entity.clone(); + + Popover::new(format!("react_{}", message.id)) + .anchor(Anchor::TopRight) + .appearance(false) + .trigger(Trigger::new(hoverable( + format!("react_trigger_{}", message.id), + div() + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child( + Icon::new(IconName::FaceSlightlySmiling) + .w(px(14.)) + .h(px(14.)), + ), + palette, + ))) + .content(move |_, _, cx| { + let popover = cx.entity(); + pop_in( + "react_list", + div() + .flex() + .gap(px(2.)) + .p(px(4.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .children(REACTIONS.map(|emoji| { + let entity = entity.clone(); + let message_id = message_id.clone(); + let popover = popover.clone(); + clickable( + format!("react_{emoji}_{message_id}"), + palette, + move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + let message_id = message_id.clone(); + entity.update(cx, |yumush, cx| { + yumush.toggle_reaction( + message_id, + emoji.to_string(), + window, + cx, + ) + }); + }, + ) + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_size(text(16.)) + .child(emoji) + })), + Anchor::TopRight, + ) + }) +} + pub fn quote_text(body: &str, attachments: usize) -> String { if body.is_empty() { format!("{attachments} attachments") @@ -57,7 +187,6 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option impl IntoElement { div() - .mt(px(3.)) .size(px(16.)) .flex_shrink_0() .flex() @@ -83,6 +212,192 @@ pub fn selection_mark(selected: bool, palette: Palette) -> impl IntoElement { })) } +pub fn pin_mark(palette: Palette) -> impl IntoElement { + div() + .flex_shrink_0() + .text_color(palette.muted) + .child(Icon::new(IconName::Pin).w(px(12.)).h(px(12.))) +} + +pub fn search_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { + let entity = entity.clone(); + let input = chat.community_search.clone(); + let hits: Vec<(String, String, String, String)> = chat + .community_hits + .iter() + .map(|hit| { + let name = hit + .author + .as_ref() + .map(|user| user.username.clone()) + .unwrap_or_default(); + ( + hit.message.id.clone(), + name, + id_time(&hit.message.id, CLOCK), + quote_text(&hit.message.body, hit.message.attachments.len()), + ) + }) + .collect(); + + Popover::new("search_popover") + .anchor(Anchor::TopRight) + .appearance(false) + .trigger(Trigger::new(hoverable( + "search_trigger", + div() + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))), + palette, + ))) + .content(move |_, _, cx| { + let popover = cx.entity(); + pop_in( + "search_list", + div() + .w(px(320.)) + .p(px(4.)) + .flex() + .flex_col() + .gap(px(4.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child(sidebar::input_box(&input, palette)) + .children(hits.iter().map(|(message_id, name, time, body)| { + let entity = entity.clone(); + let popover = popover.clone(); + let message_id = message_id.clone(); + clickable( + format!("search_hit_{message_id}"), + palette, + move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + let message_id = message_id.clone(); + entity.update(cx, |yumush, cx| { + yumush.go_to_message(message_id, window, cx) + }); + }, + ) + .flex() + .gap(px(6.)) + .px(px(8.)) + .py(px(4.)) + .rounded(px(6.)) + .text_size(text(12.)) + .child( + div() + .flex_shrink_0() + .font_weight(FontWeight::SEMIBOLD) + .child(name.clone()), + ) + .child( + div() + .flex_shrink_0() + .text_color(palette.muted) + .child(time.clone()), + ) + .child(div().flex_1().min_w_0().truncate().child(body.clone())) + })), + Anchor::TopRight, + ) + }) +} + +pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { + let entity = entity.clone(); + let pins: Vec<(String, String, String)> = chat + .pins + .iter() + .map(|pin| { + let name = chat + .author(&pin.user_id) + .map(|user| user.username.clone()) + .unwrap_or_default(); + ( + pin.id.clone(), + name, + quote_text(&pin.body, pin.attachments.len()), + ) + }) + .collect(); + + Popover::new("pins_popover") + .anchor(Anchor::TopRight) + .appearance(false) + .trigger(Trigger::new(hoverable( + "pins_trigger", + div() + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Pin).w(px(14.)).h(px(14.))), + palette, + ))) + .content(move |_, _, cx| { + let popover = cx.entity(); + pop_in( + "pins_list", + div() + .w(px(260.)) + .p(px(4.)) + .flex() + .flex_col() + .gap(px(2.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .children(pins.iter().map(|(message_id, name, body)| { + let entity = entity.clone(); + let popover = popover.clone(); + let message_id = message_id.clone(); + clickable( + format!("pin_hit_{message_id}"), + palette, + move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + let message_id = message_id.clone(); + entity.update(cx, |yumush, cx| { + yumush.go_to_message(message_id, window, cx) + }); + }, + ) + .flex() + .gap(px(6.)) + .px(px(8.)) + .py(px(4.)) + .rounded(px(6.)) + .text_size(text(12.)) + .child( + div() + .flex_shrink_0() + .font_weight(FontWeight::SEMIBOLD) + .child(name.clone()), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_color(palette.muted) + .child(body.clone()), + ) + })), + Anchor::TopRight, + ) + }) +} + pub fn actions( message: &Message, chat: &Chat, @@ -94,8 +409,10 @@ pub fn actions( let mine = me.is_some_and(|me| me.id == message.user_id); let editable = mine && !message.body.is_empty() && message.snippet.is_none(); let deletable = me.is_some_and(|me| chat.can_delete(message, me)); + let pinnable = me.is_some_and(|me| chat.can_pin(me)); let reportable = me.is_some_and(|me| me.id != message.user_id); let id = message.id.as_str(); + let armed = chat.pending_message_delete.as_deref() == Some(id); div() .flex() @@ -106,7 +423,7 @@ pub fn actions( .border_1() .border_color(palette.border) .bg(palette.panel) - .invisible() + .when(!armed, |this| this.invisible()) .group_hover(group, |style| style.visible()) .child(action( entity, @@ -116,6 +433,7 @@ pub fn actions( IconName::Reply, |yumush, id, window, cx| yumush.reply(id, window, cx), )) + .child(react_popover(message, entity, palette)) .children(editable.then(|| { action( entity, @@ -142,6 +460,20 @@ pub fn actions( IconName::ListChecks, |yumush, id, window, cx| yumush.start_select(id, window, cx), )) + .children(pinnable.then(|| { + action( + entity, + palette, + id, + if message.pinned { "Unpin" } else { "Pin" }, + if message.pinned { + IconName::PinOff + } else { + IconName::Pin + }, + |yumush, id, window, cx| yumush.toggle_pin(id, window, cx), + ) + })) .children(reportable.then(|| { action( entity, @@ -157,10 +489,14 @@ pub fn actions( entity, palette, id, - "Delete", + if armed { "Confirm" } else { "Delete" }, IconName::Trash, - |yumush, id, window, cx| yumush.delete_message(&id, window, cx), + |yumush, id, window, cx| yumush.request_message_delete(id, window, cx), ) + .when(armed, |this| { + this.text_color(palette.danger) + .bg(palette.danger.opacity(0.15)) + }) })) } @@ -190,6 +526,44 @@ pub fn report_bar( } impl Yumush { + pub(super) fn toggle_pin( + &mut self, + message_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let pinned = self + .chat + .messages + .iter() + .any(|message| message.id == message_id && message.pinned); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.pin(&message_id, !pinned).await { + notify_error(&this, cx, error); + } + }) + .detach(); + } + + pub(super) fn toggle_reaction( + &mut self, + message_id: String, + emoji: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.react(&message_id, &emoji).await { + notify_error(&this, cx, error); + } + }) + .detach(); + } + pub(super) fn start_report( &mut self, target: ReportTarget, @@ -247,7 +621,7 @@ fn action( tip: &'static str, icon: IconName, run: fn(&mut Yumush, String, &mut Window, &mut Context), -) -> impl IntoElement { +) -> Stateful
{ let entity = entity.clone(); let message_id = message_id.to_string(); diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs new file mode 100644 index 0000000..3710dba --- /dev/null +++ b/crates/client/src/gui/poll.rs @@ -0,0 +1,330 @@ +use std::collections::HashSet; + +use common::model::{Message, Poll, Rank, User}; +use gpui_kit::{ + Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, + Window, assets::IconName, component::Icon, div, px, relative, +}; + +use super::{Palette, Yumush, chat::Chat, clickable, notify_error, text}; + +pub fn voter_count(poll: &Poll) -> usize { + poll.options + .iter() + .flat_map(|option| &option.voter_ids) + .collect::>() + .len() +} + +fn my_positions(poll: &Poll, user_id: &str) -> Vec { + poll.options + .iter() + .enumerate() + .filter(|(_, option)| option.voter_ids.iter().any(|id| id == user_id)) + .map(|(position, _)| position as u32) + .collect() +} + +fn next_votes(poll: &Poll, user_id: &str, position: u32) -> Vec { + let mut mine = my_positions(poll, user_id); + if mine.contains(&position) { + mine.retain(|mine| *mine != position); + mine + } else if poll.multiple { + mine.push(position); + mine + } else { + vec![position] + } +} + +fn percent(count: usize, voters: usize) -> usize { + count * 100 / voters.max(1) +} + +pub enum PollMode<'a> { + Live(&'a Message), + Snapshot(&'a str), +} + +pub fn poll_card( + poll: &Poll, + mode: PollMode, + me: Option<&User>, + chat: &Chat, + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let voters = voter_count(poll); + let me_id = me.map(|me| me.id.as_str()); + let mine = me_id.map(|id| my_positions(poll, id)).unwrap_or_default(); + let (key, live) = match mode { + PollMode::Live(message) => (message.id.clone(), Some(message)), + PollMode::Snapshot(id) => (format!("snapshot_{id}"), None), + }; + let vote_id = live + .filter(|_| !poll.closed && me_id.is_some()) + .map(|message| message.id.clone()); + let close_id = live + .filter(|message| { + !poll.closed + && me.is_some_and(|me| { + me.id == message.user_id || chat.my_rank(me) >= Some(Rank::Moderator) + }) + }) + .map(|message| message.id.clone()); + + let rows = poll.options.iter().enumerate().map(|(position, option)| { + let count = option.voter_ids.len(); + let share = percent(count, voters); + let picked = mine.contains(&(position as u32)); + let next = me_id + .map(|id| next_votes(poll, id, position as u32)) + .unwrap_or_default(); + let entity = entity.clone(); + let id = format!("poll_option_{key}_{position}"); + match vote_id.clone() { + Some(message_id) => clickable(id, palette, move |window, cx| { + let next = next.clone(); + let message_id = message_id.clone(); + entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx)); + }), + None => div().id(id), + } + .relative() + .h(px(30.)) + .px(px(10.)) + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .rounded(px(6.)) + .overflow_hidden() + .border_1() + .border_color(if picked { + palette.accent + } else { + palette.border + }) + .child( + div() + .absolute() + .left_0() + .top_0() + .h_full() + .w(relative(share as f32 / 100.)) + .bg(palette.accent.opacity(0.18)), + ) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .min_w_0() + .children(picked.then(|| { + div() + .flex_shrink_0() + .text_color(palette.accent) + .child(Icon::new(IconName::Check).w(px(12.)).h(px(12.))) + })) + .child(div().min_w_0().truncate().child(option.text.clone())), + ) + .child( + div() + .flex_shrink_0() + .text_size(text(12.)) + .text_color(palette.muted) + .child(format!("{count} · {share}%")), + ) + }); + + let footer = div() + .flex() + .items_center() + .justify_between() + .text_size(text(12.)) + .text_color(palette.muted) + .child(match voters { + 1 => "1 voter".to_string(), + _ => format!("{voters} voters"), + }) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .children(poll.closed.then(|| "Closed")) + .children(close_id.map(|close_id| { + let close_entity = entity.clone(); + clickable( + format!("poll_close_{close_id}"), + palette, + move |window, cx| { + let close_id = close_id.clone(); + close_entity + .update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); + }, + ) + .px(px(6.)) + .py(px(2.)) + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .child("Close") + })), + ); + + div() + .flex() + .flex_col() + .gap(px(6.)) + .p(px(10.)) + .max_w(px(420.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .child(poll.question.clone()), + ) + .children(rows) + .child(footer) +} + +impl Yumush { + pub(super) fn poll_banner(&self, entity: &Entity, palette: Palette) -> Option
{ + let (message, poll) = self.chat.pins.iter().find_map(|pin| { + pin.poll + .as_ref() + .filter(|poll| !poll.closed) + .map(|poll| (pin, poll)) + })?; + let me = self.user.as_ref(); + let expanded = self.chat.poll_expanded; + let toggle = entity.clone(); + let jump = entity.clone(); + let message_id = message.id.clone(); + + Some( + div() + .flex() + .flex_col() + .gap(px(6.)) + .px(px(16.)) + .py(px(8.)) + .border_b_1() + .border_color(palette.border) + .bg(palette.panel) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child( + clickable("poll_banner_toggle", palette, move |_, cx| { + toggle.update(cx, |yumush, cx| { + yumush.chat.poll_expanded = !yumush.chat.poll_expanded; + cx.notify(); + }) + }) + .flex() + .flex_1() + .min_w_0() + .items_center() + .gap(px(8.)) + .text_size(text(12.)) + .child( + div() + .flex_shrink_0() + .text_color(palette.muted) + .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))), + ) + .child( + div() + .min_w_0() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .child(poll.question.clone()), + ) + .child( + div() + .flex_shrink_0() + .text_color(palette.muted) + .child(format!("{} votes", voter_count(poll))), + ) + .child( + div().flex_shrink_0().text_color(palette.muted).child( + Icon::new(if expanded { + IconName::ChevronUp + } else { + IconName::ChevronDown + }) + .w(px(14.)) + .h(px(14.)), + ), + ), + ) + .child( + clickable("poll_banner_jump", palette, move |window, cx| { + let message_id = message_id.clone(); + jump.update(cx, |yumush, cx| { + yumush.go_to_message(message_id, window, cx) + }); + }) + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::ArrowUpRight).w(px(14.)).h(px(14.))), + ), + ) + .children(expanded.then(|| { + poll_card( + poll, + PollMode::Live(message), + me, + &self.chat, + entity, + palette, + ) + })), + ) + } + + pub(super) fn vote( + &mut self, + message_id: String, + positions: Vec, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.vote(&message_id, positions).await { + notify_error(&this, cx, error); + } + }) + .detach(); + } + + pub(super) fn close_poll( + &mut self, + message_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.close_poll(&message_id).await { + notify_error(&this, cx, error); + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index f1e977a..2469483 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -3,12 +3,13 @@ use crate::gui::DAY_YEAR; use std::{collections::HashMap, sync::Arc}; use common::{ - model::{Rank, User}, + model::{Presence, Rank, User}, permission, }; use gpui_kit::{ - Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, IntoElement, - ParentElement, SharedString, Styled, Window, + Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, + InteractiveElement, IntoElement, ParentElement, SharedString, Stateful, + StatefulInteractiveElement, StyleRefinement, Styled, Window, assets::IconName, component::{ Icon, WindowExt, @@ -18,12 +19,12 @@ use gpui_kit::{ div, px, }; -use super::chat::{ReportTarget, View}; +use super::chat::{CardMenu, ReportTarget, View}; use super::message_actions::report_bar; use super::social::Relation; use super::{ Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, palette, - rank_tag, + pop_in, presence_color, rank_tag, swap_in, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -41,6 +42,26 @@ impl Removal { } } +pub(super) fn user_link( + id: impl Into, + user: Option<&User>, + entity: &Entity, + trigger: impl IntoElement, +) -> AnyElement { + match user { + Some(user) => profile_popover( + id, + Anchor::TopLeft, + user, + entity, + div().min_w_0().cursor_pointer().child(trigger), + ) + .trigger_style(StyleRefinement::default().min_w_0()) + .into_any_element(), + None => trigger.into_any_element(), + } +} + pub(super) fn profile_popover( id: impl Into, anchor: Anchor, @@ -55,7 +76,12 @@ pub(super) fn profile_popover( Popover::new(id) .anchor(anchor) .appearance(false) - .on_open_change(move |_, _, cx| notify_entity.update(cx, |_, cx| cx.notify())) + .on_open_change(move |_, _, cx| { + notify_entity.update(cx, |yumush, cx| { + yumush.chat.card_menu = CardMenu::Main; + cx.notify() + }) + }) .trigger(Trigger::new(trigger)) .content(move |_, _, cx| { let yumush = entity.read(cx); @@ -64,6 +90,8 @@ pub(super) fn profile_popover( actor: yumush.actor_rank(), target: yumush.chat.rank_of(&user), relation: yumush.relation(&user.id), + card_menu: yumush.chat.card_menu, + presence: yumush.presence_of(&user.id), confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()), reporting: yumush.chat.report == Some(ReportTarget::User(user.id.clone())), reason: yumush.chat.report_reason.clone(), @@ -75,7 +103,11 @@ pub(super) fn profile_popover( user: user.clone(), }; - card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars) + pop_in( + "profile_card", + card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars), + anchor, + ) }) } @@ -85,6 +117,8 @@ struct Card { actor: Option, target: Option, relation: Relation, + card_menu: CardMenu, + presence: Presence, confirming: bool, reporting: bool, reason: Entity, @@ -161,7 +195,14 @@ impl Card { .as_ref() .is_some_and(|viewer| viewer.id == self.user.id); let rows = if is_self { - self_rows(&self.others, entity, &popover, palette) + self_rows( + &self.others, + self.card_menu, + self.presence, + entity, + &popover, + palette, + ) } else { let mut rows = self.social_rows(entity, &popover, palette); rows.extend(self.moderation_rows(entity, &popover, palette)); @@ -193,6 +234,16 @@ impl Card { ) .children(rank_tag(self.target, palette)), ) + .children((!is_self).then(|| { + div() + .flex() + .items_center() + .gap(px(6.)) + .text_size(text(12.)) + .text_color(palette.muted) + .child(presence_dot(self.presence, palette)) + .child(self.presence.label()) + })) .children((!self.user.status.is_empty()).then(|| { div() .text_size(text(12.)) @@ -210,7 +261,11 @@ impl Card { .then(|| report_bar(&self.reason, entity, palette)), ) .children(divider) - .children(rows) + .child(swap_in( + ("profile_rows", self.card_menu as usize), + div().flex().flex_col().gap(px(10.)).children(rows), + self.card_menu != CardMenu::Main, + )) } fn moderation_rows( @@ -305,41 +360,46 @@ impl Card { fn self_rows( others: &[(String, String)], + card_menu: CardMenu, + presence: Presence, entity: &Entity, popover: &Entity, palette: Palette, ) -> Vec { - let mut rows: Vec = others - .iter() - .map(|(user_id, username)| { - let user_id = user_id.clone(); - menu_row( - format!("switch_{user_id}"), - username.clone(), - IconName::ArrowLeft, - palette.text, - palette, - yumush_action(entity, popover, move |yumush, window, cx| { - yumush.switch_account(user_id.clone(), window, cx) - }), - ) - .into_any_element() - }) - .collect(); - rows.push( + match card_menu { + CardMenu::Main => main_self_rows(presence, entity, popover, palette), + CardMenu::Accounts => accounts_rows(others, entity, popover, palette), + CardMenu::Presence => presence_rows(entity, palette), + } +} + +fn main_self_rows( + presence: Presence, + entity: &Entity, + popover: &Entity, + palette: Palette, +) -> Vec { + vec![ + presence_row( + "profile_presence", + presence, + palette, + card_menu_action(entity, CardMenu::Presence), + ) + .child(div().flex_1()) + .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.))) + .into_any_element(), menu_row( - "profile_add_account", - "Add account", - IconName::UserPlus, + "profile_accounts", + "Accounts", + IconName::CircleUser, palette.text, palette, - yumush_action(entity, popover, |yumush, window, cx| { - yumush.add_account(window, cx) - }), + card_menu_action(entity, CardMenu::Accounts), ) + .child(div().flex_1()) + .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.))) .into_any_element(), - ); - rows.extend([ menu_row( "profile_settings", "Settings", @@ -362,10 +422,124 @@ fn self_rows( }), ) .into_any_element(), - ]); + ] +} + +fn accounts_rows( + others: &[(String, String)], + entity: &Entity, + popover: &Entity, + palette: Palette, +) -> Vec { + let accounts = others.iter().map(|(user_id, username)| { + let user_id = user_id.clone(); + menu_row( + format!("switch_{user_id}"), + username.clone(), + IconName::CircleUser, + palette.text, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.switch_account(user_id.clone(), window, cx) + }), + ) + }); + + vec![ + menu_row( + "profile_accounts_back", + "Accounts", + IconName::ArrowLeft, + palette.muted, + palette, + card_menu_action(entity, CardMenu::Main), + ) + .into_any_element(), + div() + .id("profile_accounts") + .max_h(px(180.)) + .overflow_y_scroll() + .flex() + .flex_col() + .children(accounts) + .into_any_element(), + menu_row( + "profile_add_account", + "Add account", + IconName::UserPlus, + palette.text, + palette, + yumush_action(entity, popover, |yumush, window, cx| { + yumush.add_account(window, cx) + }), + ) + .into_any_element(), + ] +} + +fn presence_rows(entity: &Entity, palette: Palette) -> Vec { + let mut rows = vec![ + menu_row( + "profile_presence_back", + "Status", + IconName::ArrowLeft, + palette.muted, + palette, + card_menu_action(entity, CardMenu::Main), + ) + .into_any_element(), + ]; + + rows.extend(Presence::ALL.into_iter().map(|presence| { + presence_row( + format!("presence_{}", presence.as_str()), + presence, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_presence(presence, window, cx) + }), + ) + .into_any_element() + })); + rows } +fn card_menu_action( + entity: &Entity, + menu: CardMenu, +) -> impl Fn(&mut Window, &mut App) + 'static { + entity_action(entity, move |yumush, _, cx| { + yumush.chat.card_menu = menu; + cx.notify(); + }) +} + +fn presence_dot(presence: Presence, palette: Palette) -> Div { + div() + .size(px(8.)) + .rounded_full() + .bg(presence_color(presence, palette)) +} + +fn presence_row( + id: impl Into, + presence: Presence, + palette: Palette, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + clickable(id, palette, on_click) + .h(px(30.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .text_color(palette.text) + .child(presence_dot(presence, palette)) + .child(presence.label()) +} + fn yumush_action( entity: &Entity, popover: &Entity, @@ -409,7 +583,7 @@ fn menu_row( color: Hsla, palette: Palette, on_click: impl Fn(&mut Window, &mut App) + 'static, -) -> impl IntoElement { +) -> Stateful
{ clickable(id, palette, on_click) .h(px(30.)) .px(px(8.)) @@ -500,6 +674,28 @@ impl Yumush { .detach(); } + pub(super) fn set_presence( + &mut self, + presence: Presence, + window: &mut Window, + cx: &mut Context, + ) { + if let Some(me) = &self.user { + self.chat.presences.insert(me.id.clone(), presence); + } + self.chat.card_menu = CardMenu::Main; + cx.notify(); + + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.update_presence(presence).await { + super::notify_error(&this, cx, error); + } + }) + .detach(); + } + pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context) { self.chat.pending_user_delete = Some(user_id.to_string()); cx.notify(); diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index c7ac958..c70e698 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -6,7 +6,7 @@ use gpui_kit::{ AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window, assets::IconName, - component::{Icon, input::InputState}, + component::{Icon, input::InputState, switch::Switch}, div, prelude::FluentBuilder as _, px, transparent_black, @@ -118,6 +118,21 @@ impl Yumush { Yumush::set_font_size, ), ), + row( + "Close to tray", + Switch::new("close_to_tray_switch") + .checked(self.settings.close_to_tray) + .on_change({ + let entity = entity.clone(); + move |checked, _, cx| { + let checked = *checked; + entity.update(cx, |yumush, cx| { + yumush.settings.close_to_tray = checked; + yumush.commit_settings(cx); + }) + } + }), + ), ], ) .into_any_element(), diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index cbf749a..255f99a 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -1,17 +1,18 @@ use super::text; use common::{ - model::{CommunityKind, Invitation, Role, User}, + model::{CommunityKind, Invitation, Role, Unread, User}, permission, validate::validate_community_name, }; use gpui_kit::{ - Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, - ParentElement, StatefulInteractiveElement, Styled, Window, + Anchor, AnimationExt, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, + IntoElement, MouseButton, ParentElement, StatefulInteractiveElement, Styled, Window, assets::IconName, component::{ Icon, input::{Input, InputState}, menu::{ContextMenuExt, PopupMenu, PopupMenuItem}, + popover::Popover, }, div, prelude::FluentBuilder as _, @@ -19,15 +20,19 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Yumush, avatar, + Palette, Tooltip as _, Trigger, Yumush, avatar, chat::{View, create_community}, clickable, community_icon, community_name, entity_action, hoverable, hoverable_with, - input_dialog, + input_dialog, motion, pop_in, presence_avatar, profile::profile_popover, settings_page::{segment, segment_track}, social::Relation, + voice_stats, }; +const SIDEBAR_WIDTH: f32 = 232.; +const SIDEBAR_COLLAPSED_WIDTH: f32 = 48.; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SidebarTab { Messages, @@ -41,6 +46,52 @@ impl Yumush { query: &str, palette: Palette, ) -> impl IntoElement { + let collapsed = self.chat.sidebar_collapsed; + let (from, to, id) = match collapsed { + true => (SIDEBAR_WIDTH, SIDEBAR_COLLAPSED_WIDTH, "sidebar_collapsing"), + false => (SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_WIDTH, "sidebar_expanding"), + }; + let content = match collapsed { + true => self.collapsed_sidebar(entity, palette).into_any_element(), + false => self.expanded_sidebar(entity, query, palette), + }; + + div() + .h_full() + .flex_shrink_0() + .overflow_hidden() + .child(content) + .with_animation(id, motion(), move |sidebar, delta| { + sidebar.w(px(from + (to - from) * delta)) + }) + } + + fn collapsed_sidebar(&self, entity: &Entity, palette: Palette) -> Div { + div() + .h_full() + .w(px(SIDEBAR_COLLAPSED_WIDTH)) + .flex() + .flex_col() + .items_center() + .justify_between() + .py(px(12.)) + .child(self.collapse_button(entity, palette)) + .child( + div() + .flex() + .flex_col() + .items_center() + .gap(px(10.)) + .children(self.voice_dot(entity, palette)) + .children( + self.user + .as_ref() + .map(|user| self.account_trigger(entity, user, false, palette)), + ), + ) + } + + fn expanded_sidebar(&self, entity: &Entity, query: &str, palette: Palette) -> AnyElement { let (top, list) = match self.chat.tab { SidebarTab::Messages => ( Some(input_box(&self.chat.search_input, palette)), @@ -55,8 +106,7 @@ impl Yumush { div() .h_full() - .w(px(232.)) - .flex_shrink_0() + .w(px(SIDEBAR_WIDTH)) .flex() .flex_col() .py(px(12.)) @@ -66,7 +116,9 @@ impl Yumush { div() .flex() .items_center() - .child(self.tab_bar(entity, palette)), + .gap(px(6.)) + .child(self.tab_bar(entity, palette)) + .child(self.collapse_button(entity, palette)), ) .children(top) .child( @@ -77,21 +129,186 @@ impl Yumush { .overflow_y_scroll() .child(list), ) + .children(self.voice_panel(entity, palette)) .children(self.account_row(entity, palette)) + .into_any_element() + } + + fn voice_panel(&self, entity: &Entity, palette: Palette) -> Option { + let community = self.chat.voice_room()?; + let direct = matches!(community.kind, CommunityKind::Direct { .. }); + let go_id = community.id.clone(); + let tone = voice_stats::quality(&self.chat.voice_samples) + .map_or(palette.ok, |quality| quality.color(palette)); + let stats_entity = entity.clone(); + + let panel = div() + .flex() + .items_center() + .gap(px(4.)) + .p(px(6.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.ok.opacity(0.35)) + .bg(palette.ok.opacity(0.08)) + .child( + clickable( + "voice_panel_go", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.go_to_community(go_id.clone(), direct, window, cx) + }), + ) + .tip("Go to call") + .flex_1() + .min_w_0() + .px(px(4.)) + .py(px(2.)) + .rounded(px(6.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + Icon::new(IconName::AudioLines) + .w(px(16.)) + .h(px(16.)) + .text_color(tone), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(text(12.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.ok) + .child("Voice connected"), + ) + .child( + div() + .truncate() + .text_size(text(11.)) + .text_color(palette.muted) + .child(community_name(community).to_string()), + ), + ), + ) + .child(icon_button( + "voice_panel_leave".to_string(), + palette, + IconName::PhoneOff, + "Leave call", + entity_action(entity, |yumush, _, cx| { + yumush.end_voice(cx); + cx.notify(); + }), + )); + + Some( + Popover::new("voice_stats") + .anchor(Anchor::BottomLeft) + .mouse_button(MouseButton::Right) + .appearance(false) + .trigger(Trigger::new(panel)) + .content(move |_, _, cx| { + let samples = &stats_entity.read(cx).chat.voice_samples; + pop_in( + "voice_stats_card", + voice_stats::stats_card(samples, palette), + Anchor::BottomLeft, + ) + }), + ) + } + + fn voice_dot(&self, entity: &Entity, palette: Palette) -> Option { + let community = self.chat.voice_room()?; + let direct = matches!(community.kind, CommunityKind::Direct { .. }); + let go_id = community.id.clone(); + + Some( + clickable( + "voice_panel_go_collapsed", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.go_to_community(go_id.clone(), direct, window, cx) + }), + ) + .tip("Go to call") + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .border_1() + .border_color(palette.ok.opacity(0.35)) + .bg(palette.ok.opacity(0.08)) + .child( + Icon::new(IconName::AudioLines) + .w(px(14.)) + .h(px(14.)) + .text_color(palette.ok), + ), + ) + } + + pub(super) fn go_to_community( + &mut self, + community_id: String, + direct: bool, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.view == View::Chat && self.chat.is_selected(&community_id) { + return; + } + self.chat.tab = if direct { + SidebarTab::Messages + } else { + SidebarTab::Communities + }; + self.show_view(View::Chat, window, cx); + self.select_community(community_id, window, cx); + } + + fn collapse_button(&self, entity: &Entity, palette: Palette) -> AnyElement { + let (icon, tip) = match self.chat.sidebar_collapsed { + true => (IconName::PanelLeftOpen, "Expand"), + false => (IconName::PanelLeftClose, "Collapse"), + }; + + icon_button( + "sidebar_collapse".to_string(), + palette, + icon, + tip, + entity_action(entity, |yumush, _, cx| { + yumush.chat.sidebar_collapsed = !yumush.chat.sidebar_collapsed; + cx.notify(); + }), + ) } fn tab_bar(&self, entity: &Entity, palette: Palette) -> impl IntoElement { - let requests = !self.chat.friends.incoming.is_empty() || !self.chat.invitations.is_empty(); + let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32; + let direct = self.chat.unread_total(false); let tabs = [ ( SidebarTab::Communities, "Communities", - self.chat.has_unread(false), + self.chat.unread_total(true), ), ( SidebarTab::Messages, "Messages", - requests || self.chat.has_unread(true), + Unread { + messages: direct.messages + requests, + mentions: direct.mentions + requests, + ..direct + }, ), ]; @@ -113,7 +330,7 @@ impl Yumush { .gap(px(6.)) .text_size(text(12.)) .child(label) - .children(alert.then(|| dot(palette))); + .children(badge(palette, false, Some(&alert))); match tab { SidebarTab::Communities => item @@ -135,6 +352,7 @@ impl Yumush { .flex() .flex_col() .gap(px(14.)) + .child(self.notes_row(entity, palette)) .children(found.map(|user| self.found_row(entity, user, palette))) .children( query @@ -156,6 +374,30 @@ impl Yumush { )) } + fn notes_row(&self, entity: &Entity, palette: Palette) -> AnyElement { + let notes = self.chat.notes(); + let active = notes.is_some_and(|notes| self.chat.is_selected(¬es.id)); + let unread = notes.and_then(|notes| self.chat.unread.get(¬es.id)); + let open = entity.clone(); + + hoverable_with( + "notes", + entry( + palette, + active, + Icon::new(IconName::Bookmark) + .w(px(20.)) + .h(px(20.)) + .text_color(palette.accent), + "Notes", + badge(palette, false, unread), + ), + palette.accent.opacity(0.1), + ) + .on_click(move |_, window, cx| open.update(cx, |yumush, cx| yumush.open_notes(window, cx))) + .into_any_element() + } + fn is_listed(&self, user_id: &str) -> bool { self.chat .friends @@ -180,7 +422,8 @@ impl Yumush { .filter(|community| matches!(community.kind, CommunityKind::Group)) .map(|community| { let active = self.chat.is_selected(&community.id); - let alert = self.chat.unread.contains(&community.id); + let muted = self.chat.muted.contains(&community.id); + let unread = self.chat.unread.get(&community.id); let can_leave = !active || permission::can_leave(self.actor_rank()); let community_id = community.id.clone(); let select = entity.clone(); @@ -199,7 +442,7 @@ impl Yumush { &self.chat.avatars, ), community.name.clone(), - alert.then(|| dot(palette).into_any_element()), + badge(palette, muted, unread), ), themed.accent.opacity(0.1), ) @@ -208,7 +451,12 @@ impl Yumush { yumush.select_community(community_id.clone(), window, cx) }) }) - .context_menu(community_menu(entity, community.id.clone(), can_leave)) + .context_menu(community_menu( + entity, + community.id.clone(), + can_leave, + muted, + )) .into_any_element() }), ) @@ -245,7 +493,8 @@ impl Yumush { .filter(|community| matches_query(community_name(community), query)) .map(|community| { let active = self.chat.is_selected(&community.id); - let alert = self.chat.unread.contains(&community.id); + let muted = self.chat.muted.contains(&community.id); + let unread = self.chat.unread.get(&community.id); let community_id = community.id.clone(); let select = entity.clone(); @@ -255,9 +504,9 @@ impl Yumush { entry( themed, active, - community_icon(palette, community, px(20.), text(10.), &self.chat.avatars), + self.community_badge(community, px(20.), text(10.), palette), community_name(community).to_string(), - alert.then(|| dot(palette).into_any_element()), + badge(palette, muted, unread), ), themed.accent.opacity(0.1), ) @@ -266,6 +515,7 @@ impl Yumush { yumush.select_community(community_id.clone(), window, cx) }) }) + .context_menu(direct_menu(entity, community.id.clone(), muted)) .into_any_element() }) .collect() @@ -288,7 +538,12 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + presence_avatar( + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + self.presence_of(&user.id), + px(20.), + palette, + ), user.username.clone(), Vec::new(), ), @@ -351,7 +606,12 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + presence_avatar( + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + self.presence_of(&user.id), + px(20.), + palette, + ), user.username.clone(), trailing, ) @@ -365,7 +625,12 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + presence_avatar( + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + self.presence_of(&user.id), + px(20.), + palette, + ), user.username.clone(), [ icon_button( @@ -397,7 +662,12 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + presence_avatar( + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), + self.presence_of(&user.id), + px(20.), + palette, + ), user.username.clone(), [icon_button( format!("cancel_friend_{}", user.id), @@ -459,68 +729,13 @@ impl Yumush { fn account_row(&self, entity: &Entity, palette: Palette) -> Option { let user = self.user.as_ref()?; - let status = if self.connected { - palette.ok - } else { - palette.danger - }; - Some( div() .h(px(36.)) .flex() .items_center() .gap(px(4.)) - .child( - profile_popover( - "account_profile", - Anchor::BottomLeft, - user, - entity, - hoverable( - "account_trigger", - div() - .flex() - .items_center() - .h(px(36.)) - .gap(px(8.)) - .px(px(6.)) - .rounded(px(6.)) - .child( - div() - .relative() - .child(avatar( - palette, - user, - px(24.), - text(12.), - &self.chat.avatars, - )) - .child( - div() - .absolute() - .right(px(-2.)) - .bottom(px(-2.)) - .size(px(10.)) - .rounded_full() - .border_2() - .border_color(palette.window) - .bg(status), - ), - ) - .child( - div() - .flex_1() - .min_w_0() - .font_weight(FontWeight::MEDIUM) - .child(user.username.clone()), - ), - palette, - ), - ) - .flex_1() - .min_w_0(), - ) + .child(self.account_trigger(entity, user, true, palette)) .children(self.is_builder().then(|| { icon_button( "builder_button".to_string(), @@ -536,6 +751,48 @@ impl Yumush { ) } + fn account_trigger( + &self, + entity: &Entity, + user: &User, + named: bool, + palette: Palette, + ) -> impl IntoElement { + profile_popover( + "account_profile", + Anchor::BottomLeft, + user, + entity, + hoverable( + "account_trigger", + div() + .flex() + .items_center() + .h(px(36.)) + .gap(px(8.)) + .px(px(6.)) + .rounded(px(6.)) + .child(presence_avatar( + avatar(palette, user, px(24.), text(12.), &self.chat.avatars), + self.presence_of(&user.id), + px(24.), + palette, + )) + .when(named, |trigger| { + trigger.child( + div() + .flex_1() + .min_w_0() + .font_weight(FontWeight::MEDIUM) + .child(user.username.clone()), + ) + }), + palette, + ), + ) + .when(named, |trigger| trigger.flex_1().min_w_0()) + } + fn set_sidebar_tab(&mut self, tab: SidebarTab, window: &mut Window, cx: &mut Context) { self.chat.tab = tab; if tab == SidebarTab::Messages { @@ -557,10 +814,73 @@ impl Yumush { } } +pub(super) fn badge(palette: Palette, muted: bool, unread: Option<&Unread>) -> Option { + if muted { + return Some( + div() + .text_color(palette.muted) + .child(Icon::new(IconName::BellOff).w(px(12.)).h(px(12.))) + .into_any_element(), + ); + } + let unread = unread.filter(|unread| unread.messages > 0)?; + let (fill, ink) = if unread.mentions > 0 { + (palette.accent, palette.on_accent) + } else { + (palette.muted, palette.window) + }; + let count = match unread.messages { + 1..=99 => unread.messages.to_string(), + _ => "99+".to_string(), + }; + Some( + div() + .h(px(16.)) + .min_w(px(16.)) + .px(px(4.)) + .flex() + .items_center() + .justify_center() + .rounded_full() + .text_size(text(10.)) + .bg(fill) + .text_color(ink) + .child(count) + .into_any_element(), + ) +} + +fn mute_item( + menu: PopupMenu, + entity: &Entity, + community_id: String, + muted: bool, +) -> PopupMenu { + let entity = entity.clone(); + let label = if muted { "Unmute" } else { "Mute" }; + + menu.item(PopupMenuItem::new(label).on_click(move |_, _, cx| { + entity.update(cx, |yumush, cx| { + yumush.toggle_community_mute(community_id.clone(), cx) + }) + })) +} + +fn direct_menu( + entity: &Entity, + community_id: String, + muted: bool, +) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { + let entity = entity.clone(); + + move |menu, _, _| mute_item(menu, &entity, community_id.clone(), muted) +} + fn community_menu( entity: &Entity, community_id: String, can_leave: bool, + muted: bool, ) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { let entity = entity.clone(); @@ -585,6 +905,7 @@ fn community_menu( }) }), ); + let menu = mute_item(menu, &entity, community_id.clone(), muted); if !can_leave { return menu; @@ -631,7 +952,7 @@ fn new_community_menu( } } -fn input_box(input: &Entity, palette: Palette) -> Div { +pub(super) fn input_box(input: &Entity, palette: Palette) -> Div { div() .h(px(30.)) .px(px(10.)) @@ -691,10 +1012,6 @@ fn entry( .children(trailing) } -fn dot(palette: Palette) -> Div { - div().size(px(6.)).rounded_full().bg(palette.alert) -} - fn icon_button( id: String, palette: Palette, diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs index 254074d..e7df1a1 100644 --- a/crates/client/src/gui/snippet.rs +++ b/crates/client/src/gui/snippet.rs @@ -6,7 +6,7 @@ use gpui_kit::{ relative, }; -use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view}; +use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link}; pub fn snippet_card( message: &Message, @@ -62,7 +62,12 @@ fn snippet_row( div() .flex() .gap(px(8.)) - .child(avatar(palette, &user, px(20.), text(10.), &chat.avatars)) + .child(user_link( + format!("snippet_avatar_{}", item.id), + Some(&user), + entity, + avatar(palette, &user, px(20.), text(10.), &chat.avatars), + )) .child( div() .flex_1() @@ -75,12 +80,15 @@ fn snippet_row( .flex() .items_center() .gap(px(6.)) - .child( + .child(user_link( + format!("snippet_name_{}", item.id), + Some(&user), + entity, div() .font_weight(FontWeight::SEMIBOLD) .text_color(palette.tinted(&item.user_id)) .child(item.username.clone()), - ) + )) .child( div() .text_size(text(11.)) @@ -101,6 +109,16 @@ fn snippet_row( &chat.media, entity, palette, - )), + )) + .children(item.poll.as_ref().map(|poll| { + poll::poll_card( + poll, + poll::PollMode::Snapshot(&item.id), + None, + chat, + entity, + palette, + ) + })), ) } diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index 81e0fa8..5cc1649 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -111,7 +111,7 @@ impl Yumush { .iter() .filter_map(|community| match &community.kind { CommunityKind::Direct { peer } => Some(peer), - CommunityKind::Group => None, + CommunityKind::Group | CommunityKind::Notes => None, }), ); let avatar_ids: Vec = users @@ -132,18 +132,22 @@ impl Yumush { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { - let (friends, invitations) = - match (network.friends().await, network.invitations().await) { - (Ok(friends), Ok(invitations)) => (friends, invitations), - (Err(error), _) | (_, Err(error)) => { - notify_error(&this, cx, error); - return; - } - }; + let (friends, invitations, presences) = match ( + network.friends().await, + network.invitations().await, + network.read_presences().await, + ) { + (Ok(friends), Ok(invitations), Ok(presences)) => (friends, invitations, presences), + (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => { + notify_error(&this, cx, error); + return; + } + }; let _ = this.update(cx, |yumush, cx| { yumush.chat.friends = friends; yumush.chat.invitations = invitations; + yumush.chat.presences = presences.into_iter().collect(); yumush.request_social_avatars(cx); cx.notify(); }); @@ -192,6 +196,17 @@ impl Yumush { } } + pub(super) fn open_notes(&mut self, window: &mut Window, cx: &mut Context) { + if let Some(notes) = self.chat.notes() { + let community_id = notes.id.clone(); + self.select_community(community_id, window, cx); + return; + } + let network = self.network.clone(); + + spawn_community(window, cx, async move { network.open_notes().await }); + } + pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs new file mode 100644 index 0000000..5f76371 --- /dev/null +++ b/crates/client/src/gui/voice_note.rs @@ -0,0 +1,287 @@ +use std::{ + rc::Rc, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; + +use common::constant::VOICE_SAMPLE_RATE; +use gpui_kit::{ + App, Context, Div, Entity, InteractiveElement, IntoElement, MouseButton, ParentElement, Styled, + Task, Window, + assets::IconName, + component::{Icon, WindowExt, notification::Notification}, + div, px, +}; +use rtrb::{Consumer, RingBuffer}; + +use super::{ + Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, media_view::time_text, + notify_error, primary_button, text, +}; +use crate::{ + media::voice_note::{self, BARS}, + voice::{ + Playback, + audio::{self, Audio}, + }, +}; + +const TICK: Duration = Duration::from_millis(100); +const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize; +const SLOT_WIDTH: f32 = 5.; +const BAR_WIDTH: f32 = 3.; +const BAR_MIN: f32 = 2.; +const BAR_MAX: f32 = 24.; + +#[derive(Default)] +pub enum VoiceNote { + #[default] + Idle, + Recording { + started: Instant, + _audio: Audio, + consumer: Consumer, + samples: Vec, + levels: Vec, + _tick: Task<()>, + }, +} + +pub fn bars( + levels: &[f32], + progress: f32, + palette: Palette, + on_pick: impl Fn(usize, &mut Window, &mut App) + 'static, +) -> Div { + let on_pick = Rc::new(on_pick); + let offset = BARS - levels.len().min(BARS); + div() + .flex_1() + .h(px(BAR_MAX)) + .flex() + .items_center() + .children((0..BARS).map(|index| { + let level = index + .checked_sub(offset) + .and_then(|slot| levels.get(slot)) + .copied() + .unwrap_or(0.); + let color = if (index as f32) < progress * BARS as f32 { + palette.accent + } else { + palette.muted + }; + let (down, drag) = (on_pick.clone(), on_pick.clone()); + div() + .w(px(SLOT_WIDTH)) + .h_full() + .flex() + .items_center() + .justify_center() + .on_mouse_down(MouseButton::Left, move |_, window, cx| { + down(index, window, cx) + }) + .on_mouse_move(move |event, window, cx| { + if event.pressed_button == Some(MouseButton::Left) { + drag(index, window, cx); + } + }) + .child( + div() + .w(px(BAR_WIDTH)) + .h(px((BAR_MAX * level).max(BAR_MIN))) + .rounded(px(BAR_WIDTH / 2.)) + .bg(color), + ) + })) +} + +pub fn recording_row( + started: Instant, + levels: &[f32], + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let cancel = entity.clone(); + let send = entity.clone(); + + div() + .min_h(px(40.)) + .pl(px(4.)) + .pr(px(4.)) + .py(px(4.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .child( + clickable("cancel_voice_note", palette, move |_, cx| { + cancel.update(cx, |yumush, cx| yumush.cancel_voice_note(cx)) + }) + .tip("Cancel") + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::X).w(px(16.)).h(px(16.))), + ) + .child( + div() + .flex_1() + .flex() + .items_center() + .gap(px(6.)) + .text_size(text(13.)) + .text_color(palette.text) + .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.))) + .child(time_text(started.elapsed())) + .child(bars(levels, 1., palette, |_, _, _| {})), + ) + .child( + primary_button("send_voice_note", palette, move |window, cx| { + send.update(cx, |yumush, cx| yumush.send_voice_note(window, cx)) + }) + .tip("Send") + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .child(Icon::new(IconName::ArrowUp).w(px(14.)).h(px(14.))), + ) +} + +pub fn mic_button(entity: &Entity, palette: Palette) -> impl IntoElement { + let entity = entity.clone(); + + clickable("voice_note_button", palette, move |window, cx| { + entity.update(cx, |yumush, cx| yumush.start_voice_note(window, cx)) + }) + .tip("Voice message") + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Mic).w(px(16.)).h(px(16.))) +} + +impl Yumush { + fn start_voice_note(&mut self, window: &mut Window, cx: &mut Context) { + if !matches!(self.chat.voice_state, VoiceState::Off) { + window.push_notification(Notification::error("Leave voice call first"), cx); + return; + } + let (producer, consumer) = RingBuffer::new(RING_SAMPLES); + let capture = Arc::new(Mutex::new(producer)); + let (_, silent) = RingBuffer::new(1); + let playback: Playback = Arc::new(Mutex::new(silent)); + let audio = audio::start(Some(capture), playback, self.settings.voice.choice.clone()); + let tick = cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(TICK).await; + if this + .update(cx, |yumush, cx| yumush.tick_voice_note(cx)) + .is_err() + { + break; + } + } + }); + self.chat.media.voice_note = VoiceNote::Recording { + started: Instant::now(), + _audio: audio, + consumer, + samples: Vec::new(), + levels: Vec::new(), + _tick: tick, + }; + cx.notify(); + } + + fn tick_voice_note(&mut self, cx: &mut Context) { + if let VoiceNote::Recording { + consumer, + samples, + levels, + .. + } = &mut self.chat.media.voice_note + { + let start = samples.len(); + while let Ok(sample) = consumer.pop() { + samples.push(sample); + } + levels.push(voice_note::level(&samples[start..])); + if levels.len() > BARS { + levels.remove(0); + } + } + cx.notify(); + } + + fn cancel_voice_note(&mut self, cx: &mut Context) { + self.chat.media.voice_note = VoiceNote::Idle; + cx.notify(); + } + + fn send_voice_note(&mut self, window: &mut Window, cx: &mut Context) { + let VoiceNote::Recording { + mut consumer, + mut samples, + .. + } = std::mem::take(&mut self.chat.media.voice_note) + else { + return; + }; + while let Ok(sample) = consumer.pop() { + samples.push(sample); + } + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + let maximum = self + .server + .as_ref() + .map(|settings| settings.max_attachment_bytes); + cx.notify(); + + cx.spawn_in(window, async move |this, cx| { + let Some(path) = cx + .background_executor() + .spawn(async move { voice_note::save(&samples) }) + .await + else { + return; + }; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.uploading += 1; + cx.notify(); + }); + let uploaded = network + .upload_attachment(&community_id, path, maximum) + .await; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.uploading -= 1; + cx.notify(); + }); + let attachment = match uploaded { + Ok(attachment) => attachment, + Err(error) => return notify_error(&this, cx, error), + }; + if let Err(error) = network + .create_message(&community_id, "", vec![attachment.id], None) + .await + { + notify_error(&this, cx, error); + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs new file mode 100644 index 0000000..b9df84c --- /dev/null +++ b/crates/client/src/gui/voice_stats.rs @@ -0,0 +1,209 @@ +use std::collections::VecDeque; + +use gpui_kit::{ + Div, FontWeight, Hsla, ParentElement, Styled, div, hsla, prelude::FluentBuilder as _, px, +}; + +use super::{Palette, text}; +use crate::voice::VoiceSample; + +pub const SAMPLE_HISTORY: usize = 60; +const GRAPH_HEIGHT: f32 = 32.; +const PING_SCALE: f32 = 150.; +const LOSS_SCALE: f32 = 10.; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Quality { + Good, + Fair, + Poor, +} + +impl Quality { + pub fn of(sample: &VoiceSample) -> Self { + let loss = sample.traffic.loss * 100.; + let jitter = sample.traffic.jitter_ms; + if sample.ping_ms < 100. && loss < 2. && jitter < 30. { + Self::Good + } else if sample.ping_ms < 200. && loss < 8. && jitter < 60. { + Self::Fair + } else { + Self::Poor + } + } + + fn label(self) -> &'static str { + match self { + Self::Good => "Good", + Self::Fair => "Fair", + Self::Poor => "Poor", + } + } + + pub fn color(self, palette: Palette) -> Hsla { + match self { + Self::Good => palette.ok, + Self::Fair => hsla(0.11, 0.85, 0.55, 1.), + Self::Poor => palette.danger, + } + } +} + +pub fn quality(samples: &VecDeque) -> Option { + samples.back().map(Quality::of) +} + +pub fn stats_card(samples: &VecDeque, palette: Palette) -> Div { + let latest = samples.back(); + let value = |format: fn(&VoiceSample) -> String| latest.map_or("…".to_string(), format); + let tiles = [ + ("Ping", value(|sample| format!("{:.0} ms", sample.ping_ms))), + ( + "Jitter", + value(|sample| format!("{:.0} ms", sample.traffic.jitter_ms)), + ), + ( + "Loss", + value(|sample| format!("{:.1} %", sample.traffic.loss * 100.)), + ), + ( + "Buffer", + value(|sample| format!("{:.0} ms", sample.traffic.buffer_ms)), + ), + ( + "Upload", + value(|sample| format!("{:.0} kbps", sample.traffic.up_kbps)), + ), + ( + "Download", + value(|sample| format!("{:.0} kbps", sample.traffic.down_kbps)), + ), + ]; + + div() + .w(px(280.)) + .p(px(14.)) + .flex() + .flex_col() + .gap(px(12.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .shadow_lg() + .child( + div() + .flex() + .items_center() + .justify_between() + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text) + .child("Connection"), + ) + .children(latest.map(|sample| { + let quality = Quality::of(sample); + let color = quality.color(palette); + div() + .px(px(8.)) + .py(px(2.)) + .rounded_full() + .bg(color.opacity(0.15)) + .text_size(text(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(color) + .child(quality.label()) + })), + ) + .child( + div() + .flex() + .flex_wrap() + .gap(px(6.)) + .children(tiles.map(|(label, value)| tile(label, value, palette))), + ) + .child(graph( + "Ping", + samples, + |sample| sample.ping_ms / PING_SCALE, + palette, + )) + .child(graph( + "Loss", + samples, + |sample| sample.traffic.loss * 100. / LOSS_SCALE, + palette, + )) + .children(latest.map(|sample| { + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child(format!("Opus · 48 kHz · {} kbps", sample.bitrate_kbps)) + })) +} + +fn tile(label: &'static str, value: String, palette: Palette) -> Div { + div() + .w(px(80.)) + .px(px(8.)) + .py(px(6.)) + .flex() + .flex_col() + .rounded(px(6.)) + .bg(palette.window) + .child( + div() + .text_size(text(10.)) + .text_color(palette.muted) + .child(label), + ) + .child( + div() + .text_size(text(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .child(value), + ) +} + +fn graph( + label: &'static str, + samples: &VecDeque, + level: fn(&VoiceSample) -> f32, + palette: Palette, +) -> Div { + let empty = SAMPLE_HISTORY.saturating_sub(samples.len()); + let bars = samples.iter().map(|sample| { + let height = level(sample).clamp(0.04, 1.) * GRAPH_HEIGHT; + div() + .flex_1() + .h(px(height)) + .rounded_t(px(1.)) + .bg(Quality::of(sample).color(palette)) + }); + + div() + .flex() + .flex_col() + .gap(px(4.)) + .child( + div() + .text_size(text(10.)) + .text_color(palette.muted) + .child(label), + ) + .child( + div() + .h(px(GRAPH_HEIGHT)) + .p(px(2.)) + .flex() + .items_end() + .gap(px(1.)) + .rounded(px(4.)) + .bg(palette.window) + .children((0..empty).map(|_| div().flex_1())) + .children(bars) + .when(samples.is_empty(), |this| this.opacity(0.5)), + ) +} diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 9d43ef5..b61f084 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -5,8 +5,10 @@ pub mod avatar; pub mod embed; pub mod gui; pub mod media; +pub mod mutes; pub mod network; pub mod settings; +pub mod tray; pub mod voice; pub const NAME: &str = "Yumush"; diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 9c6382c..6a4898e 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -2,10 +2,11 @@ use client::{ ClientConfig, NAME, gui::{self, Yumush}, network, settings, + tray::{self, TrayAction, TrayState}, }; use gpui_kit::{ - App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application, - assets::AllAssets, component::Root, init, px, size, + App, AppContext, Bounds, Entity, QuitMode, TitlebarOptions, Window, WindowBounds, + WindowOptions, application, assets::AllAssets, component::Root, init, px, size, }; use tracing::Level; @@ -23,36 +24,93 @@ fn main() { let settings = settings::load(); let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); + let (mut tray_receiver, tray_handle) = tray::start(); application() .with_assets(AllAssets) + .with_quit_mode(QuitMode::Explicit) .run(move |cx: &mut App| { init(cx); settings::apply(settings.theme, settings.font_size, cx); gui::bind_keys(cx); - let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx); - - let titlebar = TitlebarOptions { - title: Some(NAME.into()), - ..Default::default() + let Some(view) = open_window(cx, |window, cx| { + cx.new(|cx| { + Yumush::new(network_handle, network_event_receiver, settings, window, cx) + }) + }) else { + cx.quit(); + return; }; - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(window_bounds)), - titlebar: Some(titlebar), - ..Default::default() - }, - |window, cx| { - let view = cx.new(|cx| { - Yumush::new(network_handle, network_event_receiver, settings, window, cx) + let mut tray_state = TrayState::default(); + cx.observe(&view, move |view, cx| { + let state = view.read(cx).tray_state(); + if state != tray_state { + tray_state = state; + tray_handle.set(state); + } + }) + .detach(); + + cx.spawn(async move |cx| { + while let Some(action) = tray_receiver.recv().await { + let view = view.clone(); + cx.update(|cx| match action { + TrayAction::Show => show(view, cx), + TrayAction::Quit => cx.quit(), }); - cx.new(|cx| Root::new(view, window, cx)) - }, - ) - .unwrap(); + } + }) + .detach(); cx.activate(true); }); } + +fn show(view: Entity, cx: &mut App) { + match view.read(cx).window() { + Some(handle) => { + let _ = handle.update(cx, |_, window, _| window.activate_window()); + } + None => { + open_window(cx, |_, _| view); + } + } +} + +fn open_window( + cx: &mut App, + build: impl FnOnce(&mut Window, &mut App) -> Entity, +) -> Option> { + let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx); + let titlebar = TitlebarOptions { + title: Some(NAME.into()), + ..Default::default() + }; + let mut opened = None; + + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(window_bounds)), + titlebar: Some(titlebar), + ..Default::default() + }, + |window, cx| { + let view = build(window, cx); + view.update(cx, |yumush, cx| yumush.attach_window(window, cx)); + let closing = view.clone(); + window.on_window_should_close(cx, move |_, cx| { + if !closing.update(cx, |yumush, _| yumush.detach_window()) { + cx.quit(); + } + true + }); + opened = Some(view.clone()); + cx.new(|cx| Root::new(view, window, cx)) + }, + ) + .ok()?; + + opened +} diff --git a/crates/client/src/media/mod.rs b/crates/client/src/media/mod.rs index f2435bd..fa97a10 100644 --- a/crates/client/src/media/mod.rs +++ b/crates/client/src/media/mod.rs @@ -1,6 +1,7 @@ mod convert; mod decode; mod resample; +pub mod voice_note; use std::{ fmt, diff --git a/crates/client/src/media/voice_note.rs b/crates/client/src/media/voice_note.rs new file mode 100644 index 0000000..14b514e --- /dev/null +++ b/crates/client/src/media/voice_note.rs @@ -0,0 +1,113 @@ +use std::{ + path::{Path, PathBuf}, + time::Duration, +}; + +use common::{ + constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, + model::{Attachment, AttachmentKind}, + time::now_ms, +}; +use ec_core::{Buf, CodecId, CodecParameters, Muxer, Packet, StreamInfo, TimeBase}; +use ec_ogg::OggMuxer; +use ec_opus::{Application, Encoder, ogg::opus_head}; +use ec_probe::{Reader, decoder::AudioDecoder}; + +use super::resample; + +pub const BARS: usize = 40; +const BITRATE: u32 = 32_000; +const MAX_PACKET: usize = 1275; +const RANGE_DB: f32 = 60.; + +pub struct Waveform { + pub duration: Duration, + pub peaks: Vec, +} + +pub fn level(samples: &[f32]) -> f32 { + if samples.is_empty() { + return 0.; + } + let mean = samples.iter().map(|sample| sample * sample).sum::() / samples.len() as f32; + let db = 10. * mean.max(f32::MIN_POSITIVE).log10(); + ((db + RANGE_DB) / RANGE_DB).clamp(0., 1.) +} + +fn peaks(mono: &[f32]) -> Vec { + let size = mono.len().div_ceil(BARS).max(1); + let mut levels: Vec = mono.chunks(size).map(level).collect(); + let max = levels.iter().copied().fold(0., f32::max); + if max > 0. { + levels.iter_mut().for_each(|level| *level /= max); + } + levels.resize(BARS, 0.); + levels +} + +pub fn waveform(path: &Path) -> Option { + let mut reader = Reader::open(path).ok()?; + let (index, params) = reader + .streams() + .iter() + .find(|stream| matches!(stream.params.codec, CodecId::Opus)) + .map(|stream| (stream.index, stream.params.clone()))?; + let mut decoder = AudioDecoder::new(¶ms).ok()?; + let mut interleaved = Vec::new(); + let mut scratch = Vec::new(); + while let Ok(packet) = reader.next_packet() { + if packet.stream == index && decoder.decode(&packet, &mut scratch).is_ok() { + interleaved.append(&mut scratch); + } + } + let mono = resample::downmix(&interleaved, decoder.channels()); + Some(Waveform { + duration: Duration::from_secs_f32(mono.len() as f32 / VOICE_SAMPLE_RATE as f32), + peaks: peaks(&mono), + }) +} + +pub fn is_voice_note(attachment: &Attachment) -> bool { + attachment.kind == AttachmentKind::Audio + && attachment.name.starts_with("voice-") + && attachment.name.ends_with(".ogg") +} + +pub fn encode(samples: &[f32]) -> Option> { + if samples.is_empty() { + return None; + } + let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, Application::Voip).ok()?; + encoder.set_bitrate(BITRATE); + + let timebase = TimeBase::new(1, VOICE_SAMPLE_RATE as i64); + let mut params = CodecParameters::new(CodecId::Opus); + params.extradata = Some(Buf::from_vec(opus_head(1, 0, VOICE_SAMPLE_RATE, 0, None))); + let mut muxer = OggMuxer::new(Vec::new()); + muxer + .add_stream(StreamInfo::new(0, timebase, params)) + .ok()?; + + let frame = VOICE_FRAME_SAMPLES; + let mut packet = vec![0u8; MAX_PACKET]; + for (index, chunk) in samples.chunks(frame).enumerate() { + let mut pcm = chunk.to_vec(); + pcm.resize(frame, 0.0); + let length = encoder.encode_float(&pcm, frame, &mut packet).ok()?; + let data = Packet::new(0, timebase, packet[..length].to_vec()) + .with_pts((index * frame) as i64) + .with_duration(frame as i64); + muxer.write_packet(&data).ok()?; + } + muxer.finish().ok()?; + Some(muxer.into_inner()) +} + +pub fn save(samples: &[f32]) -> Option { + let bytes = encode(samples)?; + let directory = dirs::cache_dir()?.join("yumush").join("media"); + std::fs::create_dir_all(&directory).ok()?; + let path = directory.join(format!("voice-{}.ogg", now_ms())); + std::fs::write(&path, bytes).ok()?; + Some(path) +} diff --git a/crates/client/src/mutes.rs b/crates/client/src/mutes.rs new file mode 100644 index 0000000..efd5934 --- /dev/null +++ b/crates/client/src/mutes.rs @@ -0,0 +1,57 @@ +use std::{ + collections::HashSet, + fs, + path::{Path, PathBuf}, +}; + +use tracing::warn; + +fn path() -> Option { + dirs::config_dir().map(|dir| dir.join("yumush").join("mutes")) +} + +fn prefix(account_user_id: &str) -> String { + format!("{account_user_id}\t") +} + +pub fn load(account_user_id: &str) -> HashSet { + let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else { + return HashSet::new(); + }; + let prefix = prefix(account_user_id); + + content + .lines() + .filter_map(|line| line.strip_prefix(&prefix)) + .map(String::from) + .collect() +} + +pub fn save(account_user_id: &str, muted: &HashSet) { + let Some(path) = path() else { + return; + }; + let prefix = prefix(account_user_id); + let mut content: String = fs::read_to_string(&path) + .unwrap_or_default() + .lines() + .filter(|line| !line.starts_with(&prefix)) + .map(|line| format!("{line}\n")) + .collect(); + content.extend( + muted + .iter() + .map(|community_id| format!("{prefix}{community_id}\n")), + ); + + if let Err(error) = write(&path, &content) { + warn!("save mutes failed: {error}"); + } +} + +fn write(path: &Path, content: &str) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(path, content) +} diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index af512de..8988274 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -12,14 +12,14 @@ use common::{ error::Error, event::Event, model::{ - Account, AdminLogEntry, Attachment, AttachmentInfo, Ban, Community, CommunitySummary, - CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit, - Overview, Rank, Report, ReportStatus, Role, ServerBan, ServerSettings, SessionInfo, Usage, - User, VoiceRoom, + Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community, + CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, + Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role, + ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom, }, network::{ DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded, - receive_download_status, receive_event, send_download_request, send_request, + receive_download_status, receive_event, send_download_request, send_encoded, send_request, send_stream_kind, send_upload_header, }, request::{DownloadRequest, Request, UploadHeader}, @@ -27,8 +27,8 @@ use common::{ validate::{ validate_attachment_name, validate_attachment_size, validate_avatar_size, validate_community_name, validate_forward, validate_message_body, validate_new_message, - validate_password, validate_reason, validate_server_settings, validate_status, - validate_username, + validate_password, validate_poll, validate_reason, validate_server_settings, + validate_status, validate_username, }, }; use quinn::Endpoint; @@ -47,7 +47,7 @@ use tracing::{info, warn}; use crate::{ ClientConfig, settings::VoiceSettings, - voice::{self, Voice}, + voice::{self, Voice, VoiceSample}, }; fn device_name() -> String { @@ -96,6 +96,11 @@ enum Command { thumbnail: bool, reply: oneshot::Sender, Error>>, }, + BackupDownload { + name: String, + path: PathBuf, + reply: oneshot::Sender>, + }, } #[derive(Clone)] @@ -726,6 +731,13 @@ impl NetworkHandle { } } + pub async fn open_notes(&self) -> Result { + match self.request(Request::OpenNotes).await? { + Response::Community(community) => Ok(community), + _ => Err(Error::Server), + } + } + pub async fn open_direct(&self, user_id: &str) -> Result { match self .request(Request::OpenDirect { @@ -745,6 +757,17 @@ impl NetworkHandle { } } + pub async fn read_presences(&self) -> Result, Error> { + match self.request(Request::ReadPresences).await? { + Response::Presences(presences) => Ok(presences), + _ => Err(Error::Server), + } + } + + pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> { + self.done(Request::UpdatePresence { presence }).await + } + pub async fn add_friend(&self, user_id: &str) -> Result<(), Error> { self.done(Request::AddFriend { user_id: user_id.to_string(), @@ -800,6 +823,79 @@ impl NetworkHandle { .await } + pub async fn decline_call(&self, community_id: &str) -> Result<(), Error> { + self.done(Request::DeclineCall { + community_id: community_id.to_string(), + }) + .await + } + + pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Error> { + self.done(Request::React { + message_id: message_id.to_string(), + emoji: emoji.to_string(), + }) + .await + } + + pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Error> { + self.done(Request::Pin { + message_id: message_id.to_string(), + pinned, + }) + .await + } + + pub async fn pins(&self, community_id: &str) -> Result, Error> { + match self + .request(Request::Pins { + community_id: community_id.to_string(), + }) + .await? + { + Response::Messages(messages) => Ok(messages), + _ => Err(Error::Server), + } + } + + pub async fn create_poll( + &self, + community_id: &str, + question: &str, + options: Vec, + multiple: bool, + ) -> Result { + validate_poll(question, &options)?; + + match self + .request(Request::CreatePoll { + community_id: community_id.to_string(), + question: question.to_string(), + options, + multiple, + }) + .await? + { + Response::Message(message) => Ok(message), + _ => Err(Error::Server), + } + } + + pub async fn vote(&self, message_id: &str, positions: Vec) -> Result<(), Error> { + self.done(Request::Vote { + message_id: message_id.to_string(), + positions, + }) + .await + } + + pub async fn close_poll(&self, message_id: &str) -> Result<(), Error> { + self.done(Request::ClosePoll { + message_id: message_id.to_string(), + }) + .await + } + pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Error> { validate_reason(Some(reason))?; @@ -858,6 +954,20 @@ impl NetworkHandle { } } + pub async fn search_community( + &self, + community_id: String, + text: String, + ) -> Result, Error> { + match self + .request(Request::SearchCommunity { community_id, text }) + .await? + { + Response::MessageHits(hits) => Ok(hits), + _ => Err(Error::Server), + } + } + pub async fn storage_usage(&self) -> Result<(Vec, Vec), Error> { match self.request(Request::StorageUsage).await? { Response::StorageUsage { users, communities } => Ok((users, communities)), @@ -865,6 +975,27 @@ impl NetworkHandle { } } + pub async fn create_backup(&self) -> Result { + match self.request(Request::CreateBackup).await? { + Response::Backup(backup) => Ok(backup), + _ => Err(Error::Server), + } + } + + pub async fn backups(&self) -> Result, Error> { + match self.request(Request::Backups).await? { + Response::Backups(backups) => Ok(backups), + _ => Err(Error::Server), + } + } + + pub async fn delete_backup(&self, name: &str) -> Result<(), Error> { + self.done(Request::DeleteBackup { + name: name.to_string(), + }) + .await + } + pub async fn attachments( &self, user_id: Option, @@ -943,6 +1074,21 @@ impl NetworkHandle { response.await.map_err(|_| Error::ChannelClosed)? } + pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> { + let (reply, response) = oneshot::channel(); + + self.command_sender + .send(Command::BackupDownload { + name: name.to_string(), + path, + reply, + }) + .await + .map_err(|_| Error::ChannelClosed)?; + + response.await.map_err(|_| Error::ChannelClosed)? + } + pub async fn read_messages( &self, community_id: &str, @@ -960,6 +1106,26 @@ impl NetworkHandle { } } + pub async fn unreads(&self) -> Result, Error> { + match self.request(Request::Unreads).await? { + Response::Unreads(unreads) => Ok(unreads), + _ => Err(Error::Server), + } + } + + pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> { + match self + .request(Request::MarkRead { + community_id: community_id.to_string(), + message_id: message_id.to_string(), + }) + .await? + { + Response::Done => Ok(()), + _ => Err(Error::Server), + } + } + pub async fn update_status(&self, status: &str) -> Result { validate_status(status)?; @@ -1035,6 +1201,18 @@ impl NetworkHandle { } } + pub async fn typing(&self, community_id: &str) -> Result<(), Error> { + match self + .request(Request::Typing { + community_id: community_id.to_string(), + }) + .await? + { + Response::Done => Ok(()), + _ => Err(Error::Server), + } + } + pub async fn leave_voice(&self) -> Result<(), Error> { match self.request(Request::LeaveVoice).await? { Response::Done => Ok(()), @@ -1042,6 +1220,18 @@ impl NetworkHandle { } } + pub async fn read_community(&self, community_id: &str) -> Result { + match self + .request(Request::ReadCommunity { + community_id: community_id.to_string(), + }) + .await? + { + Response::Community(community) => Ok(community), + _ => Err(Error::Server), + } + } + pub async fn voice_participants(&self, community_id: &str) -> Result, Error> { match self .request(Request::VoiceParticipants { @@ -1133,6 +1323,14 @@ impl NetworkHandle { voice::play_chime(&self.voice_settings.lock().unwrap()); } + pub fn play_notification(&self) { + voice::play_yumush(&self.voice_settings.lock().unwrap()); + } + + pub fn play_ring(&self) { + voice::play_ring(&self.voice_settings.lock().unwrap()); + } + pub fn stop_mic_test(&self) { self.mic_test.lock().unwrap().take(); } @@ -1142,6 +1340,10 @@ impl NetworkHandle { live.or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db)) } + pub fn voice_sample(&self) -> Option { + self.voice.lock().unwrap().as_ref().map(Voice::sample) + } + pub fn set_talking(&self, talking: bool) { if let Some(voice) = self.voice.lock().unwrap().as_ref() { voice.set_talking(talking); @@ -1378,6 +1580,44 @@ async fn upload( } } +async fn backup_download( + connection: &quinn::Connection, + name: &str, + path: &Path, +) -> Result<(), Error> { + let (mut send_stream, mut receive_stream) = connection.open_bi().await?; + send_stream_kind(StreamKind::Backup, &mut send_stream).await?; + send_encoded( + &Request::DownloadBackup { + name: name.to_string(), + }, + &mut send_stream, + ) + .await?; + send_stream.finish()?; + + match receive_download_status(&mut receive_stream).await? { + DownloadStatus::Error => { + Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?) + } + DownloadStatus::Ok => { + let mut length_bytes = [0u8; 8]; + receive_stream.read_exact(&mut length_bytes).await?; + let length = u64::from_le_bytes(length_bytes); + + let mut file = tokio::fs::File::create(path).await?; + let copied = tokio::io::copy(&mut receive_stream, &mut file).await?; + if copied != length { + return Err(Error::Network(format!( + "backup truncated ({copied} < {length})" + ))); + } + + Ok(()) + } + } +} + async fn download( connection: &quinn::Connection, attachment_id: &str, @@ -1544,6 +1784,13 @@ async fn actor( let _ = reply.send(download(&connection, &attachment_id, thumbnail).await); }); } + Some(Command::BackupDownload { name, path, reply }) => { + let connection = connection.clone(); + + tokio::spawn(async move { + let _ = reply.send(backup_download(&connection, &name, &path).await); + }); + } None => break 'session, }, Some((epoch, session_token)) = token_receiver.recv() => { diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index 8afe4d5..ada0311 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -124,6 +124,7 @@ pub struct Settings { pub theme: ThemeChoice, pub font_size: FontSize, pub voice: VoiceSettings, + pub close_to_tray: bool, } fn path() -> Option { @@ -179,6 +180,7 @@ pub fn load() -> Settings { .and_then(|value| FontSize::parse(&value)) .unwrap_or(FontSize::Medium), voice, + close_to_tray: text("close_to_tray").is_none_or(|value| value != "false"), } } @@ -204,6 +206,7 @@ pub fn save(settings: &Settings) { let content = [ line("theme", settings.theme.name()), line("font_size", settings.font_size.name()), + line("close_to_tray", settings.close_to_tray), line("voice.sensitivity", voice.sensitivity_db), line("voice.input_volume", voice.input_volume), line("voice.output_volume", voice.output_volume), diff --git a/crates/client/src/tray.rs b/crates/client/src/tray.rs new file mode 100644 index 0000000..497cae6 --- /dev/null +++ b/crates/client/src/tray.rs @@ -0,0 +1,205 @@ +use tokio::sync::mpsc; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrayAction { + Show, + Quit, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct TrayState { + pub messages: u32, + pub mentions: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Badge { + None, + Unread, + Mention, +} + +impl TrayState { + fn badge(self) -> Badge { + match (self.messages, self.mentions) { + (_, 1..) => Badge::Mention, + (1.., _) => Badge::Unread, + _ => Badge::None, + } + } +} + +#[derive(Clone)] +pub struct TrayHandle(mpsc::UnboundedSender); + +impl TrayHandle { + pub fn set(&self, state: TrayState) { + let _ = self.0.send(state); + } +} + +#[cfg(target_os = "linux")] +pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { + use ksni::TrayMethods; + use tracing::warn; + + let (sender, receiver) = mpsc::unbounded_channel(); + let (state_sender, mut state_receiver) = mpsc::unbounded_channel(); + let tray = Tray { + sender, + state: TrayState::default(), + }; + + let _ = std::thread::Builder::new() + .name("tray".to_string()) + .spawn(move || { + let runtime = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(error) => { + warn!("tray runtime: {error}"); + return; + } + }; + runtime.block_on(async move { + match tray.assume_sni_available(true).spawn().await { + Ok(handle) => { + while let Some(state) = state_receiver.recv().await { + handle.update(|tray| tray.state = state).await; + } + std::future::pending::<()>().await + } + Err(error) => warn!("tray: {error}"), + } + }); + }); + + (receiver, TrayHandle(state_sender)) +} + +#[cfg(not(target_os = "linux"))] +pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { + ( + mpsc::unbounded_channel().1, + TrayHandle(mpsc::unbounded_channel().0), + ) +} + +#[cfg(target_os = "linux")] +struct Tray { + sender: mpsc::UnboundedSender, + state: TrayState, +} + +#[cfg(target_os = "linux")] +impl ksni::Tray for Tray { + fn id(&self) -> String { + crate::NAME.to_string() + } + + fn title(&self) -> String { + crate::NAME.to_string() + } + + fn icon_pixmap(&self) -> Vec { + vec![icon(self.state.badge())] + } + + fn status(&self) -> ksni::Status { + match self.state.badge() { + Badge::Mention => ksni::Status::NeedsAttention, + _ => ksni::Status::Active, + } + } + + fn tool_tip(&self) -> ksni::ToolTip { + let description = match self.state.badge() { + Badge::None => String::new(), + _ => format!( + "{} unread · {} mentions", + self.state.messages, self.state.mentions + ), + }; + ksni::ToolTip { + title: crate::NAME.to_string(), + description, + ..Default::default() + } + } + + fn activate(&mut self, _x: i32, _y: i32) { + let _ = self.sender.send(TrayAction::Show); + } + + fn menu(&self) -> Vec> { + use ksni::menu::StandardItem; + + [("Show", TrayAction::Show), ("Quit", TrayAction::Quit)] + .into_iter() + .map(|(label, action)| { + StandardItem { + label: label.to_string(), + activate: Box::new(move |tray: &mut Self| { + let _ = tray.sender.send(action); + }), + ..Default::default() + } + .into() + }) + .collect() + } +} + +#[cfg(target_os = "linux")] +const ICON_SIZE: i32 = 32; +#[cfg(target_os = "linux")] +const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; +#[cfg(target_os = "linux")] +const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; +#[cfg(target_os = "linux")] +const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); +#[cfg(target_os = "linux")] +const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; +#[cfg(target_os = "linux")] +const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; + +#[cfg(target_os = "linux")] +fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { + let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); + (radius - distance + 0.5).clamp(0.0, 1.0) +} + +#[cfg(target_os = "linux")] +fn icon(badge: Badge) -> ksni::Icon { + let dot = match badge { + Badge::None => None, + Badge::Unread => Some(UNREAD_COLOR), + Badge::Mention => Some(MENTION_COLOR), + }; + let data = (0..ICON_SIZE * ICON_SIZE) + .flat_map(|index| { + let x = (index % ICON_SIZE) as f32 + 0.5; + let y = (index / ICON_SIZE) as f32 + 0.5; + let base = ICON_DROPS + .iter() + .map(|drop| coverage(x, y, *drop)) + .fold(0.0, f32::max); + let ([red, green, blue], alpha) = match dot { + Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), + Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { + (ICON_COLOR, 0.0) + } + _ => (ICON_COLOR, base), + }; + [(alpha * 255.0) as u8, red, green, blue] + }) + .collect(); + + ksni::Icon { + width: ICON_SIZE, + height: ICON_SIZE, + data, + } +} diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index 15a9f19..d751d44 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -71,6 +71,16 @@ struct Speaker { first_sequence: u32, previous_transit: Option, jitter_ms: f32, + highest: u32, +} + +#[derive(Debug, Clone, Copy, Default)] +pub struct Traffic { + pub jitter_ms: f32, + pub buffer_ms: f32, + pub loss: f32, + pub up_kbps: f32, + pub down_kbps: f32, } impl Speaker { @@ -87,6 +97,7 @@ impl Speaker { first_sequence: sequence, previous_transit: None, jitter_ms: 0.0, + highest: sequence.wrapping_sub(1), } } @@ -161,6 +172,11 @@ pub struct Engine { sending: bool, level_db: f32, speakers: HashMap, + sent_bytes: usize, + received_bytes: usize, + expected: u32, + arrived: u32, + counting_since: Instant, } impl Default for Engine { @@ -187,6 +203,11 @@ impl Engine { sending: false, level_db: SILENT_DB, speakers: HashMap::new(), + sent_bytes: 0, + received_bytes: 0, + expected: 0, + arrived: 0, + counting_since: Instant::now(), } } @@ -239,7 +260,9 @@ impl Engine { continue; }; - packets.push(encode_packet(self.sequence, &payload[..length])); + let packet = encode_packet(self.sequence, &payload[..length]); + self.sent_bytes += packet.len(); + packets.push(packet); self.sequence = self.sequence.wrapping_add(1); } @@ -251,6 +274,7 @@ impl Engine { return; }; let now = Instant::now(); + self.received_bytes += datagram.len(); let stale = self .speakers @@ -268,6 +292,11 @@ impl Engine { if payload.is_empty() || sequence < speaker.next { return; } + if sequence.wrapping_sub(speaker.highest) < u32::MAX / 2 { + self.expected += sequence.wrapping_sub(speaker.highest); + speaker.highest = sequence; + } + self.arrived += 1; let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0 - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS; @@ -312,6 +341,50 @@ impl Engine { .collect() } + pub fn take_traffic(&mut self) -> Traffic { + let now = Instant::now(); + let seconds = now + .duration_since(self.counting_since) + .as_secs_f32() + .max(f32::EPSILON); + let heard = self + .speakers + .values() + .filter(|speaker| now.duration_since(speaker.last_heard) <= RESTART_AFTER); + let (jitter_ms, buffer_ms) = heard.fold((0.0f32, 0.0f32), |(jitter, buffer), speaker| { + ( + jitter.max(speaker.jitter_ms), + buffer.max(speaker.target() as f32 * FRAME_MS), + ) + }); + let loss = if self.expected == 0 { + 0.0 + } else { + 1.0 - (self.arrived as f32 / self.expected as f32).min(1.0) + }; + let traffic = Traffic { + jitter_ms, + buffer_ms, + loss, + up_kbps: self.sent_bytes as f32 * 8.0 / 1000.0 / seconds, + down_kbps: self.received_bytes as f32 * 8.0 / 1000.0 / seconds, + }; + + self.sent_bytes = 0; + self.received_bytes = 0; + self.expected = 0; + self.arrived = 0; + self.counting_since = now; + traffic + } + + pub fn bitrate_kbps(&self) -> u32 { + match self.profile { + Profile::Voice => VOICE_BITRATE as u32 / 1000, + Profile::Music => MUSIC_BITRATE as u32 / 1000, + } + } + pub fn forget(&mut self, user_id: &str) { self.speakers.remove(user_id); } diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index 8b12823..443c09e 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -21,7 +21,7 @@ pub mod engine; use crate::settings::{Activation, VoiceSettings}; use audio::{Audio, Choice}; -use engine::{Engine, SILENT_DB}; +use engine::{Engine, SILENT_DB, Traffic}; const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2; @@ -32,8 +32,16 @@ const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)]; pub type Capture = Arc>>; pub type Playback = Arc>>; +#[derive(Debug, Clone, Copy, Default)] +pub struct VoiceSample { + pub ping_ms: f32, + pub traffic: Traffic, + pub bitrate_kbps: u32, +} + pub struct Voice { engine: Arc>, + connection: Option, stop: Arc, worker: Option>, capture: Capture, @@ -55,6 +63,7 @@ pub fn start(connection: Option, settings: &VoiceSettings) -> Voice playback.clone(), settings.choice.clone(), ); + let link = connection.clone(); let worker = { let engine = engine.clone(); let stop = stop.clone(); @@ -75,6 +84,7 @@ pub fn start(connection: Option, settings: &VoiceSettings) -> Voice let mut voice = Voice { engine, + connection: link, stop, worker, capture, @@ -88,25 +98,150 @@ pub fn start(connection: Option, settings: &VoiceSettings) -> Voice pub fn play_chime(settings: &VoiceSettings) { let rate = VOICE_SAMPLE_RATE as f32; - let gain = 0.3 * settings.output_volume / 100.0; let mut samples = Vec::new(); for (frequency, seconds) in CHIME { let length = (rate * seconds) as usize; samples.extend((0..length).map(|index| { let time = index as f32 / rate; let fade = (1.0 - index as f32 / length as f32).powi(2); - (std::f32::consts::TAU * frequency * time).sin() * fade * gain + (std::f32::consts::TAU * frequency * time).sin() * fade })); } + play(samples, 0.3, settings); +} + +pub fn play_yumush(settings: &VoiceSettings) { + play(plops(&YUMUSH, YUMUSH_SECONDS), 0.35, settings); +} + +pub fn play_ring(settings: &VoiceSettings) { + play(plops(&RING, RING_SECONDS), 0.35, settings); +} + +fn plops(plops: &[Plop], seconds: f32) -> Vec { + let rate = VOICE_SAMPLE_RATE as f32; + let mut dry = vec![0.0; (rate * seconds) as usize]; + for plop in plops { + plop.add(&mut dry, rate); + } + reverb(dry, rate) +} + +const YUMUSH_SECONDS: f32 = 0.9; +const RING_SECONDS: f32 = 1.3; +const DETUNE: [f32; 2] = [0.998, 1.002]; +const PITCH_SETTLE: f32 = 0.04; +const ATTACK: f32 = 0.004; +const COMB_SECONDS: [f32; 4] = [0.0297, 0.0371, 0.0411, 0.0437]; +const COMB_FEEDBACK: f32 = 0.72; +const COMB_DAMPING: f32 = 0.35; +const REVERB_WET: f32 = 0.25; + +struct Plop { + start: f32, + from: f32, + rise: f32, + decay: f32, + gain: f32, +} + +const YUMUSH: [Plop; 2] = [ + Plop { + start: 0.0, + from: 620.0, + rise: 0.6, + decay: 0.07, + gain: 1.0, + }, + Plop { + start: 0.13, + from: 400.0, + rise: 0.45, + decay: 0.14, + gain: 0.9, + }, +]; + +const RING: [Plop; 4] = [ + Plop { + start: 0.0, + from: 400.0, + rise: 0.45, + decay: 0.1, + gain: 0.9, + }, + Plop { + start: 0.14, + from: 500.0, + rise: 0.45, + decay: 0.1, + gain: 0.9, + }, + Plop { + start: 0.28, + from: 620.0, + rise: 0.6, + decay: 0.12, + gain: 1.0, + }, + Plop { + start: 0.5, + from: 620.0, + rise: 0.6, + decay: 0.2, + gain: 0.8, + }, +]; + +impl Plop { + fn add(&self, out: &mut [f32], rate: f32) { + let start = (self.start * rate) as usize; + for detune in DETUNE { + let mut phase = 0.0; + for (index, sample) in out.iter_mut().enumerate().skip(start) { + let time = (index - start) as f32 / rate; + let frequency = + self.from * detune * (1.0 + self.rise * (1.0 - (-time / PITCH_SETTLE).exp())); + phase += std::f32::consts::TAU * frequency / rate; + let envelope = (time / ATTACK).min(1.0) * (-time / self.decay).exp(); + *sample += phase.sin() * envelope * self.gain / DETUNE.len() as f32; + } + } + } +} + +fn reverb(dry: Vec, rate: f32) -> Vec { + let mut wet = vec![0.0; dry.len()]; + for seconds in COMB_SECONDS { + let mut buffer = vec![0.0; (rate * seconds) as usize]; + let mut filtered = 0.0; + for (index, (input, output)) in dry.iter().zip(wet.iter_mut()).enumerate() { + let slot = index % buffer.len(); + let delayed = buffer[slot]; + filtered = delayed * (1.0 - COMB_DAMPING) + filtered * COMB_DAMPING; + buffer[slot] = input + filtered * COMB_FEEDBACK; + *output += delayed / COMB_SECONDS.len() as f32; + } + } + + dry.iter() + .zip(wet) + .map(|(dry, wet)| dry + wet * REVERB_WET) + .collect() +} + +fn play(samples: Vec, gain: f32, settings: &VoiceSettings) { + let rate = VOICE_SAMPLE_RATE as f32; + let gain = gain * settings.output_volume / 100.0; let duration = Duration::from_secs_f32(samples.len() as f32 / rate + 0.3); - let (mut producer, consumer) = RingBuffer::new(samples.len()); + let (mut producer, consumer) = RingBuffer::new(samples.len().max(1)); for sample in samples { - let _ = producer.push(sample); + let _ = producer.push(sample * gain); } let choice = settings.choice.clone(); let _ = std::thread::Builder::new() - .name("chime".to_string()) + .name("sound".to_string()) .spawn(move || { let _audio = audio::start(None, Arc::new(Mutex::new(consumer)), choice); std::thread::sleep(duration); @@ -197,6 +332,22 @@ impl Voice { .map_or(SILENT_DB, |engine| engine.level_db()) } + pub fn sample(&self) -> VoiceSample { + let ping_ms = self + .connection + .as_ref() + .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0); + let Ok(mut engine) = self.engine.lock() else { + return VoiceSample::default(); + }; + + VoiceSample { + ping_ms, + traffic: engine.take_traffic(), + bitrate_kbps: engine.bitrate_kbps(), + } + } + pub fn set_muted(&self, muted: bool) { if let Ok(mut engine) = self.engine.lock() { engine.set_muted(muted); diff --git a/crates/common/src/constant.rs b/crates/common/src/constant.rs index fd795a0..31a33ae 100644 --- a/crates/common/src/constant.rs +++ b/crates/common/src/constant.rs @@ -7,6 +7,11 @@ pub const MINIMUM_MESSAGE_LENGTH: usize = 1; pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16; pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3; pub const MESSAGE_PAGE_LIMIT: usize = 50; +pub const REACTIONS: [&str; 8] = ["👍", "❤️", "😂", "😮", "😢", "🔥", "🎉", "👀"]; +pub const MINIMUM_POLL_OPTIONS: usize = 2; +pub const MAXIMUM_POLL_OPTIONS: usize = 10; +pub const MAXIMUM_POLL_QUESTION_LENGTH: usize = 128; +pub const MAXIMUM_POLL_OPTION_LENGTH: usize = 64; pub const LOG_PAGE_LIMIT: u32 = 500; pub const AVATAR_SIZE: u32 = 128; pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024; diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index 04ec4cc..271e666 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -160,6 +160,8 @@ pub enum Error { AttachmentLimit(InvalidInput), #[error("device: {0}")] Device(InvalidInput), + #[error("backup name: {0}")] + BackupName(InvalidInput), #[error("banned")] Banned, #[error("maintenance")] @@ -172,8 +174,8 @@ pub enum Error { Announcement(InvalidInput), #[error("limit reached")] LimitReached, - #[error("too many requests")] - RateLimited, + #[error("too many requests, retry in {retry_after_seconds}s")] + RateLimited { retry_after_seconds: u64 }, } from_display! { Error { diff --git a/crates/common/src/event.rs b/crates/common/src/event.rs index 2fc3fbf..8276a1a 100644 --- a/crates/common/src/event.rs +++ b/crates/common/src/event.rs @@ -1,6 +1,6 @@ use bitcode::{Decode, Encode}; -use crate::model::{Community, Friends, Invitation, Member, Message, Rank, User}; +use crate::model::{Community, Friends, Invitation, Member, Message, Presence, Rank, User}; #[derive(Debug, Clone, Encode, Decode)] pub enum Event { @@ -37,6 +37,10 @@ pub enum Event { user_id: String, }, UserUpdated(User), + PresenceChanged { + user_id: String, + presence: Presence, + }, VoiceJoined { community_id: String, user_id: String, @@ -53,4 +57,25 @@ pub enum Event { Announcement { text: String, }, + Typing { + community_id: String, + user_id: String, + }, +} + +impl Event { + pub fn community_id(&self) -> Option<&str> { + match self { + Self::MessageCreated(message) + | Self::MessageUpdated(message) + | Self::MessageDeleted(message) => Some(&message.community_id), + Self::CommunityUpdated(community) => Some(&community.id), + Self::MemberJoined { community_id, .. } + | Self::MemberLeft { community_id, .. } + | Self::RankChanged { community_id, .. } + | Self::VoiceJoined { community_id, .. } + | Self::VoiceLeft { community_id, .. } => Some(community_id), + _ => None, + } + } } diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index 465dfa1..edba8d3 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -33,6 +33,39 @@ impl Role { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum Presence { + Online, + Busy, + Offline, +} + +impl Presence { + pub const ALL: [Self; 3] = [Presence::Online, Presence::Busy, Presence::Offline]; + + pub fn as_str(self) -> &'static str { + match self { + Presence::Online => "online", + Presence::Busy => "busy", + Presence::Offline => "offline", + } + } + + pub fn label(self) -> &'static str { + match self { + Presence::Online => "Online", + Presence::Busy => "Busy", + Presence::Offline => "Offline", + } + } + + pub fn parse(text: &str) -> Option { + Self::ALL + .into_iter() + .find(|presence| presence.as_str() == text) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] pub enum Rank { Member, @@ -111,6 +144,7 @@ pub struct Member { pub enum CommunityKind { Group, Direct { peer: User }, + Notes, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -122,6 +156,19 @@ pub struct Community { pub voice_enabled: bool, } +#[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)] +pub struct Unread { + pub community_id: String, + pub messages: u32, + pub mentions: u32, + pub last_read: Option, +} + +pub fn mentions(body: &str, username: &str) -> bool { + body.to_lowercase() + .contains(&format!("@{}", username.to_lowercase())) +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct VoiceRoom { pub community_id: String, @@ -198,6 +245,9 @@ pub enum AdminAction { GhostDisabled, GhostVisit, GhostVoice { seconds: u64 }, + BackupCreated { name: String }, + BackupDeleted { name: String }, + BackupDownloaded { name: String }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -230,10 +280,13 @@ pub enum AdminActionKind { GhostDisabled, GhostVisit, GhostVoice, + BackupCreated, + BackupDeleted, + BackupDownloaded, } impl AdminActionKind { - pub const ALL: [Self; 28] = [ + pub const ALL: [Self; 31] = [ AdminActionKind::RoleChanged, AdminActionKind::UserDeleted, AdminActionKind::UserSuspended, @@ -262,6 +315,9 @@ impl AdminActionKind { AdminActionKind::GhostDisabled, AdminActionKind::GhostVisit, AdminActionKind::GhostVoice, + AdminActionKind::BackupCreated, + AdminActionKind::BackupDeleted, + AdminActionKind::BackupDownloaded, ]; pub const fn as_str(self) -> &'static str { @@ -294,6 +350,9 @@ impl AdminActionKind { AdminActionKind::GhostDisabled => "ghost_disabled", AdminActionKind::GhostVisit => "ghost_visit", AdminActionKind::GhostVoice => "ghost_voice", + AdminActionKind::BackupCreated => "backup_created", + AdminActionKind::BackupDeleted => "backup_deleted", + AdminActionKind::BackupDownloaded => "backup_downloaded", } } @@ -333,21 +392,24 @@ impl AdminAction { AdminAction::GhostDisabled => AdminActionKind::GhostDisabled, AdminAction::GhostVisit => AdminActionKind::GhostVisit, AdminAction::GhostVoice { .. } => AdminActionKind::GhostVoice, + AdminAction::BackupCreated { .. } => AdminActionKind::BackupCreated, + AdminAction::BackupDeleted { .. } => AdminActionKind::BackupDeleted, + AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, } } } -const fn action_names() -> [&'static str; 28] { - let mut names = [""; 28]; +const fn action_names() -> [&'static str; 31] { + let mut names = [""; 31]; let mut index = 0; - while index < 28 { + while index < 31 { names[index] = AdminActionKind::ALL[index].as_str(); index += 1; } names } -pub const ACTION_NAMES: [&str; 28] = action_names(); +pub const ACTION_NAMES: [&str; 31] = action_names(); pub fn action_name(action: &AdminAction) -> &'static str { action.kind().as_str() @@ -364,6 +426,9 @@ pub fn action_detail(action: &AdminAction) -> Option { AdminAction::VoiceMuted { muted } => Some(muted.to_string()), AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()), AdminAction::GhostVoice { seconds } => Some(seconds.to_string()), + AdminAction::BackupCreated { name } + | AdminAction::BackupDeleted { name } + | AdminAction::BackupDownloaded { name } => Some(name.clone()), _ => None, } } @@ -472,6 +537,13 @@ pub struct AttachmentInfo { pub community: String, } +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct BackupInfo { + pub name: String, + pub size_bytes: u64, + pub created_ms: u64, +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Usage { pub user: User, @@ -611,6 +683,7 @@ pub struct SnippetMessage { pub avatar_id: Option, pub body: String, pub attachments: Vec, + pub poll: Option, } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -619,6 +692,26 @@ pub struct Snippet { pub messages: Vec, } +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct Reaction { + pub emoji: String, + pub user_ids: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct PollOption { + pub text: String, + pub voter_ids: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +pub struct Poll { + pub question: String, + pub options: Vec, + pub multiple: bool, + pub closed: bool, +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Message { pub id: String, @@ -626,9 +719,49 @@ pub struct Message { pub community_id: String, pub body: String, pub attachments: Vec, + pub reactions: Vec, pub reply: Option, pub snippet: Option, + pub poll: Option, pub edited: bool, + pub pinned: bool, + pub call: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum CallLog { + Started, + Declined, + Missed, + Ended { seconds: u64 }, +} + +impl CallLog { + pub fn as_str(self) -> &'static str { + match self { + CallLog::Started => "started", + CallLog::Declined => "declined", + CallLog::Missed => "missed", + CallLog::Ended { .. } => "ended", + } + } + + pub fn parse(text: &str, seconds: u64) -> Option { + match text { + "started" => Some(CallLog::Started), + "declined" => Some(CallLog::Declined), + "missed" => Some(CallLog::Missed), + "ended" => Some(CallLog::Ended { seconds }), + _ => None, + } + } + + pub fn seconds(self) -> u64 { + match self { + CallLog::Ended { seconds } => seconds, + CallLog::Started | CallLog::Declined | CallLog::Missed => 0, + } + } } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] diff --git a/crates/common/src/network.rs b/crates/common/src/network.rs index acd9d1a..438fdba 100644 --- a/crates/common/src/network.rs +++ b/crates/common/src/network.rs @@ -29,6 +29,7 @@ pub enum StreamKind { Request = 0, Upload = 1, Download = 2, + Backup = 3, } impl StreamKind { @@ -37,6 +38,7 @@ impl StreamKind { 0 => Some(StreamKind::Request), 1 => Some(StreamKind::Upload), 2 => Some(StreamKind::Download), + 3 => Some(StreamKind::Backup), _ => None, } } diff --git a/crates/common/src/permission.rs b/crates/common/src/permission.rs index 2422b60..c72a672 100644 --- a/crates/common/src/permission.rs +++ b/crates/common/src/permission.rs @@ -35,6 +35,14 @@ pub fn can_edit_message(is_author: bool) -> bool { is_author } +pub fn can_pin(actor: Option, direct: bool) -> bool { + actor >= Some(Rank::Moderator) || (direct && actor.is_some()) +} + +pub fn can_close_poll(actor: Option, is_author: bool) -> bool { + is_author || actor >= Some(Rank::Moderator) +} + pub fn can_delete_message(actor: Option, author: Option, is_author: bool) -> bool { is_author || (actor >= Some(Rank::Moderator) && actor > author) } diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index e6afd24..77c88d5 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -1,6 +1,6 @@ use bitcode::{Decode, Encode}; -use crate::model::{Rank, ReportStatus, Role, ServerSettings}; +use crate::model::{Presence, Rank, ReportStatus, Role, ServerSettings}; #[derive(Debug, Clone, Encode, Decode)] pub struct UploadHeader { @@ -39,6 +39,10 @@ pub enum Request { UpdateStatus { status: String, }, + UpdatePresence { + presence: Presence, + }, + ReadPresences, UpdateAvatar { image: Vec, }, @@ -113,14 +117,49 @@ pub enum Request { DeleteMessage { message_id: String, }, + CreatePoll { + community_id: String, + question: String, + options: Vec, + multiple: bool, + }, + Vote { + message_id: String, + positions: Vec, + }, + ClosePoll { + message_id: String, + }, + React { + message_id: String, + emoji: String, + }, + Pin { + message_id: String, + pinned: bool, + }, + Pins { + community_id: String, + }, ReadMessages { community_id: String, before: Option, }, + Unreads, + MarkRead { + community_id: String, + message_id: String, + }, + Typing { + community_id: String, + }, JoinVoice { community_id: String, }, LeaveVoice, + DeclineCall { + community_id: String, + }, VoiceParticipants { community_id: String, }, @@ -130,6 +169,7 @@ pub enum Request { OpenDirect { user_id: String, }, + OpenNotes, Friends, AddFriend { user_id: String, @@ -252,6 +292,10 @@ pub enum Request { after_ms: Option, before_ms: Option, }, + SearchCommunity { + community_id: String, + text: String, + }, PurgeUser { user_id: String, }, @@ -281,4 +325,12 @@ pub enum Request { SetGhost { enabled: bool, }, + CreateBackup, + Backups, + DeleteBackup { + name: String, + }, + DownloadBackup { + name: String, + }, } diff --git a/crates/common/src/response.rs b/crates/common/src/response.rs index b03a0e5..5a0b04a 100644 --- a/crates/common/src/response.rs +++ b/crates/common/src/response.rs @@ -3,15 +3,19 @@ use bitcode::{Decode, Encode}; use crate::{ error::Error, model::{ - Account, AdminLogEntry, Attachment, AttachmentInfo, Ban, Community, CommunitySummary, - CommunityUsage, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit, - DayStat, Overview, Report, ServerBan, ServerSettings, SessionInfo, Usage, User, VoiceRoom, + Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community, + CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, + Member, Message, MessageHit, Overview, Presence, Report, ServerBan, ServerSettings, + SessionInfo, Unread, Usage, User, VoiceRoom, }, }; #[derive(Debug, Clone, Encode, Decode)] pub enum Response { - Session { user: User, token: String }, + Session { + user: User, + token: String, + }, User(User), Avatar(Vec), Community(Community), @@ -20,6 +24,7 @@ pub enum Response { Bans(Vec), Message(Message), Messages(Vec), + Unreads(Vec), Attachment(Attachment), Voice(Vec), Friends(Friends), @@ -45,4 +50,7 @@ pub enum Response { communities: Vec, }, DailyStats(Vec), + Backup(BackupInfo), + Backups(Vec), + Presences(Vec<(String, Presence)>), } diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index 6559744..5e52a65 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -1,14 +1,18 @@ +use std::collections::BTreeSet; + use crate::{ constant::{ - MAXIMUM_ANNOUNCEMENT_LENGTH, MAXIMUM_ATTACHMENT_LIMIT_BYTES, MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_AVATAR_BYTES, - MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_DEVICE_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES, - MAXIMUM_MESSAGE_LENGTH, MAXIMUM_PASSWORD_LENGTH, MAXIMUM_REASON_LENGTH, - MAXIMUM_STATUS_LENGTH, MAXIMUM_USERNAME_LENGTH, MINIMUM_ATTACHMENT_LIMIT_BYTES, - MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, - MINIMUM_USERNAME_LENGTH, + MAXIMUM_ANNOUNCEMENT_LENGTH, MAXIMUM_ATTACHMENT_LIMIT_BYTES, + MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_AVATAR_BYTES, MAXIMUM_COMMUNITY_NAME_LENGTH, + MAXIMUM_DEVICE_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, + MAXIMUM_PASSWORD_LENGTH, MAXIMUM_POLL_OPTION_LENGTH, MAXIMUM_POLL_OPTIONS, + MAXIMUM_POLL_QUESTION_LENGTH, MAXIMUM_REASON_LENGTH, MAXIMUM_STATUS_LENGTH, + MAXIMUM_USERNAME_LENGTH, MINIMUM_ATTACHMENT_LIMIT_BYTES, MINIMUM_COMMUNITY_NAME_LENGTH, + MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS, + MINIMUM_USERNAME_LENGTH, REACTIONS, }, error::{Error, InvalidInput}, - model::ServerSettings, + model::{Poll, ServerSettings}, }; fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> { @@ -78,6 +82,40 @@ pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> R check(body, 0, maximum, false).map_err(Error::Message) } +pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { + check_length(question.chars().count(), 1, MAXIMUM_POLL_QUESTION_LENGTH) + .map_err(Error::Message)?; + check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS) + .map_err(Error::Message)?; + for option in options { + check_length(option.chars().count(), 1, MAXIMUM_POLL_OPTION_LENGTH) + .map_err(Error::Message)?; + } + + Ok(()) +} + +pub fn validate_vote(poll: &Poll, positions: &[u32]) -> Result<(), Error> { + let unique: BTreeSet<&u32> = positions.iter().collect(); + let in_range = positions + .iter() + .all(|position| (*position as usize) < poll.options.len()); + let allowed = poll.multiple || positions.len() <= 1; + if poll.closed || !in_range || unique.len() != positions.len() || !allowed { + return Err(Error::Forbidden); + } + + Ok(()) +} + +pub fn validate_reaction(emoji: &str) -> Result<(), Error> { + if REACTIONS.contains(&emoji) { + return Ok(()); + } + + Err(Error::Message(InvalidInput::ForbiddenCharacter)) +} + pub fn validate_attachment_name(name: &str) -> Result<(), Error> { check_length(name.chars().count(), 1, MAXIMUM_ATTACHMENT_NAME_LENGTH) .map_err(Error::AttachmentName)?; @@ -89,6 +127,19 @@ pub fn validate_attachment_name(name: &str) -> Result<(), Error> { Ok(()) } +pub fn validate_backup_name(name: &str) -> Result<(), Error> { + if name.is_empty() + || name.contains("..") + || !name.chars().all(|character| { + character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') + }) + { + return Err(Error::BackupName(InvalidInput::ForbiddenCharacter)); + } + + Ok(()) +} + fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> { match actual { 0 => Err(InvalidInput::Empty), @@ -142,7 +193,10 @@ pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> validate_community_name(&settings.name)?; validate_attachment_limit(settings.max_attachment_bytes)?; check_quota(settings.user_quota_bytes, settings.max_attachment_bytes)?; - check_quota(settings.community_quota_bytes, settings.max_attachment_bytes)?; + check_quota( + settings.community_quota_bytes, + settings.max_attachment_bytes, + )?; validate_announcement(&settings.announcement)?; check_length( settings.max_message_length as usize, diff --git a/crates/server/src/admin_log.rs b/crates/server/src/admin_log.rs index 9bf68d8..25617ad 100644 --- a/crates/server/src/admin_log.rs +++ b/crates/server/src/admin_log.rs @@ -54,6 +54,9 @@ fn action_of(text: &str, detail: Option) -> Option { AdminActionKind::GhostVoice => AdminAction::GhostVoice { seconds: detail?.parse().ok()?, }, + AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? }, + AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? }, + AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? }, }) } diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index a790b7d..7319510 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -478,7 +478,14 @@ pub async fn store( validate_attachment_name(&header.name)?; let settings = server_settings::read(&conn).await?; validate_attachment_size(header.size, settings.max_attachment_bytes)?; - ensure_quota(&user.id, &header.community_id, header.size, &settings, &conn).await?; + ensure_quota( + &user.id, + &header.community_id, + header.size, + &settings, + &conn, + ) + .await?; let id = new_id(); let part = directory.join(format!("{id}.part")); @@ -579,7 +586,7 @@ async fn locate( Ok((path, length)) } -async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> { +pub async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> { let mut file = File::open(path).await?; let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; loop { @@ -730,6 +737,7 @@ mod tests { &Services::default(), None, &test::directory(), + &test::directory(), ) .await; diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs new file mode 100644 index 0000000..c471344 --- /dev/null +++ b/crates/server/src/backup.rs @@ -0,0 +1,150 @@ +use std::path::{Path, PathBuf}; + +use common::{ + error::Error as CommonError, + model::{AdminAction, BackupInfo, User}, + network::{ + DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_request, send_download_status, + send_encoded, + }, + permission, + request::Request, + time, + validate::validate_backup_name, +}; +use quinn::{RecvStream, SendStream}; +use turso::Connection; + +use crate::{ + admin_log, attachment, + database::{self, DB}, + error::Error, + request::ensure, + user, +}; + +const PREFIX: &str = "yumush-"; +const EXTENSION: &str = ".db"; + +pub fn directory(database_path: &str) -> Result { + let directory = Path::new(database_path) + .parent() + .unwrap_or_else(|| Path::new("")) + .join("backups"); + std::fs::create_dir_all(&directory)?; + + Ok(directory) +} + +fn created_secs(name: &str) -> Option { + name.strip_prefix(PREFIX)? + .strip_suffix(EXTENSION)? + .parse() + .ok() +} + +fn info(directory: &Path, name: &str) -> Result { + let created_secs = created_secs(name).ok_or(CommonError::NotFound)?; + let size_bytes = std::fs::metadata(directory.join(name))?.len(); + + Ok(BackupInfo { + name: name.to_string(), + size_bytes, + created_ms: created_secs * 1000, + }) +} + +fn path_of(directory: &Path, name: &str) -> Result { + validate_backup_name(name)?; + created_secs(name).ok_or(CommonError::NotFound)?; + + Ok(directory.join(name)) +} + +pub async fn create(conn: &Connection, directory: &Path) -> Result { + let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); + let path = directory.join(&name); + let statement = format!( + "VACUUM INTO '{}'", + path.to_string_lossy().replace('\'', "''") + ); + conn.execute(&statement, ()).await?; + + info(directory, &name) +} + +pub fn list(directory: &Path) -> Result, Error> { + let mut backups = Vec::new(); + for entry in std::fs::read_dir(directory)? { + let name = entry?.file_name().to_string_lossy().into_owned(); + if created_secs(&name).is_some() { + backups.push(info(directory, &name)?); + } + } + backups.sort_by(|left, right| right.created_ms.cmp(&left.created_ms)); + + Ok(backups) +} + +pub fn delete(name: &str, directory: &Path) -> Result<(), Error> { + std::fs::remove_file(path_of(directory, name)?)?; + + Ok(()) +} + +async fn locate( + user: Option<&User>, + request: Request, + db: &DB, + directory: &Path, +) -> Result<(PathBuf, u64), Error> { + let user = user.ok_or(CommonError::Unauthenticated)?; + let Request::DownloadBackup { name } = request else { + return Err(CommonError::Forbidden.into()); + }; + let conn = database::connect(db).await?; + let me = user::read(&user.id, &conn).await?; + ensure(permission::is_builder(me.role))?; + + let path = path_of(directory, &name)?; + let length = tokio::fs::metadata(&path) + .await + .map_err(|_| CommonError::NotFound)? + .len(); + admin_log::record( + Some(&me.id), + None, + None, + &AdminAction::BackupDownloaded { name }, + &conn, + ) + .await?; + + Ok((path, length)) +} + +pub async fn download( + user: Option<&User>, + receive_stream: RecvStream, + mut send_stream: SendStream, + db: &DB, + directory: &Path, +) -> Result<(), Error> { + let request = receive_request(receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?; + + match locate(user, request, db, directory).await { + Ok((path, length)) => { + send_download_status(DownloadStatus::Ok, &mut send_stream).await?; + send_stream.write_all(&length.to_le_bytes()).await?; + attachment::stream_file(&path, &mut send_stream).await?; + } + Err(error) => { + let error: CommonError = error.into(); + send_download_status(DownloadStatus::Error, &mut send_stream).await?; + send_encoded(&error, &mut send_stream).await?; + } + } + send_stream.finish()?; + + Ok(()) +} diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs index 384cd7d..e0144e1 100644 --- a/crates/server/src/community.rs +++ b/crates/server/src/community.rs @@ -11,15 +11,17 @@ use crate::{database::new_id, error::Error, user}; pub enum Kind { Group, Direct, + Notes, } impl Kind { - const ALL: [Self; 2] = [Kind::Group, Kind::Direct]; + const ALL: [Self; 3] = [Kind::Group, Kind::Direct, Kind::Notes]; pub fn as_str(self) -> &'static str { match self { Kind::Group => "group", Kind::Direct => "direct", + Kind::Notes => "notes", } } @@ -56,13 +58,39 @@ async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result< user::from_row(&row) } +async fn outsider_name( + community_id: &str, + viewer_id: &str, + conn: &Connection, +) -> Result, Error> { + let mut rows = conn + .query( + "SELECT a.username, b.username FROM direct JOIN user a ON a.id = direct.user_a JOIN user b ON b.id = direct.user_b WHERE direct.community_id = ?1 AND direct.user_a != ?2 AND direct.user_b != ?2", + (community_id, viewer_id), + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(None); + }; + let first: String = row.get(0)?; + let second: String = row.get(1)?; + + Ok(Some(format!("{first} & {second}"))) +} + async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result { - let (id, name, kind, avatar_id, voice_enabled) = raw; + let (id, mut name, kind, avatar_id, voice_enabled) = raw; let kind = match kind { Kind::Group => CommunityKind::Group, - Kind::Direct => CommunityKind::Direct { - peer: peer(&id, viewer_id, conn).await?, - }, + Kind::Direct => { + if let Some(outsider) = outsider_name(&id, viewer_id, conn).await? { + name = outsider; + } + CommunityKind::Direct { + peer: peer(&id, viewer_id, conn).await?, + } + } + Kind::Notes => CommunityKind::Notes, }; Ok(Community { @@ -104,6 +132,17 @@ pub async fn create_direct(conn: &Connection) -> Result { Ok(id) } +pub async fn create_notes(conn: &Connection) -> Result { + let id = new_id(); + conn.execute( + "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)", + (id.as_str(), Kind::Notes.as_str()), + ) + .await?; + + Ok(id) +} + pub async fn read( community_id: &str, viewer_id: &str, @@ -236,7 +275,7 @@ pub async fn delete( Ok(deleted) } -async fn kind(community_id: &str, conn: &Connection) -> Result { +pub async fn kind(community_id: &str, conn: &Connection) -> Result { let mut rows = conn .query("SELECT kind FROM community WHERE id = ?1", (community_id,)) .await?; @@ -250,6 +289,13 @@ pub async fn is_direct(community_id: &str, conn: &Connection) -> Result Result { + Ok(matches!( + kind(community_id, conn).await?, + Kind::Direct | Kind::Notes + )) +} + pub async fn set_voice_enabled( community_id: &str, enabled: bool, @@ -280,13 +326,28 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result Result { let mut rows = conn .query( - "SELECT CASE WHEN kind = ?2 THEN 'DM' ELSE name END FROM community WHERE id = ?1", + "SELECT kind = ?2, name FROM community WHERE id = ?1", (community_id, Kind::Direct.as_str()), ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; + let direct: i64 = row.get(0)?; + if direct == 0 { + return Ok(row.get(1)?); + } + + let mut rows = conn + .query( + "SELECT user.username FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.username COLLATE NOCASE", + (community_id,), + ) + .await?; + let mut usernames = Vec::new(); + while let Some(row) = rows.next().await? { + usernames.push(row.get::(0)?); + } - Ok(row.get(0)?) + Ok(format!("DM · {}", usernames.join(" & "))) } #[cfg(test)] diff --git a/crates/server/src/database.rs b/crates/server/src/database.rs index b7ad018..bb1664e 100644 --- a/crates/server/src/database.rs +++ b/crates/server/src/database.rs @@ -240,6 +240,55 @@ const MIGRATIONS: &[&str] = &[ " ALTER TABLE user ADD COLUMN ghost INTEGER NOT NULL DEFAULT 0; ", + " + ALTER TABLE user ADD COLUMN presence TEXT NOT NULL DEFAULT 'online'; +", + " + ALTER TABLE message ADD COLUMN call TEXT; + ALTER TABLE message ADD COLUMN call_seconds INTEGER NOT NULL DEFAULT 0; +", + " + CREATE TABLE reaction ( + message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + emoji TEXT NOT NULL, + PRIMARY KEY (message_id, user_id, emoji) + ); +", + " + ALTER TABLE message ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0; +", + " + ALTER TABLE user_community ADD COLUMN last_read TEXT; + UPDATE user_community SET last_read = (SELECT MAX(id) FROM message WHERE message.community_id = user_community.community_id); +", + " + CREATE TABLE notes ( + user_id TEXT PRIMARY KEY REFERENCES user (id) ON DELETE CASCADE, + community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE + ); +", + " + CREATE TABLE poll ( + message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE, + question TEXT NOT NULL, + multiple INTEGER NOT NULL, + closed INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE poll_option ( + message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, + position INTEGER NOT NULL, + text TEXT NOT NULL, + PRIMARY KEY (message_id, position) + ); + CREATE TABLE poll_vote ( + message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE, + position INTEGER NOT NULL, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + PRIMARY KEY (message_id, position, user_id) + ); +", + "ALTER TABLE snippet_message ADD COLUMN poll BLOB;", ]; pub async fn open(path: &str) -> Result { diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 0fc40a8..6eb51d2 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -1,17 +1,19 @@ +pub mod admin_log; pub mod attachment; pub mod authentication; +pub mod backup; pub mod certificate; pub mod community; -pub mod admin_log; pub mod database; pub mod direct; pub mod error; pub mod friend; -pub mod invite; pub mod invitation; +pub mod invite; pub mod log; pub mod message; pub mod network; +pub mod notes; pub mod overview; pub mod rate_limit; pub mod report; @@ -70,10 +72,18 @@ pub async fn showtime() -> Result<(), Error> { let database = database::open(&config.database_path).await?; let certificate = certificate::load(&config.certificate_path, &config.key_path)?; let attachments = attachment::directory(&config.database_path)?; + let backups = backup::directory(&config.database_path)?; tokio::spawn(attachment::collect(database.clone(), attachments.clone())); tokio::spawn(retention::collect(database.clone(), attachments.clone())); - network::serve(&config.server_address, certificate, database, attachments).await + network::serve( + &config.server_address, + certificate, + database, + attachments, + backups, + ) + .await } pub async fn set_role(username: &str, role: Role) -> Result<(), Error> { diff --git a/crates/server/src/message.rs b/crates/server/src/message.rs index 2822602..a043bd2 100644 --- a/crates/server/src/message.rs +++ b/crates/server/src/message.rs @@ -1,11 +1,14 @@ -use std::path::Path; +use std::{collections::HashMap, path::Path}; use common::{ constant::{ MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT, }, error::{Error as CommonError, InvalidInput}, - model::{Message, MessageHit, Quote, Snippet, SnippetMessage, User}, + model::{ + CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage, + User, + }, time, validate::{validate_message_body, validate_new_message}, }; @@ -15,10 +18,15 @@ use crate::{attachment, community, database::new_id, error::Error, user}; const SEARCH_LIMIT: usize = 200; -const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL) FROM message m LEFT JOIN message r ON r.id = m.reply_to"; +const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned FROM message m LEFT JOIN message r ON r.id = m.reply_to"; fn from_row(row: &Row) -> Result { let edited: i64 = row.get(4)?; + let call_seconds: i64 = row.get(10)?; + let pinned: i64 = row.get(11)?; + let call = row + .get::>(9)? + .and_then(|text| CallLog::parse(&text, call_seconds as u64)); let reply = match row.get::>(5)? { Some(message_id) => { let body: String = row.get(7)?; @@ -39,12 +47,136 @@ fn from_row(row: &Row) -> Result { community_id: row.get(2)?, body: row.get(3)?, attachments: Vec::new(), + reactions: Vec::new(), reply, snippet: None, + poll: None, edited: edited != 0, + pinned: pinned != 0, + call, }) } +fn placeholders(count: usize) -> String { + (1..=count) + .map(|index| format!("?{index}")) + .collect::>() + .join(", ") +} + +async fn reactions_of( + message_ids: &[String], + conn: &Connection, +) -> Result>, Error> { + let mut reactions: HashMap> = HashMap::new(); + if message_ids.is_empty() { + return Ok(reactions); + } + + let placeholders = placeholders(message_ids.len()); + let mut rows = conn + .query( + &format!( + "SELECT message_id, emoji, user_id FROM reaction WHERE message_id IN ({placeholders}) ORDER BY message_id, emoji, user_id" + ), + message_ids.to_vec(), + ) + .await?; + + while let Some(row) = rows.next().await? { + let message_id: String = row.get(0)?; + let emoji: String = row.get(1)?; + let user_id: String = row.get(2)?; + let entries = reactions.entry(message_id).or_default(); + match entries + .last_mut() + .filter(|reaction| reaction.emoji == emoji) + { + Some(reaction) => reaction.user_ids.push(user_id), + None => entries.push(Reaction { + emoji, + user_ids: vec![user_id], + }), + } + } + + Ok(reactions) +} + +async fn polls_of( + message_ids: &[String], + conn: &Connection, +) -> Result, Error> { + let mut polls: HashMap = HashMap::new(); + if message_ids.is_empty() { + return Ok(polls); + } + + let placeholders = placeholders(message_ids.len()); + let mut rows = conn + .query( + &format!( + "SELECT message_id, question, multiple, closed FROM poll WHERE message_id IN ({placeholders})" + ), + message_ids.to_vec(), + ) + .await?; + while let Some(row) = rows.next().await? { + let multiple: i64 = row.get(2)?; + let closed: i64 = row.get(3)?; + polls.insert( + row.get(0)?, + Poll { + question: row.get(1)?, + options: Vec::new(), + multiple: multiple != 0, + closed: closed != 0, + }, + ); + } + drop(rows); + + let mut rows = conn + .query( + &format!( + "SELECT message_id, text FROM poll_option WHERE message_id IN ({placeholders}) ORDER BY message_id, position" + ), + message_ids.to_vec(), + ) + .await?; + while let Some(row) = rows.next().await? { + let message_id: String = row.get(0)?; + if let Some(poll) = polls.get_mut(&message_id) { + poll.options.push(PollOption { + text: row.get(1)?, + voter_ids: Vec::new(), + }); + } + } + drop(rows); + + let mut rows = conn + .query( + &format!( + "SELECT message_id, position, user_id FROM poll_vote WHERE message_id IN ({placeholders}) ORDER BY message_id, position, user_id" + ), + message_ids.to_vec(), + ) + .await?; + while let Some(row) = rows.next().await? { + let message_id: String = row.get(0)?; + let position: i64 = row.get(1)?; + let option = polls + .get_mut(&message_id) + .and_then(|poll| poll.options.get_mut(position as usize)); + if let Some(option) = option { + option.voter_ids.push(row.get(2)?); + } + } + + Ok(polls) +} + async fn snippet_of(message_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( @@ -60,7 +192,7 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result Result>>(6)? + .and_then(|bytes| bitcode::decode(&bytes).ok()), }, )); } @@ -90,11 +225,21 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result Result { - message.attachments = attachment::of_message(&message.id, None, conn).await?; - message.snippet = snippet_of(&message.id, conn).await?; +async fn hydrate(messages: Vec, conn: &Connection) -> Result, Error> { + let ids: Vec = messages.iter().map(|message| message.id.clone()).collect(); + let mut reactions = reactions_of(&ids, conn).await?; + let mut polls = polls_of(&ids, conn).await?; + + let mut hydrated = Vec::new(); + for mut message in messages { + message.reactions = reactions.remove(&message.id).unwrap_or_default(); + message.poll = polls.remove(&message.id); + message.attachments = attachment::of_message(&message.id, None, conn).await?; + message.snippet = snippet_of(&message.id, conn).await?; + hydrated.push(message); + } - Ok(message) + Ok(hydrated) } async fn insert( @@ -114,7 +259,7 @@ async fn insert( Ok(message_id) } -async fn ensure_in_community( +pub async fn ensure_in_community( message_id: &str, community_id: &str, conn: &Connection, @@ -132,6 +277,28 @@ async fn ensure_in_community( Ok(()) } +pub async fn create_call_log( + community_id: &str, + user_id: &str, + call: CallLog, + conn: &Connection, +) -> Result { + let message_id = new_id(); + conn.execute( + "INSERT INTO message (id, user_id, community_id, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5)", + ( + message_id.as_str(), + user_id, + community_id, + call.as_str(), + call.seconds() as i64, + ), + ) + .await?; + + read(&message_id, conn).await +} + pub async fn create( user_id: &str, community_id: &str, @@ -159,7 +326,10 @@ pub async fn read(message_id: &str, conn: &Connection) -> Result let message = from_row(&row)?; drop(rows); - hydrate(message, conn).await + hydrate(vec![message], conn) + .await? + .pop() + .ok_or(CommonError::NotFound.into()) } pub async fn read_page( @@ -183,12 +353,118 @@ pub async fn read_page( drop(rows); messages.reverse(); - let mut page = Vec::new(); - for message in messages { - page.push(hydrate(message, conn).await?); + hydrate(messages, conn).await +} + +pub async fn create_poll( + user_id: &str, + community_id: &str, + question: &str, + options: &[String], + multiple: bool, + conn: &Connection, +) -> Result { + let message_id = insert(user_id, community_id, "", None, conn).await?; + conn.execute( + "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)", + (message_id.as_str(), question, multiple as i64), + ) + .await?; + for (position, text) in options.iter().enumerate() { + conn.execute( + "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)", + (message_id.as_str(), position as i64, text.as_str()), + ) + .await?; + } + + read(&message_id, conn).await +} + +pub async fn vote( + message_id: &str, + user_id: &str, + positions: &[u32], + conn: &Connection, +) -> Result { + conn.execute( + "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2", + (message_id, user_id), + ) + .await?; + for position in positions { + conn.execute( + "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)", + (message_id, *position as i64, user_id), + ) + .await?; + } + + read(message_id, conn).await +} + +pub async fn close_poll(message_id: &str, conn: &Connection) -> Result { + let updated = conn + .execute( + "UPDATE poll SET closed = 1 WHERE message_id = ?1", + (message_id,), + ) + .await?; + if updated == 0 { + return Err(CommonError::NotFound.into()); } - Ok(page) + read(message_id, conn).await +} + +pub async fn react( + message_id: &str, + user_id: &str, + emoji: &str, + conn: &Connection, +) -> Result { + let removed = conn + .execute( + "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3", + (message_id, user_id, emoji), + ) + .await?; + if removed == 0 { + conn.execute( + "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)", + (message_id, user_id, emoji), + ) + .await?; + } + + read(message_id, conn).await +} + +pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result { + conn.execute( + "UPDATE message SET pinned = ?2 WHERE id = ?1", + (message_id, pinned as i64), + ) + .await?; + + read(message_id, conn).await +} + +pub async fn pinned(community_id: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn + .query( + &format!("{SELECT} WHERE m.community_id = ?1 AND m.pinned = 1 ORDER BY m.id DESC"), + (community_id,), + ) + .await?; + + let mut messages = Vec::new(); + while let Some(row) = rows.next().await? { + messages.push(from_row(&row)?); + } + drop(rows); + + hydrate(messages, conn).await } pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result { @@ -303,6 +579,7 @@ async fn entry(source: &Message, conn: &Connection) -> Result>>); +#[derive(Default)] +struct VisitBook { + seen: HashMap>, + watching: HashMap, +} + #[derive(Clone, Default)] -pub struct Visits(Arc>>>); +pub struct Visits(Arc>); impl Visits { pub fn first(&self, connection_id: usize, community_id: &str) -> bool { self.0 .lock() .unwrap() + .seen .entry(connection_id) .or_default() .insert(community_id.to_string()) } + pub fn watch(&self, connection_id: usize, community_id: Option<&str>) { + let watching = &mut self.0.lock().unwrap().watching; + match community_id { + Some(community_id) => watching.insert(connection_id, community_id.to_string()), + None => watching.remove(&connection_id), + }; + } + + fn watches(&self, connection_id: usize, community_id: &str) -> bool { + self.0 + .lock() + .unwrap() + .watching + .get(&connection_id) + .is_some_and(|watched| watched == community_id) + } + pub fn forget(&self, connection_id: usize) { - self.0.lock().unwrap().remove(&connection_id); + let mut book = self.0.lock().unwrap(); + book.seen.remove(&connection_id); + book.watching.remove(&connection_id); } } @@ -170,6 +196,7 @@ struct Shared { db: DB, services: Services, directory: PathBuf, + backups: PathBuf, } pub async fn serve( @@ -177,17 +204,20 @@ pub async fn serve( server_config: quinn::ServerConfig, db: DB, directory: PathBuf, + backups: PathBuf, ) -> Result<(), Error> { let endpoint = Endpoint::server(server_config, server_address.parse()?)?; info!("listening on {server_address}"); let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH); - tokio::spawn(the_actor(event_receiver)); + let services = Services::default(); + tokio::spawn(the_actor(event_receiver, services.visits.clone())); let shared = Shared { event_sender, db, - services: Services::default(), + services, directory, + backups, }; while let Some(incoming) = endpoint.accept().await { @@ -244,9 +274,11 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro if let Some((user_id, token)) = signed_in(&state) { let conn = database::connect(&shared.db).await?; authentication::seen(&user_id, &token, &conn).await?; - let broadcasts = + let mut broadcasts = request::leave_connection_voice(&shared.services.voice, Some(&connection), &conn) .await?; + broadcasts + .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); for broadcast in broadcasts { let _ = shared .event_sender @@ -298,6 +330,17 @@ async fn route( ) .await } + StreamKind::Backup => { + let user = signed_user(&state); + backup::download( + user.as_ref(), + receive_stream, + send_stream, + &shared.db, + &shared.backups, + ) + .await + } } } @@ -317,29 +360,37 @@ async fn answer( &shared.services, Some(&connection), &shared.directory, + &shared.backups, ) .await; let after = signed_in(&state); if before != after { let connection_id = connection.stable_id(); - let event = match after { + let (event, presence_user_id) = match after { Some((user_id, token)) => { shared .services .presence .sign_in(&connection, &user_id, &token); - Event::SignedIn { - connection_id, - user_id, - } + ( + Event::SignedIn { + connection_id, + user_id: user_id.clone(), + }, + Some(user_id), + ) } None => { shared.services.presence.sign_out(connection_id); - Event::SignedOut { connection_id } + let user_id = before.map(|(user_id, _)| user_id); + (Event::SignedOut { connection_id }, user_id) } }; let _ = shared.event_sender.send(event).await; + if let Some(user_id) = presence_user_id { + broadcast_presence(&shared, &user_id).await; + } } for broadcast in broadcasts { @@ -354,6 +405,24 @@ async fn answer( Ok(()) } +async fn broadcast_presence(shared: &Shared, user_id: &str) { + let broadcasts = match database::connect(&shared.db).await { + Ok(conn) => request::presence_changed(&shared.services.presence, user_id, &conn).await, + Err(error) => Err(error), + }; + match broadcasts { + Ok(broadcasts) => { + for broadcast in broadcasts { + let _ = shared + .event_sender + .send(Event::Broadcast(Box::new(broadcast))) + .await; + } + } + Err(error) => warn!("presence: {error}"), + } +} + fn signed_user(state: &Mutex) -> Option { match &*state.lock().unwrap() { State::Anonymous => None, @@ -384,7 +453,7 @@ async fn write_session(mut event_receiver: mpsc::Receiver>, mut send_s } } -async fn the_actor(mut event_receiver: mpsc::Receiver) { +async fn the_actor(mut event_receiver: mpsc::Receiver, visits: Visits) { let mut sessions: Vec = Vec::new(); while let Some(event) = event_receiver.recv().await { @@ -429,13 +498,17 @@ async fn the_actor(mut event_receiver: mpsc::Receiver) { } } Event::Broadcast(broadcast) => { + let community_id = broadcast.event.community_id().map(str::to_string); let event = Arc::new(broadcast.event); sessions.retain(|session| { let Some(user_id) = &session.user_id else { return true; }; - if !broadcast.user_ids.contains(user_id) { + let watching = community_id.as_deref().is_some_and(|community_id| { + visits.watches(session.connection_id, community_id) + }); + if !broadcast.user_ids.contains(user_id) && !watching { return true; } diff --git a/crates/server/src/notes.rs b/crates/server/src/notes.rs new file mode 100644 index 0000000..b1d8293 --- /dev/null +++ b/crates/server/src/notes.rs @@ -0,0 +1,36 @@ +use common::model::{Community, Rank}; +use turso::Connection; + +use crate::{community, error::Error, user_community}; + +async fn find(user_id: &str, conn: &Connection) -> Result, Error> { + let mut rows = conn + .query( + "SELECT community_id FROM notes WHERE user_id = ?1", + (user_id,), + ) + .await?; + + Ok(rows.next().await?.map(|row| row.get(0)).transpose()?) +} + +pub async fn open(me: &str, conn: &mut Connection) -> Result { + let tx = conn.transaction().await?; + let community_id = match find(me, &tx).await? { + Some(community_id) => community_id, + None => { + let community_id = community::create_notes(&tx).await?; + user_community::join(me, &community_id, Rank::Owner, &tx).await?; + tx.execute( + "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)", + (me, community_id.as_str()), + ) + .await?; + community_id + } + }; + let community = community::read(&community_id, me, &tx).await?; + tx.commit().await?; + + Ok(community) +} diff --git a/crates/server/src/rate_limit.rs b/crates/server/src/rate_limit.rs index fda02b8..b650b87 100644 --- a/crates/server/src/rate_limit.rs +++ b/crates/server/src/rate_limit.rs @@ -3,7 +3,10 @@ use std::{ sync::{Arc, Mutex}, }; -use common::time::{MINUTE_MILLIS, now_ms}; +use common::{ + error::Error, + time::{MINUTE_MILLIS, now_ms}, +}; const PRUNE_LENGTH: usize = 4096; @@ -11,9 +14,9 @@ const PRUNE_LENGTH: usize = 4096; pub struct RateLimit(Arc>>); impl RateLimit { - pub fn allow(&self, key: &str, limit: u32) -> bool { + pub fn allow(&self, key: &str, limit: u32) -> Result<(), Error> { if limit == 0 { - return true; + return Ok(()); } let now = now_ms(); @@ -27,10 +30,13 @@ impl RateLimit { *window = (now, 0); } if window.1 >= limit { - return false; + let wait = MINUTE_MILLIS - now.saturating_sub(window.0); + return Err(Error::RateLimited { + retry_after_seconds: wait.div_ceil(1000), + }); } window.1 += 1; - true + Ok(()) } } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index b1bc63a..2ae24e6 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -8,8 +8,8 @@ use common::{ error::Error as CommonError, event::Event, model::{ - AdminAction, CommunityKind, CommunitySummary, LogAction, Member, Rank, ReportStatus, - ServerBanKind, ServerSettings, User, VoiceRoom, + AdminAction, CallLog, CommunityKind, CommunitySummary, LogAction, Member, Presence, Rank, + ReportStatus, ServerBanKind, ServerSettings, User, VoiceRoom, }, permission, request::Request, @@ -17,21 +17,22 @@ use common::{ time::{self, MINUTE_MILLIS}, validate::{ validate_avatar_size, validate_forward, validate_message_body, validate_new_message, - validate_reason, validate_server_settings, + validate_poll, validate_reaction, validate_reason, validate_server_settings, validate_vote, }, }; use turso::Connection; use crate::{ - admin_log, attachment, authentication, community, + admin_log, attachment, authentication, backup, community, database::{self, DB}, direct, error::Error, friend, invitation, invite, log, message, - network::{Services, State}, - overview, rate_limit::RateLimit, report, server_ban, server_settings, stats, user, - user_community, - voice::{Left, Voice}, + network::{self, Services, State}, + notes, overview, + rate_limit::RateLimit, + report, server_ban, server_settings, stats, user, user_community, + voice::{CallEnd, GhostChange, Left, Voice}, }; pub struct Broadcast { @@ -48,8 +49,9 @@ pub async fn handle( services: &Services, connection: Option<&quinn::Connection>, directory: &Path, + backups: &Path, ) -> Outcome { - match dispatch(request, state, db, services, connection, directory).await { + match dispatch(request, state, db, services, connection, directory, backups).await { Ok(outcome) => outcome, Err(error) => (Response::Error(error.into()), Vec::new()), } @@ -62,6 +64,7 @@ async fn dispatch( services: &Services, connection: Option<&quinn::Connection>, directory: &Path, + backups: &Path, ) -> Result { let Services { voice, @@ -347,7 +350,10 @@ async fn dispatch( &conn, ) .await?; - let broadcasts = user_updated(&user, &conn).await?; + let mut broadcasts = user_updated(&user, &conn).await?; + if permission::is_builder(role) { + broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?); + } (Response::User(user), broadcasts) } Request::UpdateStatus { status } => { @@ -363,6 +369,23 @@ async fn dispatch( let broadcasts = user_updated(&user, &conn).await?; (Response::User(user), broadcasts) } + Request::UpdatePresence { presence: chosen } => { + let (me, _) = authenticated(state, &conn).await?; + user::update_presence(&me.id, chosen, &conn).await?; + let broadcasts = presence_changed(presence, &me.id, &conn).await?; + (Response::Done, broadcasts) + } + Request::ReadPresences => { + let (me, _) = authenticated(state, &conn).await?; + let mut presences = Vec::new(); + for user_id in related_user_ids(&me.id, &conn).await? { + let effective = effective_presence(presence, &user_id, &conn).await?; + if effective != Presence::Offline || user_id == me.id { + presences.push((user_id, effective)); + } + } + (Response::Presences(presences), Vec::new()) + } Request::UpdateAvatar { image } => { let (me, token) = authenticated(state, &conn).await?; validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?; @@ -445,7 +468,7 @@ async fn dispatch( Request::CreateCommunity { name } => { let (me, _) = authenticated(state, &conn).await?; let limit = server_settings::read(&conn).await?.max_communities_per_user; - let owned = user_community::owned(&me.id, &conn).await?.len(); + let owned = user_community::owned_groups(&me.id, &conn).await?; ensure_or( limit == 0 || owned < limit as usize, CommonError::LimitReached, @@ -459,6 +482,9 @@ async fn dispatch( } Request::ReadCommunity { community_id } => { let (me, _) = authenticated(state, &conn).await?; + ensure(permission::can_read( + actor_rank(&me, &community_id, &conn).await?, + ))?; ( Response::Community(community::read(&community_id, &me.id, &conn).await?), Vec::new(), @@ -466,7 +492,7 @@ async fn dispatch( } Request::UpdateCommunity { community_id, name } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; ensure(permission::can_rename_community( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -484,7 +510,7 @@ async fn dispatch( image, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; ensure(permission::can_rename_community( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -505,7 +531,7 @@ async fn dispatch( } Request::DeleteCommunity { community_id } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; ensure(permission::can_delete_community( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -534,7 +560,7 @@ async fn dispatch( } Request::LeaveCommunity { community_id } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; ensure(permission::can_leave( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -644,7 +670,7 @@ async fn dispatch( rank, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_set_rank( actor_rank(&me, &community_id, &conn).await?, @@ -699,7 +725,10 @@ async fn dispatch( tx.commit().await?; let members = user_community::members(&community_id, &conn).await?; let event = Event::MessageCreated(created.clone()); - (Response::Message(created), broadcast(event, &members)) + ( + Response::Message(created), + broadcast_with(event, &members, &me.id), + ) } Request::ForwardMessages { message_ids, @@ -728,7 +757,7 @@ async fn dispatch( let mut broadcasts = Vec::new(); for message in &created { let event = Event::MessageCreated(message.clone()); - broadcasts.extend(broadcast(event, &members)); + broadcasts.extend(broadcast_with(event, &members, &me.id)); } (Response::Messages(created), broadcasts) } @@ -743,7 +772,120 @@ async fn dispatch( let updated = message::update(&message_id, &body, &conn).await?; let members = user_community::members(&updated.community_id, &conn).await?; let event = Event::MessageUpdated(updated.clone()); - (Response::Message(updated), broadcast(event, &members)) + ( + Response::Message(updated), + broadcast_with(event, &members, &me.id), + ) + } + Request::CreatePoll { + community_id, + question, + options, + multiple, + } => { + let (me, _) = authenticated(state, &conn).await?; + let settings = server_settings::read(&conn).await?; + limit_messages(&me, rate_limit, &settings)?; + validate_poll(&question, &options)?; + ensure(permission::can_post( + actor_rank(&me, &community_id, &conn).await?, + ))?; + let tx = conn.transaction().await?; + let created = + message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx) + .await?; + stats::mark_active(&me.id, &tx).await?; + tx.commit().await?; + let members = user_community::members(&community_id, &conn).await?; + let event = Event::MessageCreated(created.clone()); + ( + Response::Message(created), + broadcast_with(event, &members, &me.id), + ) + } + Request::Vote { + message_id, + positions, + } => { + let (me, _) = authenticated(state, &conn).await?; + let existing = message::read(&message_id, &conn).await?; + ensure(permission::can_read( + actor_rank(&me, &existing.community_id, &conn).await?, + ))?; + let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?; + validate_vote(poll, &positions)?; + let updated = message::vote(&message_id, &me.id, &positions, &conn).await?; + let members = user_community::members(&updated.community_id, &conn).await?; + let event = Event::MessageUpdated(updated); + (Response::Done, broadcast_with(event, &members, &me.id)) + } + Request::ClosePoll { message_id } => { + let (me, _) = authenticated(state, &conn).await?; + let existing = message::read(&message_id, &conn).await?; + ensure(permission::can_close_poll( + actor_rank(&me, &existing.community_id, &conn).await?, + existing.user_id == me.id, + ))?; + let updated = message::close_poll(&message_id, &conn).await?; + let members = user_community::members(&updated.community_id, &conn).await?; + let event = Event::MessageUpdated(updated); + (Response::Done, broadcast_with(event, &members, &me.id)) + } + Request::React { message_id, emoji } => { + let (me, _) = authenticated(state, &conn).await?; + validate_reaction(&emoji)?; + let existing = message::read(&message_id, &conn).await?; + ensure(permission::can_read( + actor_rank(&me, &existing.community_id, &conn).await?, + ))?; + let updated = message::react(&message_id, &me.id, &emoji, &conn).await?; + let members = user_community::members(&updated.community_id, &conn).await?; + let event = Event::MessageUpdated(updated); + (Response::Done, broadcast_with(event, &members, &me.id)) + } + Request::Pin { message_id, pinned } => { + let (me, _) = authenticated(state, &conn).await?; + let existing = message::read(&message_id, &conn).await?; + let direct = community::is_direct(&existing.community_id, &conn).await?; + ensure(permission::can_pin( + actor_rank(&me, &existing.community_id, &conn).await?, + direct, + ))?; + let updated = message::pin(&message_id, pinned, &conn).await?; + let members = user_community::members(&updated.community_id, &conn).await?; + let event = Event::MessageUpdated(updated); + (Response::Done, broadcast_with(event, &members, &me.id)) + } + Request::Unreads => { + let (me, _) = authenticated(state, &conn).await?; + ( + Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?), + Vec::new(), + ) + } + Request::MarkRead { + community_id, + message_id, + } => { + let (me, _) = authenticated(state, &conn).await?; + ensure( + user_community::rank(&me.id, &community_id, &conn) + .await? + .is_some(), + )?; + message::ensure_in_community(&message_id, &community_id, &conn).await?; + user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?; + (Response::Done, Vec::new()) + } + Request::Pins { community_id } => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::can_read( + actor_rank(&me, &community_id, &conn).await?, + ))?; + ( + Response::Messages(message::pinned(&community_id, &conn).await?), + Vec::new(), + ) } Request::DeleteMessage { message_id } => { let (me, _) = authenticated(state, &conn).await?; @@ -778,7 +920,10 @@ async fn dispatch( } let members = user_community::members(&deleted.community_id, &conn).await?; let event = Event::MessageDeleted(deleted.clone()); - (Response::Message(deleted), broadcast(event, &members)) + ( + Response::Message(deleted), + broadcast_with(event, &members, &me.id), + ) } Request::ReadMessages { community_id, @@ -788,11 +933,20 @@ async fn dispatch( ensure(permission::can_read( actor_rank(&me, &community_id, &conn).await?, ))?; + let outsider = user_community::rank(&me.id, &community_id, &conn) + .await? + .is_none(); + if before.is_none() + && let Some(connection) = connection + { + visits.watch( + connection.stable_id(), + outsider.then_some(community_id.as_str()), + ); + } let visit = before.is_none() && permission::is_builder(me.role) - && user_community::rank(&me.id, &community_id, &conn) - .await? - .is_none() + && outsider && user::is_ghost(&me.id, &conn).await?; if visit && connection @@ -816,18 +970,34 @@ async fn dispatch( ensure(permission::can_join_voice( actor_rank(&me, &community_id, &conn).await?, ))?; - ensure(community::voice_enabled(&community_id, &conn).await?)?; + ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?; + ensure( + permission::is_builder(me.role) + || community::voice_enabled(&community_id, &conn).await?, + )?; let Some(connection) = connection else { return Err(CommonError::Server.into()); }; let members = user_community::members(&community_id, &conn).await?; let muted = user::voice_muted(&me.id, &conn).await?; - let ghost = user::is_ghost(&me.id, &conn).await?; + let outsider = user_community::rank(&me.id, &community_id, &conn) + .await? + .is_none(); + let ghost = outsider || user::is_ghost(&me.id, &conn).await?; + let starts_call = !ghost + && community::is_direct(&community_id, &conn).await? + && voice.participants(&community_id).is_empty(); let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost); let mut broadcasts = match joined { Some(previous) => voice_left(previous, &conn).await?, None => Vec::new(), }; + if starts_call { + let created = + message::create_call_log(&community_id, &me.id, CallLog::Started, &conn) + .await?; + broadcasts.extend(broadcast(Event::MessageCreated(created), &members)); + } if !ghost { let event = Event::VoiceJoined { community_id: community_id.clone(), @@ -847,6 +1017,27 @@ async fn dispatch( broadcasts, ) } + Request::Typing { community_id } => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::can_read( + actor_rank(&me, &community_id, &conn).await?, + ))?; + let broadcasts = if user::is_ghost(&me.id, &conn).await? { + Vec::new() + } else { + let members: Vec = user_community::members(&community_id, &conn) + .await? + .into_iter() + .filter(|member| member.user.id != me.id) + .collect(); + let event = Event::Typing { + community_id, + user_id: me.id.clone(), + }; + broadcast(event, &members) + }; + (Response::Done, broadcasts) + } Request::LeaveVoice => { authenticated(state, &conn).await?; ( @@ -854,6 +1045,23 @@ async fn dispatch( leave_connection_voice(voice, connection, &conn).await?, ) } + Request::DeclineCall { community_id } => { + let (me, _) = authenticated(state, &conn).await?; + ensure(community::is_direct(&community_id, &conn).await?)?; + ensure(permission::can_read( + actor_rank(&me, &community_id, &conn).await?, + ))?; + let participants = voice.participants(&community_id); + ensure(!participants.is_empty() && !participants.contains(&me.id))?; + voice.decline(&community_id); + let created = + message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?; + let members = user_community::members(&community_id, &conn).await?; + ( + Response::Done, + broadcast(Event::MessageCreated(created), &members), + ) + } Request::VoiceParticipants { community_id } => { let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_read( @@ -886,6 +1094,13 @@ async fn dispatch( }; (Response::Community(community), broadcasts) } + Request::OpenNotes => { + let (me, _) = authenticated(state, &conn).await?; + ( + Response::Community(notes::open(&me.id, &mut conn).await?), + Vec::new(), + ) + } Request::Friends => { let (me, _) = authenticated(state, &conn).await?; ( @@ -916,7 +1131,7 @@ async fn dispatch( user_id, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; ensure(permission::can_read( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -1014,7 +1229,7 @@ async fn dispatch( user_id, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(!community::is_direct(&community_id, &conn).await?)?; + ensure(!community::is_fixed(&community_id, &conn).await?)?; ensure(permission::can_transfer_ownership( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -1234,6 +1449,15 @@ async fn dispatch( .await?; (Response::MessageHits(hits), Vec::new()) } + Request::SearchCommunity { community_id, text } => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::can_read( + actor_rank(&me, &community_id, &conn).await?, + ))?; + let hits = + message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?; + (Response::MessageHits(hits), Vec::new()) + } Request::PurgeUser { user_id } => { let (me, _) = authenticated(state, &conn).await?; managed(&me, &user_id, &conn).await?; @@ -1312,6 +1536,32 @@ async fn dispatch( let (users, communities) = attachment::usage(&conn).await?; (Response::StorageUsage { users, communities }, Vec::new()) } + Request::CreateBackup => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::is_builder(me.role))?; + let backup = backup::create(&conn, backups).await?; + let action = AdminAction::BackupCreated { + name: backup.name.clone(), + }; + admin_log::record(Some(&me.id), None, None, &action, &conn).await?; + (Response::Backup(backup), Vec::new()) + } + Request::Backups => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::is_builder(me.role))?; + (Response::Backups(backup::list(backups)?), Vec::new()) + } + Request::DeleteBackup { name } => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::is_builder(me.role))?; + backup::delete(&name, backups)?; + let action = AdminAction::BackupDeleted { name }; + admin_log::record(Some(&me.id), None, None, &action, &conn).await?; + (Response::Done, Vec::new()) + } + Request::DownloadBackup { .. } => { + return Err(CommonError::Server.into()); + } Request::VoiceRooms => { let (me, _) = authenticated(state, &conn).await?; ensure(permission::is_builder(me.role))?; @@ -1390,7 +1640,7 @@ async fn dispatch( tx.commit().await?; let mut broadcasts = Vec::new(); if !enabled { - broadcasts.extend(voice_closed(voice, &community_id, &conn).await?); + broadcasts.extend(voice_silenced(voice, &community_id, &conn).await?); } let event = Event::CommunityUpdated(updated.clone()); broadcasts.extend(broadcast(event, &members)); @@ -1408,9 +1658,23 @@ async fn dispatch( }; admin_log::record(Some(&me.id), None, None, &action, &conn).await?; let mut broadcasts = Vec::new(); - if let Some((community_id, seconds)) = voice.set_ghost(&me.id, enabled) { + let outsider = match voice.room_of(&me.id) { + Some(community_id) => user_community::rank(&me.id, &community_id, &conn) + .await? + .is_none(), + None => false, + }; + if !outsider + && let Some(GhostChange { + community_id, + ghost_seconds: seconds, + call, + }) = voice.set_ghost(&me.id, enabled) + { let members = user_community::members(&community_id, &conn).await?; if enabled { + broadcasts + .extend(call_ended(&community_id, &me.id, call, &members, &conn).await?); broadcasts.push(Broadcast { event: Event::VoiceLeft { community_id, @@ -1513,10 +1777,7 @@ async fn limit_logins( ) -> Result<(), Error> { let limit = server_settings::read(conn).await?.logins_per_minute; - ensure_or( - rate_limit.allow(&address(connection), limit), - CommonError::RateLimited, - ) + Ok(rate_limit.allow(&address(connection), limit)?) } fn limit_messages( @@ -1528,10 +1789,7 @@ fn limit_messages( return Ok(()); } - ensure_or( - rate_limit.allow(&me.id, settings.messages_per_minute), - CommonError::RateLimited, - ) + Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?) } fn ensure_untaken(taken: bool) -> Result<(), Error> { @@ -1579,7 +1837,7 @@ async fn remove_member( banned, } = removal; validate_reason(reason.as_deref())?; - ensure(!community::is_direct(&community_id, conn).await?)?; + ensure(!community::is_fixed(&community_id, conn).await?)?; let target = user::read(&user_id, conn).await?; ensure(permission::can_moderate( actor_rank(me, &community_id, conn).await?, @@ -1620,20 +1878,52 @@ async fn remove_member( Ok((Response::Done, broadcasts)) } -async fn user_updated(user: &User, conn: &Connection) -> Result, Error> { - let mut user_ids = BTreeSet::from([user.id.clone()]); - for community in community::communities_of(&user.id, conn).await? { +async fn related_user_ids(user_id: &str, conn: &Connection) -> Result, Error> { + let mut user_ids = BTreeSet::from([user_id.to_string()]); + for community in community::communities_of(user_id, conn).await? { for member in user_community::members(&community.id, conn).await? { user_ids.insert(member.user.id); } } - for friend in friend::state(&user.id, conn).await?.friends { + for friend in friend::state(user_id, conn).await?.friends { user_ids.insert(friend.id); } + Ok(user_ids.into_iter().collect()) +} + +async fn user_updated(user: &User, conn: &Connection) -> Result, Error> { Ok(vec![Broadcast { event: Event::UserUpdated(user.clone()), - user_ids: user_ids.into_iter().collect(), + user_ids: related_user_ids(&user.id, conn).await?, + }]) +} + +async fn effective_presence( + presence: &network::Presence, + user_id: &str, + conn: &Connection, +) -> Result { + if !presence.user_ids().iter().any(|id| id == user_id) { + return Ok(Presence::Offline); + } + + user::presence(user_id, conn).await +} + +pub async fn presence_changed( + presence: &network::Presence, + user_id: &str, + conn: &Connection, +) -> Result, Error> { + let presence = effective_presence(presence, user_id, conn).await?; + + Ok(vec![Broadcast { + event: Event::PresenceChanged { + user_id: user_id.to_string(), + presence, + }, + user_ids: related_user_ids(user_id, conn).await?, }]) } @@ -1690,6 +1980,51 @@ async fn voice_leave( } } +async fn voice_unmuted( + voice: &Voice, + user_id: &str, + conn: &Connection, +) -> Result, Error> { + let Some(community_id) = voice.set_muted(user_id, false) else { + return Ok(Vec::new()); + }; + let mut user_ids = vec![user_id.to_string()]; + if !user::is_ghost(user_id, conn).await? { + user_ids.extend( + user_community::members(&community_id, conn) + .await? + .into_iter() + .map(|member| member.user.id), + ); + } + + Ok(vec![Broadcast { + event: Event::VoiceMuted { + user_id: user_id.to_string(), + muted: false, + }, + user_ids, + }]) +} + +async fn voice_silenced( + voice: &Voice, + community_id: &str, + conn: &Connection, +) -> Result, Error> { + let mut broadcasts = Vec::new(); + for user_id in voice.room_users(community_id) { + if permission::is_builder(user::read(&user_id, conn).await?.role) { + continue; + } + if let Some(left) = voice.leave_room(community_id, &user_id) { + broadcasts.extend(voice_left(left, conn).await?); + } + } + + Ok(broadcasts) +} + async fn voice_closed( voice: &Voice, community_id: &str, @@ -1703,15 +2038,45 @@ async fn voice_closed( Ok(broadcasts) } +fn call_log_of(end: CallEnd) -> Option { + match end { + CallEnd::Answered { seconds } => Some(CallLog::Ended { seconds }), + CallEnd::Unanswered => Some(CallLog::Missed), + CallEnd::Declined => None, + } +} + +async fn call_ended( + community_id: &str, + user_id: &str, + call: Option, + members: &[Member], + conn: &Connection, +) -> Result, Error> { + let direct = match call { + Some(_) => community::is_direct(community_id, conn).await?, + None => false, + }; + let Some(call) = call.filter(|_| direct).and_then(call_log_of) else { + return Ok(Vec::new()); + }; + let created = message::create_call_log(community_id, user_id, call, conn).await?; + + Ok(broadcast(Event::MessageCreated(created), members)) +} + async fn voice_left(left: Left, conn: &Connection) -> Result, Error> { let Some(seconds) = left.ghost_seconds else { let members = user_community::members(&left.community_id, conn).await?; + let mut broadcasts = + call_ended(&left.community_id, &left.user_id, left.call, &members, conn).await?; let event = Event::VoiceLeft { community_id: left.community_id, user_id: left.user_id, }; + broadcasts.extend(broadcast(event, &members)); - return Ok(broadcast(event, &members)); + return Ok(broadcasts); }; let community = community::label(&left.community_id, conn).await?; admin_log::record( @@ -1788,6 +2153,16 @@ pub fn ensure(allowed: bool) -> Result<(), Error> { Ok(()) } +fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Vec { + let mut broadcasts = broadcast(event, members); + for broadcast in &mut broadcasts { + if !broadcast.user_ids.iter().any(|id| id == user_id) { + broadcast.user_ids.push(user_id.to_string()); + } + } + broadcasts +} + fn broadcast(event: Event, members: &[Member]) -> Vec { vec![Broadcast { event, @@ -1825,6 +2200,7 @@ mod tests { &Services::default(), None, &test::directory(), + &test::directory(), ) .await; @@ -1848,6 +2224,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -1863,6 +2240,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; handle( @@ -1874,6 +2252,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; } @@ -1893,6 +2272,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -1910,6 +2290,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; @@ -1931,6 +2312,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -1945,6 +2327,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -1959,6 +2342,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; handle( @@ -1970,6 +2354,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; @@ -1980,6 +2365,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -1992,6 +2378,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -2017,6 +2404,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -2032,6 +2420,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -2054,6 +2443,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await else { @@ -2071,6 +2461,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; @@ -2083,6 +2474,7 @@ mod tests { &services, None, &test::directory(), + &test::directory(), ) .await; diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs index c2b1550..012a9d7 100644 --- a/crates/server/src/stats.rs +++ b/crates/server/src/stats.rs @@ -52,11 +52,7 @@ pub async fn daily(days: u32, conn: &Connection) -> Result, Error> Ok(stats) } -async fn count( - conn: &Connection, - sql: &str, - params: impl turso::IntoParams, -) -> Result { +async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result { let mut rows = conn.query(sql, params).await?; let row = rows .next() diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index 61ac3dc..8fa7fbe 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -1,7 +1,7 @@ use common::{ constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, error::{Error as CommonError, InvalidInput}, - model::{Account, Role, User}, + model::{Account, Presence, Role, User}, time, validate::{validate_avatar_size, validate_status, validate_username}, }; @@ -77,7 +77,10 @@ pub async fn any(conn: &Connection) -> Result { pub async fn by_username(username: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( - &format!("SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE", user_columns("user")), + &format!( + "SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE", + user_columns("user") + ), (username,), ) .await?; @@ -91,7 +94,10 @@ pub async fn credentials( ) -> Result, Error> { let mut rows = conn .query( - &format!("SELECT {}, password_hash FROM user WHERE username = ?1", user_columns("user")), + &format!( + "SELECT {}, password_hash FROM user WHERE username = ?1", + user_columns("user") + ), (username,), ) .await?; @@ -114,7 +120,10 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result< let mut rows = conn .query( - &format!("UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), + &format!( + "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), (user_id, username), ) .await?; @@ -128,7 +137,10 @@ pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Re let mut rows = conn .query( - &format!("UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), + &format!( + "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), (user_id, status), ) .await?; @@ -186,7 +198,10 @@ async fn set_avatar_id( ) -> Result { let mut rows = conn .query( - &format!("UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), + &format!( + "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), (user_id, avatar_id), ) .await?; @@ -210,7 +225,10 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result { let mut rows = conn .query( - &format!("UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}", user_columns("user")), + &format!( + "UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}", + user_columns("user") + ), (username, role.as_str()), ) .await?; @@ -222,7 +240,10 @@ pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result Result { let mut rows = conn .query( - &format!("UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), + &format!( + "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", + user_columns("user") + ), (user_id, role.as_str()), ) .await?; @@ -332,9 +353,36 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result { Ok(flag != 0) } +pub async fn presence(user_id: &str, conn: &Connection) -> Result { + let mut rows = conn + .query("SELECT presence FROM user WHERE id = ?1", (user_id,)) + .await?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; + let text: String = row.get(0)?; + + Ok(Presence::parse(&text).ok_or(CommonError::Server)?) +} + +pub async fn update_presence( + user_id: &str, + presence: Presence, + conn: &Connection, +) -> Result<(), Error> { + conn.execute( + "UPDATE user SET presence = ?2 WHERE id = ?1", + (user_id, presence.as_str()), + ) + .await?; + + Ok(()) +} + pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result { let mut rows = conn - .query("SELECT voice_muted FROM user WHERE id = ?1", (user_id,)) + .query( + "SELECT voice_muted AND role != ?2 FROM user WHERE id = ?1", + (user_id, Role::Builder.as_str()), + ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; let muted: i64 = row.get(0)?; @@ -384,7 +432,10 @@ pub async fn all(conn: &Connection) -> Result, Error> { pub async fn delete(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( - &format!("DELETE FROM user WHERE id = ?1 RETURNING {}", user_columns("user")), + &format!( + "DELETE FROM user WHERE id = ?1 RETURNING {}", + user_columns("user") + ), (user_id,), ) .await?; diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index 9924293..6524d5c 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -1,10 +1,10 @@ use common::{ error::Error as CommonError, - model::{Ban, Member, Rank}, + model::{Ban, Member, Rank, Unread}, }; use turso::{Connection, Row}; -use crate::{error::Error, user}; +use crate::{community, error::Error, user}; fn rank_of(row: &Row, index: usize) -> Result { let text: String = row.get(index)?; @@ -71,6 +71,49 @@ pub async fn set_rank( Ok(()) } +pub async fn mark_read( + user_id: &str, + community_id: &str, + message_id: &str, + conn: &Connection, +) -> Result<(), Error> { + conn.execute( + "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", + (user_id, community_id, message_id), + ) + .await?; + + Ok(()) +} + +pub async fn unreads( + user_id: &str, + username: &str, + conn: &Connection, +) -> Result, Error> { + let mention = format!("@{}", username.to_lowercase()); + let mut rows = conn + .query( + "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read) AND instr(lower(m.body), ?2) > 0), uc.last_read FROM user_community uc WHERE uc.user_id = ?1", + (user_id, mention.as_str()), + ) + .await?; + + let mut unreads = Vec::new(); + while let Some(row) = rows.next().await? { + let messages: i64 = row.get(1)?; + let mentions: i64 = row.get(2)?; + unreads.push(Unread { + community_id: row.get(0)?, + messages: messages as u32, + mentions: mentions as u32, + last_read: row.get::>(3)?, + }); + } + + Ok(unreads) +} + pub async fn members(community_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( @@ -90,6 +133,19 @@ pub async fn members(community_id: &str, conn: &Connection) -> Result Result { + let mut rows = conn + .query( + "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3", + (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()), + ) + .await?; + let row = rows.next().await?.ok_or(CommonError::Server)?; + let count: i64 = row.get(0)?; + + Ok(count as usize) +} + pub async fn owned(user_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( diff --git a/crates/server/src/voice.rs b/crates/server/src/voice.rs index 59805bb..2e9cce8 100644 --- a/crates/server/src/voice.rs +++ b/crates/server/src/voice.rs @@ -5,7 +5,10 @@ use std::{ }; use bytes::Bytes; -use common::voice::{SEQUENCE_LENGTH, encode_relay}; +use common::{ + time, + voice::{SEQUENCE_LENGTH, encode_relay}, +}; use quinn::Connection; struct Participant { @@ -16,13 +19,72 @@ struct Participant { joined_at: Instant, } +pub enum CallEnd { + Answered { seconds: u64 }, + Unanswered, + Declined, +} + +pub struct GhostChange { + pub community_id: String, + pub ghost_seconds: Option, + pub call: Option, +} + pub struct Left { pub community_id: String, pub user_id: String, pub ghost_seconds: Option, + pub call: Option, +} + +struct Room { + participants: Vec, + started_ms: u64, + answered: bool, + declined: bool, +} + +impl Room { + fn new() -> Self { + Self { + participants: Vec::new(), + started_ms: time::now_ms(), + answered: false, + declined: false, + } + } + + fn occupied(&self) -> bool { + self.participants + .iter() + .any(|participant| !participant.ghost) + } + + fn admit(&mut self) { + if self.occupied() { + self.answered = true; + } else { + self.started_ms = time::now_ms(); + self.answered = false; + self.declined = false; + } + } + + fn end(&self) -> CallEnd { + if self.answered { + CallEnd::Answered { + seconds: time::now_ms().saturating_sub(self.started_ms) / 1000, + } + } else if self.declined { + CallEnd::Declined + } else { + CallEnd::Unanswered + } + } } -type Rooms = HashMap>; +type Rooms = HashMap; #[derive(Clone, Default)] pub struct Voice(Arc>); @@ -38,24 +100,34 @@ impl Voice { ) -> Option { let mut rooms = self.0.lock().unwrap(); let previous = leave_locked(&mut rooms, user_id); - rooms + let room = rooms .entry(community_id.to_string()) - .or_default() - .push(Participant { - user_id: user_id.to_string(), - connection, - muted, - ghost, - joined_at: Instant::now(), - }); + .or_insert_with(Room::new); + if !ghost { + room.admit(); + } + room.participants.push(Participant { + user_id: user_id.to_string(), + connection, + muted, + ghost, + joined_at: Instant::now(), + }); previous } + pub fn decline(&self, community_id: &str) { + if let Some(room) = self.0.lock().unwrap().get_mut(community_id) { + room.declined = true; + } + } + pub fn set_muted(&self, user_id: &str, muted: bool) -> Option { let mut rooms = self.0.lock().unwrap(); for (community_id, room) in rooms.iter_mut() { if let Some(participant) = room + .participants .iter_mut() .find(|participant| participant.user_id == user_id) { @@ -68,29 +140,67 @@ impl Voice { None } - pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<(String, Option)> { + pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option { let mut rooms = self.0.lock().unwrap(); for (community_id, room) in rooms.iter_mut() { - if let Some(participant) = room - .iter_mut() - .find(|participant| participant.user_id == user_id) - { - if participant.ghost == ghost { - return None; - } - let seconds = participant - .ghost - .then(|| participant.joined_at.elapsed().as_secs()); - participant.ghost = ghost; - participant.joined_at = Instant::now(); - - return Some((community_id.clone(), seconds)); + let Some(index) = room + .participants + .iter() + .position(|participant| participant.user_id == user_id) + else { + continue; + }; + if room.participants[index].ghost == ghost { + return None; } + if !ghost { + room.admit(); + } + let participant = &mut room.participants[index]; + let seconds = participant + .ghost + .then(|| participant.joined_at.elapsed().as_secs()); + participant.ghost = ghost; + participant.joined_at = Instant::now(); + let call = (ghost && !room.occupied()).then(|| room.end()); + + return Some(GhostChange { + community_id: community_id.clone(), + ghost_seconds: seconds, + call, + }); } None } + pub fn room_users(&self, community_id: &str) -> Vec { + self.0 + .lock() + .unwrap() + .get(community_id) + .map(|room| { + room.participants + .iter() + .map(|participant| participant.user_id.clone()) + .collect() + }) + .unwrap_or_default() + } + + pub fn room_of(&self, user_id: &str) -> Option { + self.0 + .lock() + .unwrap() + .iter() + .find(|(_, room)| { + room.participants + .iter() + .any(|participant| participant.user_id == user_id) + }) + .map(|(community_id, _)| community_id.clone()) + } + pub fn leave(&self, user_id: &str) -> Option { leave_locked(&mut self.0.lock().unwrap(), user_id) } @@ -107,7 +217,12 @@ impl Voice { } pub fn count(&self) -> usize { - self.0.lock().unwrap().values().map(Vec::len).sum() + self.0 + .lock() + .unwrap() + .values() + .map(|room| room.participants.len()) + .sum() } pub fn participants(&self, community_id: &str) -> Vec { @@ -116,7 +231,8 @@ impl Voice { .unwrap() .get(community_id) .map(|room| { - room.iter() + room.participants + .iter() .filter(|participant| !participant.ghost) .map(|participant| participant.user_id.clone()) .collect() @@ -131,10 +247,12 @@ impl Voice { .iter() .map(|(community_id, room)| { let user_ids = room + .participants .iter() .map(|participant| participant.user_id.clone()) .collect(); let ghost_ids = room + .participants .iter() .filter(|participant| participant.ghost) .map(|participant| participant.user_id.clone()) @@ -150,16 +268,18 @@ impl Voice { .lock() .unwrap() .remove(community_id) + .map(|room| room.participants) .unwrap_or_default() .into_iter() - .map(|participant| left(community_id, participant)) + .map(|participant| left(community_id, participant, None)) .collect() } pub fn relay(&self, connection_id: usize, packet: &[u8]) { let rooms = self.0.lock().unwrap(); let Some(room) = rooms.values().find(|room| { - room.iter() + room.participants + .iter() .any(|participant| participant.connection.stable_id() == connection_id) }) else { return; @@ -167,7 +287,7 @@ impl Voice { let Some(sender) = find(&rooms, connection_id) else { return; }; - if sender.muted || sender.ghost { + if sender.muted { return; } let (Some(relay), Some(echo)) = ( @@ -180,6 +300,7 @@ impl Voice { let bytes = Bytes::from(relay); for participant in room + .participants .iter() .filter(|participant| participant.user_id != sender.user_id) { @@ -191,38 +312,42 @@ impl Voice { fn find(rooms: &Rooms, connection_id: usize) -> Option<&Participant> { rooms .values() - .flatten() + .flat_map(|room| &room.participants) .find(|participant| participant.connection.stable_id() == connection_id) } -fn left(community_id: &str, participant: Participant) -> Left { +fn left(community_id: &str, participant: Participant, call: Option) -> Left { Left { community_id: community_id.to_string(), user_id: participant.user_id, ghost_seconds: participant .ghost .then(|| participant.joined_at.elapsed().as_secs()), + call, } } fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option { let room = rooms.get_mut(community_id)?; let index = room + .participants .iter() .position(|participant| participant.user_id == user_id)?; - let participant = room.remove(index); - if room.is_empty() { + let participant = room.participants.remove(index); + let call = (!participant.ghost && !room.occupied()).then(|| room.end()); + if room.participants.is_empty() { rooms.remove(community_id); } - Some(left(community_id, participant)) + Some(left(community_id, participant, call)) } fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option { let community_id = rooms .iter() .find(|(_, room)| { - room.iter() + room.participants + .iter() .any(|participant| participant.user_id == user_id) }) .map(|(community_id, _)| community_id.clone())?;