forge
Explore
Log in

Don't you dare go Hollow

Add reactions, pins, polls, notes, voice notes, unread tracking, search and backups

Browse files at this commit

040a711f69c00b30da067a46858f4fd796317d44Ahmet Kaan GümüşParent: a16328a
  • feat
    • add reactions, pins, polls, notes, voice notes, unread tracking, search and backups
Show full message
✨ feat: add reactions, pins, polls, notes, voice notes, unread tracking, search and backups

- markdown rendering with syntax highlighting, formatting shortcuts and cheat sheet
- emoji reactions, pinned messages and pinned poll banner
- polls with single/multiple choice, closing and forwarded snapshots
- private notes community
- voice notes with live and playback waveforms
- typing indicator, unread counts, mentions, new-messages divider and jump to bottom
- message search for members and go to message
- composer drafts
- connection status notice
- builder database backup and export
- tray, mutes and voice stats

62 changed files +7424 -761

.gitignoremodified+2 -0
@@ -3,3 +3,5 @@ Cargo.lock
3 configs/server_config.toml3 configs/server_config.toml
4 *.pem4 *.pem
5 yumush.db*5 yumush.db*
6+attachments/
7+backups/
crates/client/Cargo.tomlmodified+2 -1
@@ -8,7 +8,7 @@ common.workspace = true
8 tokio.workspace = true8 tokio.workspace = true
9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
10 10
11-gpui-kit = "0.11.0"11+gpui-kit = { version = "0.11.0", features = ["syntect"] }
12 ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }12 ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }
13 ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }13 ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }
14 ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }14 ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" }
@@ -33,6 +33,7 @@ rtrb = "0.4.1"
33 33
34 [target.'cfg(target_os = "linux")'.dependencies]34 [target.'cfg(target_os = "linux")'.dependencies]
35 pipewire = { version = "0.10.1", features = ["v0_3_49"] }35 pipewire = { version = "0.10.1", features = ["v0_3_49"] }
36+ksni = "0.3.7"
36 37
37 [target.'cfg(target_os = "windows")'.dependencies]38 [target.'cfg(target_os = "windows")'.dependencies]
38 wasapi = "0.27.0"39 wasapi = "0.27.0"
crates/client/src/gui.rsmodified+451 -38
@@ -3,33 +3,40 @@ use std::{
3 fmt::Display,3 fmt::Display,
4 hash::{DefaultHasher, Hash, Hasher},4 hash::{DefaultHasher, Hash, Hasher},
5 sync::Arc,5 sync::Arc,
6+ time::Duration,
6 };7 };
7 8
8 use common::{9 use common::{
9 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},10 constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH},
10 error::Error,11 error::Error,
11 event::Event,12 event::Event,
12- model::{Community, CommunityKind, Rank, ServerSettings, User},13+ model::{
14+ BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, ServerSettings,
15+ Unread, User, mentions,
16+ },
13 time::created_at_ms,17 time::created_at_ms,
14 };18 };
15 use gpui_kit::{19 use gpui_kit::{
16- AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight,20+ Anchor, Animation, AnimationElement, AnimationExt, AnyElement, AnyWindowHandle, App,
17- Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent,21+ AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight, Hsla, Image,
18- KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful,22+ ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, KeyUpEvent,
23+ ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful,
19 StatefulInteractiveElement, Styled, WeakEntity, Window, actions,24 StatefulInteractiveElement, Styled, WeakEntity, Window, actions,
20 base::Selectable,25 base::Selectable,
21 component::{26 component::{
22- ActiveTheme, Theme, WindowExt,27+ ActiveTheme, Sizable, Theme, WindowExt,
23 input::{Input, InputEvent, InputState},28 input::{Input, InputEvent, InputState},
24 notification::Notification,29 notification::Notification,
30+ spinner::Spinner,
25 },31 },
26- div, hsla, img, px, rems, rgb,32+ div, ease_out_quint, hsla, img, px, rems, rgb,
27 };33 };
28 use jiff::{Timestamp, tz::TimeZone};34 use jiff::{Timestamp, tz::TimeZone};
29 use tokio::sync::mpsc;35 use tokio::sync::mpsc;
30 36
31 use crate::{37 use crate::{
32 accounts::{self, Accounts},38 accounts::{self, Accounts},
39+ mutes,
33 network::{NetworkEvent, NetworkHandle},40 network::{NetworkEvent, NetworkHandle},
34 settings::{Look, Scale, Settings, ThemeChoice},41 settings::{Look, Scale, Settings, ThemeChoice},
35 };42 };
@@ -42,12 +49,15 @@ mod composer;
42 mod forward;49 mod forward;
43 mod media_view;50 mod media_view;
44 mod message_actions;51 mod message_actions;
52+mod poll;
45 mod profile;53 mod profile;
46 mod settings_page;54 mod settings_page;
47 mod sidebar;55 mod sidebar;
48 mod snippet;56 mod snippet;
49 mod social;57 mod social;
58+mod voice_note;
50 mod voice_settings;59 mod voice_settings;
60+mod voice_stats;
51 61
52 use auth::Auth;62 use auth::Auth;
53 use chat::{Chat, View};63 use chat::{Chat, View};
@@ -99,7 +109,7 @@ impl Palette {
99 return self;109 return self;
100 };110 };
101 let (id, avatar_id) = match &community.kind {111 let (id, avatar_id) = match &community.kind {
102- CommunityKind::Group => (&community.id, &community.avatar_id),112+ CommunityKind::Group | CommunityKind::Notes => (&community.id, &community.avatar_id),
103 CommunityKind::Direct { peer } => (&peer.id, &peer.avatar_id),113 CommunityKind::Direct { peer } => (&peer.id, &peer.avatar_id),
104 };114 };
105 let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) {115 let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) {
@@ -250,7 +260,9 @@ pub fn avatar(
250 pub fn community_name(community: &Community) -> &str {260 pub fn community_name(community: &Community) -> &str {
251 match &community.kind {261 match &community.kind {
252 CommunityKind::Group => &community.name,262 CommunityKind::Group => &community.name,
253- CommunityKind::Direct { peer } => &peer.username,263+ CommunityKind::Direct { peer } if community.name.is_empty() => &peer.username,
264+ CommunityKind::Direct { .. } => &community.name,
265+ CommunityKind::Notes => "Notes",
254 }266 }
255 }267 }
256 268
@@ -272,6 +284,7 @@ pub fn community_icon(
272 None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)),284 None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)),
273 },285 },
274 CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars),286 CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars),
287+ CommunityKind::Notes => badge(palette, &community.id, "Notes", size, font).rounded(px(4.)),
275 }288 }
276 }289 }
277 290
@@ -314,6 +327,42 @@ pub fn millis_time(millis: u64, format: &str) -> String {
314 .to_string()327 .to_string()
315 }328 }
316 329
330+const MOTION_TRAVEL: f32 = 6.;
331+
332+pub fn motion() -> Animation {
333+ Animation::new(Duration::from_millis(160)).with_easing(ease_out_quint())
334+}
335+
336+pub fn pop_in<E: IntoElement + Styled + 'static>(
337+ id: impl Into<ElementId>,
338+ element: E,
339+ anchor: Anchor,
340+) -> AnimationElement<E> {
341+ let travel = match anchor.is_bottom() {
342+ true => MOTION_TRAVEL,
343+ false => -MOTION_TRAVEL,
344+ };
345+
346+ element.with_animation(id, motion(), move |element, delta| {
347+ element.top(px(travel * (1. - delta))).opacity(delta)
348+ })
349+}
350+
351+pub fn swap_in<E: IntoElement + Styled + 'static>(
352+ id: impl Into<ElementId>,
353+ element: E,
354+ forward: bool,
355+) -> AnimationElement<E> {
356+ let travel = match forward {
357+ true => MOTION_TRAVEL,
358+ false => -MOTION_TRAVEL,
359+ };
360+
361+ element.with_animation(id, motion(), move |element, delta| {
362+ element.left(px(travel * (1. - delta))).opacity(delta)
363+ })
364+}
365+
317 pub fn hoverable(id: impl Into<ElementId>, element: Div, palette: Palette) -> Stateful<Div> {366 pub fn hoverable(id: impl Into<ElementId>, element: Div, palette: Palette) -> Stateful<Div> {
318 hoverable_with(id, element, palette.hover)367 hoverable_with(id, element, palette.hover)
319 }368 }
@@ -429,11 +478,41 @@ pub fn rank_tag(rank: Option<Rank>, palette: Palette) -> Option<Div> {
429 )478 )
430 }479 }
431 480
481+pub fn presence_color(presence: Presence, palette: Palette) -> Hsla {
482+ match presence {
483+ Presence::Online => palette.ok,
484+ Presence::Busy => palette.danger,
485+ Presence::Offline => palette.muted,
486+ }
487+}
488+
489+pub fn presence_avatar(
490+ avatar: impl IntoElement,
491+ presence: Presence,
492+ size: Pixels,
493+ palette: Palette,
494+) -> Div {
495+ let dot = if size > px(20.) { px(10.) } else { px(8.) };
496+
497+ div().relative().flex_shrink_0().child(avatar).child(
498+ div()
499+ .absolute()
500+ .right(px(-2.))
501+ .bottom(px(-2.))
502+ .size(dot)
503+ .rounded_full()
504+ .border_2()
505+ .border_color(palette.window)
506+ .bg(presence_color(presence, palette)),
507+ )
508+}
509+
432 pub fn bind_keys(cx: &mut App) {510 pub fn bind_keys(cx: &mut App) {
433 cx.bind_keys([511 cx.bind_keys([
434 KeyBinding::new(FIND_KEY, FocusFind, None),512 KeyBinding::new(FIND_KEY, FocusFind, None),
435 KeyBinding::new("escape", CloseSettings, None),513 KeyBinding::new("escape", CloseSettings, None),
436 ]);514 ]);
515+ composer::bind_keys(cx);
437 }516 }
438 517
439 #[derive(Debug, Clone, Copy, PartialEq, Eq)]518 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -443,19 +522,83 @@ enum Route {
443 Chat,522 Chat,
444 }523 }
445 524
525+#[derive(Debug, Clone, PartialEq)]
526+enum Connection {
527+ Connecting,
528+ Connected,
529+ Lost { error: String, attempts: u32 },
530+}
531+
532+impl Connection {
533+ fn is_connected(&self) -> bool {
534+ matches!(self, Self::Connected)
535+ }
536+
537+ fn lost(&mut self, error: &Error) {
538+ let attempts = match self {
539+ Self::Lost { attempts, .. } => *attempts + 1,
540+ _ => 1,
541+ };
542+ *self = Self::Lost {
543+ error: reason(error),
544+ attempts,
545+ };
546+ }
547+}
548+
549+fn reason(error: &Error) -> String {
550+ let text = error.to_string();
551+ let lower = text.to_lowercase();
552+ if lower.contains("timed out") || lower.contains("unreachable") {
553+ "Server unreachable".into()
554+ } else if lower.contains("certificate") || lower.contains("tls") {
555+ "Certificate error".into()
556+ } else if lower.contains("refused") {
557+ "Connection refused".into()
558+ } else {
559+ text
560+ }
561+}
562+
563+fn connection_notice(connection: &Connection, palette: Palette) -> Option<Div> {
564+ let (label, color) = match connection {
565+ Connection::Connecting => ("Connecting…".to_string(), palette.muted),
566+ Connection::Connected => return None,
567+ Connection::Lost { error, attempts } => {
568+ (format!("Reconnecting… {error} ({attempts})"), palette.alert)
569+ }
570+ };
571+ Some(
572+ div()
573+ .h(px(22.))
574+ .flex()
575+ .items_center()
576+ .justify_center()
577+ .gap(px(6.))
578+ .text_size(text(11.))
579+ .text_color(color)
580+ .child(Spinner::new().xsmall().color(color))
581+ .child(label),
582+ )
583+}
584+
446 pub struct Yumush {585 pub struct Yumush {
447 user: Option<User>,586 user: Option<User>,
448 current_route: Route,587 current_route: Route,
449 auth: Auth,588 auth: Auth,
450 chat: Chat,589 chat: Chat,
451 network: NetworkHandle,590 network: NetworkHandle,
452- connected: bool,591+ connection: Connection,
453 server: Option<ServerSettings>,592 server: Option<ServerSettings>,
454 dismissed_announcement: Option<String>,593 dismissed_announcement: Option<String>,
455 settings: Settings,594 settings: Settings,
456 accounts: Accounts,595 accounts: Accounts,
457 voice: VoiceControls,596 voice: VoiceControls,
458 focus: gpui_kit::FocusHandle,597 focus: gpui_kit::FocusHandle,
598+ window: Option<AnyWindowHandle>,
599+ deferred: Vec<NetworkEvent>,
600+ backups: Vec<BackupInfo>,
601+ pending_backup_delete: Option<String>,
459 }602 }
460 603
461 impl Yumush {604 impl Yumush {
@@ -468,31 +611,30 @@ impl Yumush {
468 ) -> Self {611 ) -> Self {
469 network.set_voice_settings(settings.voice.clone());612 network.set_voice_settings(settings.voice.clone());
470 613
471- cx.spawn_in(window, async move |this, cx| {614+ cx.spawn(async move |this, cx| {
472 while let Some(event) = network_event_receiver.recv().await {615 while let Some(event) = network_event_receiver.recv().await {
473- let updated = this.update_in(cx, |yumush, window, cx| {616+ let Ok(handle) = this.read_with(cx, |yumush, _| yumush.window) else {
474- yumush.handle_network_event(event, window, cx);617+ break;
475- });618+ };
476-619+ let mut event = Some(event);
477- if updated.is_err() {620+ if let Some(handle) = handle {
621+ let _ = handle.update(cx, |_, window, cx| {
622+ if let Some(event) = event.take() {
623+ let _ = this.update(cx, |yumush, cx| {
624+ yumush.handle_network_event(event, Some(window), cx)
625+ });
626+ }
627+ });
628+ }
629+ if let Some(event) = event
630+ && this
631+ .update(cx, |yumush, cx| {
632+ yumush.handle_network_event(event, None, cx)
633+ })
634+ .is_err()
635+ {
478 break;636 break;
479 }637 }
480- }
481- })
482- .detach();
483-
484- cx.observe_window_appearance(window, |yumush, window, cx| {
485- if yumush.settings.theme == ThemeChoice::System {
486- Theme::sync_system_appearance(Some(window), cx);
487- sync_theme(cx);
488- }
489- cx.notify();
490- })
491- .detach();
492-
493- cx.observe_window_activation(window, |yumush, window, _| {
494- if !window.is_window_active() {
495- yumush.network.set_talking(false);
496 }638 }
497 })639 })
498 .detach();640 .detach();
@@ -506,15 +648,63 @@ impl Yumush {
506 auth: Auth::new(window, cx),648 auth: Auth::new(window, cx),
507 chat: Chat::new(window, cx),649 chat: Chat::new(window, cx),
508 network,650 network,
509- connected: false,651+ connection: Connection::Connecting,
510 server: None,652 server: None,
511 dismissed_announcement: None,653 dismissed_announcement: None,
512 settings,654 settings,
513 accounts: accounts::load(),655 accounts: accounts::load(),
514 voice,656 voice,
657+ window: None,
658+ deferred: Vec::new(),
659+ backups: Vec::new(),
660+ pending_backup_delete: None,
515 }661 }
516 }662 }
517 663
664+ pub fn tray_state(&self) -> crate::tray::TrayState {
665+ let groups = self.chat.unread_total(true);
666+ let direct = self.chat.unread_total(false);
667+ crate::tray::TrayState {
668+ messages: groups.messages + direct.messages,
669+ mentions: groups.mentions + direct.mentions,
670+ }
671+ }
672+
673+ pub fn attach_window(&mut self, window: &mut Window, cx: &mut Context<Self>) {
674+ self.window = Some(window.window_handle());
675+
676+ cx.observe_window_appearance(window, |yumush, window, cx| {
677+ if yumush.settings.theme == ThemeChoice::System {
678+ Theme::sync_system_appearance(Some(window), cx);
679+ sync_theme(cx);
680+ }
681+ cx.notify();
682+ })
683+ .detach();
684+
685+ cx.observe_window_activation(window, |yumush, window, cx| {
686+ if window.is_window_active() {
687+ yumush.read_selected(cx);
688+ } else {
689+ yumush.network.set_talking(false);
690+ }
691+ })
692+ .detach();
693+
694+ for event in std::mem::take(&mut self.deferred) {
695+ self.handle_network_event(event, Some(window), cx);
696+ }
697+ }
698+
699+ pub fn window(&self) -> Option<AnyWindowHandle> {
700+ self.window
701+ }
702+
703+ pub fn detach_window(&mut self) -> bool {
704+ self.window = None;
705+ self.settings.close_to_tray
706+ }
707+
518 pub(super) fn enter_session(708 pub(super) fn enter_session(
519 &mut self,709 &mut self,
520 user: User,710 user: User,
@@ -524,6 +714,7 @@ impl Yumush {
524 ) {714 ) {
525 self.accounts.sign_in(&user, token);715 self.accounts.sign_in(&user, token);
526 self.request_user_avatar(&user, cx);716 self.request_user_avatar(&user, cx);
717+ self.chat.muted = mutes::load(&user.id);
527 self.user = Some(user);718 self.user = Some(user);
528 self.change_page(Route::Chat, window, cx);719 self.change_page(Route::Chat, window, cx);
529 self.load_communities(window, cx);720 self.load_communities(window, cx);
@@ -540,7 +731,7 @@ impl Yumush {
540 let Some(account) = self.accounts.get(&user_id).cloned() else {731 let Some(account) = self.accounts.get(&user_id).cloned() else {
541 return;732 return;
542 };733 };
543- if !self.connected {734+ if !self.connection.is_connected() {
544 window.push_notification(Notification::error("Not connected"), cx);735 window.push_notification(Notification::error("Not connected"), cx);
545 return;736 return;
546 }737 }
@@ -584,6 +775,17 @@ impl Yumush {
584 cx.notify();775 cx.notify();
585 }776 }
586 777
778+ pub(super) fn toggle_community_mute(&mut self, community_id: String, cx: &mut Context<Self>) {
779+ let Some(me) = self.user.as_ref().map(|me| me.id.clone()) else {
780+ return;
781+ };
782+ if !self.chat.muted.remove(&community_id) {
783+ self.chat.muted.insert(community_id);
784+ }
785+ mutes::save(&me, &self.chat.muted);
786+ cx.notify();
787+ }
788+
587 fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {789 fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
588 let Some(user) = self.user.take() else {790 let Some(user) = self.user.take() else {
589 return;791 return;
@@ -667,6 +869,33 @@ impl Yumush {
667 self.user.as_ref().and_then(|me| self.chat.my_rank(me))869 self.user.as_ref().and_then(|me| self.chat.my_rank(me))
668 }870 }
669 871
872+ pub fn community_badge(
873+ &self,
874+ community: &Community,
875+ size: Pixels,
876+ font: Rems,
877+ palette: Palette,
878+ ) -> Div {
879+ let icon = community_icon(palette, community, size, font, &self.chat.avatars);
880+ match &community.kind {
881+ CommunityKind::Direct { peer } => {
882+ presence_avatar(icon, self.presence_of(&peer.id), size, palette)
883+ }
884+ CommunityKind::Group | CommunityKind::Notes => icon,
885+ }
886+ }
887+
888+ pub fn presence_of(&self, user_id: &str) -> Presence {
889+ if self.is_me(user_id) && !self.connection.is_connected() {
890+ return Presence::Offline;
891+ }
892+ self.chat
893+ .presences
894+ .get(user_id)
895+ .copied()
896+ .unwrap_or(Presence::Offline)
897+ }
898+
670 pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context<Self>) {899 pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context<Self>) {
671 if self.chat.avatars.contains_key(avatar_id)900 if self.chat.avatars.contains_key(avatar_id)
672 || self.chat.avatar_requests.contains(avatar_id)901 || self.chat.avatar_requests.contains(avatar_id)
@@ -724,13 +953,114 @@ impl Yumush {
724 user_id,953 user_id,
725 muted: true,954 muted: true,
726 } if self.is_me(user_id) => self.force_mute(cx),955 } if self.is_me(user_id) => self.force_mute(cx),
956+ Event::Typing { .. } => {
957+ cx.spawn(async move |this, cx| {
958+ cx.background_executor().timer(chat::TYPING_TTL).await;
959+ let _ = this.update(cx, |_, cx| cx.notify());
960+ })
961+ .detach();
962+ }
727 _ => {}963 _ => {}
728 }964 }
729- self.chat.apply_event(event);965+ self.chat
966+ .apply_event(event, self.user.as_ref().map(|user| user.id.as_str()));
967+ self.request_authors(cx);
730 self.request_social_avatars(cx);968 self.request_social_avatars(cx);
731 self.request_media(cx);969 self.request_media(cx);
732 }970 }
733 971
972+ fn mark_read(&mut self, community_id: &str, message_id: &str, cx: &mut Context<Self>) {
973+ self.chat.mark_read(community_id, message_id);
974+ let network = self.network.clone();
975+ let community_id = community_id.to_string();
976+ let message_id = message_id.to_string();
977+
978+ cx.spawn(async move |_, _| {
979+ let _ = network.mark_read(&community_id, &message_id).await;
980+ })
981+ .detach();
982+ }
983+
984+ fn read_selected(&mut self, cx: &mut Context<Self>) {
985+ let Some(community_id) = self.chat.selected_community_id.clone() else {
986+ return;
987+ };
988+ let Some(message_id) = self.chat.messages.last().map(|message| message.id.clone()) else {
989+ return;
990+ };
991+ if self
992+ .chat
993+ .unread
994+ .get(&community_id)
995+ .is_some_and(|unread| unread.messages > 0)
996+ {
997+ self.mark_read(&community_id, &message_id, cx);
998+ }
999+ }
1000+
1001+ fn count_message(&mut self, message: &Message, active: bool, cx: &mut Context<Self>) {
1002+ let Some(me) = self.user.as_ref() else {
1003+ return;
1004+ };
1005+ if message.user_id == me.id {
1006+ return;
1007+ }
1008+ if active && self.chat.is_selected(&message.community_id) {
1009+ self.mark_read(&message.community_id, &message.id, cx);
1010+ return;
1011+ }
1012+ let unread = self
1013+ .chat
1014+ .unread
1015+ .entry(message.community_id.clone())
1016+ .or_insert_with(|| Unread {
1017+ community_id: message.community_id.clone(),
1018+ messages: 0,
1019+ mentions: 0,
1020+ last_read: None,
1021+ });
1022+ unread.messages += 1;
1023+ if mentions(&message.body, &me.username) {
1024+ unread.mentions += 1;
1025+ }
1026+ }
1027+
1028+ fn should_notify(&self, message: &Message, active: bool) -> bool {
1029+ let Some(me) = self.user.as_ref() else {
1030+ return false;
1031+ };
1032+ let viewing = active && self.chat.is_selected(&message.community_id);
1033+
1034+ message.user_id != me.id
1035+ && message.call.is_none()
1036+ && !self.chat.muted.contains(&message.community_id)
1037+ && self.presence_of(&me.id) == Presence::Online
1038+ && !viewing
1039+ }
1040+
1041+ fn starts_call(&self, community_id: &str, user_id: &str) -> bool {
1042+ !self.is_me(user_id)
1043+ && self.chat.voice_ids(community_id).is_empty()
1044+ && self.is_direct(community_id)
1045+ }
1046+
1047+ fn ends_call(&self, community_id: &str, user_id: &str) -> bool {
1048+ !self.is_me(user_id)
1049+ && self.chat.in_voice(community_id)
1050+ && self.is_direct(community_id)
1051+ && self
1052+ .chat
1053+ .voice_ids(community_id)
1054+ .iter()
1055+ .all(|id| id == user_id || self.is_me(id))
1056+ }
1057+
1058+ pub(super) fn is_direct(&self, community_id: &str) -> bool {
1059+ self.chat.communities().iter().any(|community| {
1060+ community.id == community_id && matches!(community.kind, CommunityKind::Direct { .. })
1061+ })
1062+ }
1063+
734 fn is_me(&self, user_id: &str) -> bool {1064 fn is_me(&self, user_id: &str) -> bool {
735 self.user.as_ref().is_some_and(|me| me.id == user_id)1065 self.user.as_ref().is_some_and(|me| me.id == user_id)
736 }1066 }
@@ -792,20 +1122,70 @@ impl Yumush {
792 fn handle_network_event(1122 fn handle_network_event(
793 &mut self,1123 &mut self,
794 event: NetworkEvent,1124 event: NetworkEvent,
795- window: &mut Window,1125+ window: Option<&mut Window>,
796 cx: &mut Context<Self>,1126 cx: &mut Context<Self>,
797 ) {1127 ) {
1128+ let active = window
1129+ .as_ref()
1130+ .is_some_and(|window| window.is_window_active());
1131+ if let NetworkEvent::Pushed(pushed) = &event
1132+ && let Event::MessageCreated(message) = pushed.as_ref()
1133+ && self.should_notify(message, active)
1134+ {
1135+ self.network.play_notification();
1136+ }
1137+
1138+ if let NetworkEvent::Pushed(pushed) = &event
1139+ && let Event::MessageCreated(message) = pushed.as_ref()
1140+ {
1141+ self.count_message(message, active, cx);
1142+ }
1143+
1144+ if let NetworkEvent::Pushed(pushed) = &event
1145+ && let Event::MessageCreated(message) = pushed.as_ref()
1146+ && message.call == Some(CallLog::Declined)
1147+ && self.chat.in_voice(&message.community_id)
1148+ {
1149+ self.end_voice(cx);
1150+ }
1151+
1152+ if let NetworkEvent::Pushed(pushed) = &event
1153+ && let Event::VoiceJoined {
1154+ community_id,
1155+ user_id,
1156+ } = pushed.as_ref()
1157+ && self.starts_call(community_id, user_id)
1158+ {
1159+ self.chat.ringing.insert(community_id.clone());
1160+ }
1161+
1162+ if let NetworkEvent::Pushed(pushed) = &event
1163+ && let Event::VoiceLeft {
1164+ community_id,
1165+ user_id,
1166+ } = pushed.as_ref()
1167+ && self.ends_call(community_id, user_id)
1168+ {
1169+ self.end_voice(cx);
1170+ }
1171+
1172+ let Some(window) = window else {
1173+ self.handle_hidden(event, cx);
1174+ return;
1175+ };
1176+
798 match event {1177 match event {
799 NetworkEvent::Connected => {1178 NetworkEvent::Connected => {
800- self.connected = true;1179+ self.connection = Connection::Connected;
801 self.load_server_settings(window, cx);1180 self.load_server_settings(window, cx);
802 if self.user.is_some() {1181 if self.user.is_some() {
803 self.reload(window, cx);1182 self.reload(window, cx);
1183+ self.rejoin_voice(window, cx);
804 } else if let Some(active) = self.accounts.active.clone() {1184 } else if let Some(active) = self.accounts.active.clone() {
805 self.switch_account(active, window, cx);1185 self.switch_account(active, window, cx);
806 }1186 }
807 }1187 }
808- NetworkEvent::Disconnected(_) => self.connected = false,1188+ NetworkEvent::Disconnected(error) => self.connection.lost(&error),
809 NetworkEvent::SessionLost => {1189 NetworkEvent::SessionLost => {
810 if let Some(user) = &self.user {1190 if let Some(user) = &self.user {
811 self.accounts.forget(&user.id.clone());1191 self.accounts.forget(&user.id.clone());
@@ -860,6 +1240,33 @@ impl Yumush {
860 },1240 },
861 }1241 }
862 1242
1243+ self.update_ringing(cx);
1244+ cx.notify();
1245+ }
1246+
1247+ fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context<Self>) {
1248+ match event {
1249+ NetworkEvent::Connected => {
1250+ self.connection = Connection::Connected;
1251+ self.deferred.push(NetworkEvent::Connected);
1252+ }
1253+ NetworkEvent::Disconnected(error) => self.connection.lost(&error),
1254+ NetworkEvent::SessionLost => self.deferred.push(NetworkEvent::SessionLost),
1255+ NetworkEvent::Pushed(event) => match *event {
1256+ Event::MemberLeft { .. }
1257+ | Event::Removed { .. }
1258+ | Event::CommunityDeleted { .. }
1259+ | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)),
1260+ Event::Announcement { text } => {
1261+ if let Some(settings) = self.server.as_mut() {
1262+ settings.announcement = text;
1263+ }
1264+ }
1265+ event => self.apply_pushed(event, cx),
1266+ },
1267+ }
1268+
1269+ self.update_ringing(cx);
863 cx.notify();1270 cx.notify();
864 }1271 }
865 }1272 }
@@ -951,8 +1358,13 @@ impl Render for Yumush {
951 Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(),1358 Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(),
952 Route::Chat => self.chat_page(cx).into_any_element(),1359 Route::Chat => self.chat_page(cx).into_any_element(),
953 };1360 };
1361+ let banner = (route == Route::Chat)
1362+ .then(|| connection_notice(&self.connection, palette))
1363+ .flatten();
954 1364
955 div()1365 div()
1366+ .flex()
1367+ .flex_col()
956 .size_full()1368 .size_full()
957 .bg(palette.window)1369 .bg(palette.window)
958 .text_color(palette.text)1370 .text_color(palette.text)
@@ -977,6 +1389,7 @@ impl Render for Yumush {
977 .on_modifiers_changed(cx.listener(|this, event: &ModifiersChangedEvent, _, cx| {1389 .on_modifiers_changed(cx.listener(|this, event: &ModifiersChangedEvent, _, cx| {
978 this.voice_modifiers(event, cx);1390 this.voice_modifiers(event, cx);
979 }))1391 }))
980- .child(page)1392+ .children(banner)
1393+ .child(div().flex_1().min_h_0().child(page))
981 }1394 }
982 }1395 }
crates/client/src/gui/auth.rsmodified+6 -3
@@ -1,4 +1,5 @@
1 use super::{1 use super::{
2+ Tooltip as _,
2 settings_page::{segment, segment_track},3 settings_page::{segment, segment_track},
3 text,4 text,
4 };5 };
@@ -11,8 +12,8 @@ use gpui_kit::{
11 use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon};12 use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon};
12 13
13 use crate::gui::{14 use crate::gui::{
14- Palette, Route, Yumush, badge, clickable, hoverable, new_input, notify_error, palette,15+ Palette, Route, Yumush, badge, clickable, connection_notice, hoverable, new_input,
15- primary_button,16+ notify_error, palette, primary_button,
16 };17 };
17 18
18 pub struct Auth {19 pub struct Auth {
@@ -186,7 +187,8 @@ impl Yumush {
186 .child(field(palette, &self.auth.username_input))187 .child(field(palette, &self.auth.username_input))
187 .child(password_field(palette, &self.auth.password_input))188 .child(password_field(palette, &self.auth.password_input))
188 .children(invite)189 .children(invite)
189- .child(action_button),190+ .child(action_button)
191+ .children(connection_notice(&self.connection, palette)),
190 )192 )
191 }193 }
192 }194 }
@@ -237,6 +239,7 @@ impl Yumush {
237 });239 });
238 },240 },
239 )241 )
242+ .tip("Forget")
240 .size(px(22.))243 .size(px(22.))
241 .flex()244 .flex()
242 .items_center()245 .items_center()
crates/client/src/gui/builder.rsmodified+1 -0
@@ -1,4 +1,5 @@
1 mod access;1 mod access;
2+mod backups;
2 mod communities;3 mod communities;
3 mod log;4 mod log;
4 mod messages;5 mod messages;
crates/client/src/gui/builder/backups.rsadded+210 -0
@@ -0,0 +1,210 @@
1+use common::model::BackupInfo;
2+use gpui_kit::{
3+ Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,
4+ component::Icon, div, prelude::FluentBuilder as _, px,
5+};
6+
7+use super::ui::{accent_button, card, card_header, list_row};
8+use crate::gui::{
9+ DATE, Palette, Tooltip, Yumush, clickable, entity_action, millis_time, notify_error, storage,
10+ text,
11+};
12+
13+fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity<Yumush>, palette: Palette) -> Div {
14+ let export_name = info.name.clone();
15+ let export = clickable(
16+ format!("export_backup_{}", info.name),
17+ palette,
18+ entity_action(entity, move |yumush, window, cx| {
19+ yumush.export_backup(&export_name, window, cx)
20+ }),
21+ )
22+ .tip("Export")
23+ .size(px(26.))
24+ .flex()
25+ .flex_shrink_0()
26+ .items_center()
27+ .justify_center()
28+ .rounded(px(6.))
29+ .text_color(palette.muted)
30+ .child(Icon::new(IconName::Download).w(px(14.)).h(px(14.)));
31+
32+ let delete_name = info.name.clone();
33+ let delete = clickable(
34+ format!("delete_backup_{}", info.name),
35+ palette,
36+ entity_action(entity, move |yumush, window, cx| {
37+ yumush.delete_backup(&delete_name, window, cx)
38+ }),
39+ )
40+ .tip(if pending { "Confirm" } else { "Delete" })
41+ .size(px(26.))
42+ .flex()
43+ .flex_shrink_0()
44+ .items_center()
45+ .justify_center()
46+ .rounded(px(6.))
47+ .text_color(palette.danger)
48+ .when(pending, |this| {
49+ this.bg(palette.danger).text_color(palette.on_accent)
50+ })
51+ .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.)));
52+
53+ list_row()
54+ .child(
55+ Icon::new(IconName::HardDrive)
56+ .w(px(16.))
57+ .h(px(16.))
58+ .flex_shrink_0()
59+ .text_color(palette.muted),
60+ )
61+ .child(
62+ div()
63+ .flex_1()
64+ .min_w_0()
65+ .truncate()
66+ .text_size(text(13.))
67+ .text_color(palette.text)
68+ .child(info.name.clone()),
69+ )
70+ .child(
71+ div()
72+ .flex_shrink_0()
73+ .text_size(text(12.))
74+ .text_color(palette.muted)
75+ .child(millis_time(info.created_ms, DATE)),
76+ )
77+ .child(
78+ div()
79+ .w(px(72.))
80+ .flex_shrink_0()
81+ .flex()
82+ .justify_end()
83+ .text_size(text(12.))
84+ .text_color(palette.muted)
85+ .child(storage(info.size_bytes)),
86+ )
87+ .child(export)
88+ .child(delete)
89+}
90+
91+impl Yumush {
92+ pub(super) fn backups_card(&self, entity: &Entity<Self>, palette: Palette) -> Div {
93+ let create = accent_button(
94+ "create_backup",
95+ "Create",
96+ palette,
97+ entity_action(entity, |yumush, window, cx| {
98+ yumush.create_backup(window, cx)
99+ }),
100+ )
101+ .into_any_element();
102+ let rows: Vec<Div> = self
103+ .backups
104+ .iter()
105+ .map(|info| {
106+ let pending = self.pending_backup_delete.as_deref() == Some(info.name.as_str());
107+ backup_row(info, pending, entity, palette)
108+ })
109+ .collect();
110+ let body = if rows.is_empty() {
111+ div()
112+ .py(px(24.))
113+ .flex()
114+ .justify_center()
115+ .text_size(text(12.))
116+ .text_color(palette.muted)
117+ .child("No backups")
118+ } else {
119+ div()
120+ .flex()
121+ .flex_col()
122+ .children(rows.into_iter().enumerate().map(|(index, row)| {
123+ row.when(index > 0, |row| {
124+ row.border_t_1().border_color(palette.border)
125+ })
126+ }))
127+ };
128+
129+ card(palette)
130+ .child(card_header("Backups", vec![create], palette))
131+ .child(body)
132+ }
133+
134+ pub(super) fn load_backups(&self, window: &mut Window, cx: &mut Context<Self>) {
135+ if !self.is_builder() {
136+ return;
137+ }
138+ let network = self.network.clone();
139+
140+ cx.spawn_in(window, async move |this, cx| {
141+ let backups = match network.backups().await {
142+ Ok(backups) => backups,
143+ Err(error) => {
144+ notify_error(&this, cx, error);
145+ return;
146+ }
147+ };
148+
149+ let _ = this.update(cx, |yumush, cx| {
150+ yumush.backups = backups;
151+ cx.notify();
152+ });
153+ })
154+ .detach();
155+ }
156+
157+ fn create_backup(&self, window: &mut Window, cx: &mut Context<Self>) {
158+ let network = self.network.clone();
159+
160+ cx.spawn_in(window, async move |this, cx| {
161+ match network.create_backup().await {
162+ Ok(_) => {
163+ let _ =
164+ this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx));
165+ }
166+ Err(error) => notify_error(&this, cx, error),
167+ }
168+ })
169+ .detach();
170+ }
171+
172+ fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
173+ if self.pending_backup_delete.as_deref() != Some(name) {
174+ self.pending_backup_delete = Some(name.to_string());
175+ cx.notify();
176+ return;
177+ }
178+ self.pending_backup_delete = None;
179+ let network = self.network.clone();
180+ let name = name.to_string();
181+
182+ cx.spawn_in(window, async move |this, cx| {
183+ match network.delete_backup(&name).await {
184+ Ok(()) => {
185+ let _ =
186+ this.update_in(cx, |yumush, window, cx| yumush.load_backups(window, cx));
187+ }
188+ Err(error) => notify_error(&this, cx, error),
189+ }
190+ })
191+ .detach();
192+ }
193+
194+ fn export_backup(&self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
195+ let directory = dirs::download_dir().unwrap_or_else(std::env::temp_dir);
196+ let target = cx.prompt_for_new_path(&directory, Some(name));
197+ let network = self.network.clone();
198+ let name = name.to_string();
199+
200+ cx.spawn_in(window, async move |this, cx| {
201+ let Ok(Ok(Some(target))) = target.await else {
202+ return;
203+ };
204+ if let Err(error) = network.download_backup(&name, target).await {
205+ notify_error(&this, cx, error);
206+ }
207+ })
208+ .detach();
209+ }
210+}
crates/client/src/gui/builder/communities.rsmodified+75 -14
@@ -1,4 +1,4 @@
1-use common::model::{Community, CommunitySummary, Member, Rank};1+use common::model::{Community, CommunityKind, CommunitySummary, Member, Rank};
2 use gpui_kit::{2 use gpui_kit::{
3 AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,3 AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
4 assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px,4 assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px,
@@ -10,7 +10,7 @@ use super::{
10 };10 };
11 use crate::gui::{11 use crate::gui::{
12 Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text,12 Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text,
13- entity_action, notify_error, text,13+ entity_action, notify_error, profile::user_link, text,
14 };14 };
15 15
16 fn rows_body(rows: Vec<Div>, empty: &str, palette: Palette) -> Div {16 fn rows_body(rows: Vec<Div>, empty: &str, palette: Palette) -> Div {
@@ -226,6 +226,57 @@ impl Yumush {
226 .detach();226 .detach();
227 }227 }
228 228
229+ pub(super) fn jump_to(
230+ &mut self,
231+ community_id: String,
232+ voice: bool,
233+ window: &mut Window,
234+ cx: &mut Context<Self>,
235+ ) {
236+ if let Some(community) = self
237+ .chat
238+ .communities()
239+ .iter()
240+ .find(|community| community.id == community_id)
241+ .cloned()
242+ {
243+ self.enter(community, voice, window, cx);
244+ return;
245+ }
246+ let network = self.network.clone();
247+
248+ cx.spawn_in(window, async move |this, cx| {
249+ match network.read_community(&community_id).await {
250+ Ok(community) => {
251+ let _ = this.update_in(cx, |yumush, window, cx| {
252+ yumush.enter(community, voice, window, cx)
253+ });
254+ }
255+ Err(error) => notify_error(&this, cx, error),
256+ }
257+ })
258+ .detach();
259+ }
260+
261+ fn enter(
262+ &mut self,
263+ community: Community,
264+ voice: bool,
265+ window: &mut Window,
266+ cx: &mut Context<Self>,
267+ ) {
268+ let community_id = community.id.clone();
269+ if self.chat.joined(&community_id) {
270+ let direct = matches!(community.kind, CommunityKind::Direct { .. });
271+ self.go_to_community(community_id.clone(), direct, window, cx);
272+ } else {
273+ self.open_builder_community(community, window, cx);
274+ }
275+ if voice && !self.chat.in_voice(&community_id) {
276+ self.toggle_voice(community_id, window, cx);
277+ }
278+ }
279+
229 pub(super) fn open_builder_community(280 pub(super) fn open_builder_community(
230 &mut self,281 &mut self,
231 community: Community,282 community: Community,
@@ -295,19 +346,29 @@ impl Yumush {
295 .flex()346 .flex()
296 .items_center()347 .items_center()
297 .gap(px(8.))348 .gap(px(8.))
298- .child(avatar(
299- palette,
300- &member.user,
301- px(20.),
302- text(10.),
303- &self.chat.avatars,
304- ))
305 .child(349 .child(
306- div()350+ div().flex_1().min_w_0().flex().child(user_link(
307- .flex_1()351+ format!("transfer_user_{}", member.user.id),
308- .min_w_0()352+ Some(&member.user),
309- .truncate()353+ entity,
310- .child(member.user.username.clone()),354+ div()
355+ .flex()
356+ .items_center()
357+ .gap(px(8.))
358+ .child(avatar(
359+ palette,
360+ &member.user,
361+ px(20.),
362+ text(10.),
363+ &self.chat.avatars,
364+ ))
365+ .child(
366+ div()
367+ .min_w_0()
368+ .truncate()
369+ .child(member.user.username.clone()),
370+ ),
371+ )),
311 )372 )
312 .child(plain_button(373 .child(plain_button(
313 format!("transfer_to_{}", member.user.id),374 format!("transfer_to_{}", member.user.id),
crates/client/src/gui/builder/log.rsmodified+6 -0
@@ -76,6 +76,9 @@ fn builder_log_text(entry: &AdminLogEntry) -> String {
76 AdminAction::GhostVoice { seconds } => {76 AdminAction::GhostVoice { seconds } => {
77 format!("{actor} listened in {community} as ghost for {seconds}s")77 format!("{actor} listened in {community} as ghost for {seconds}s")
78 }78 }
79+ AdminAction::BackupCreated { name } => format!("{actor} created backup {name}"),
80+ AdminAction::BackupDeleted { name } => format!("{actor} deleted backup {name}"),
81+ AdminAction::BackupDownloaded { name } => format!("{actor} exported backup {name}"),
79 }82 }
80 }83 }
81 84
@@ -146,6 +149,9 @@ fn action_icon(action: &AdminAction) -> IconName {
146 | AdminAction::GhostDisabled149 | AdminAction::GhostDisabled
147 | AdminAction::GhostVisit150 | AdminAction::GhostVisit
148 | AdminAction::GhostVoice { .. } => IconName::Eye,151 | AdminAction::GhostVoice { .. } => IconName::Eye,
152+ AdminAction::BackupCreated { .. }
153+ | AdminAction::BackupDeleted { .. }
154+ | AdminAction::BackupDownloaded { .. } => IconName::HardDrive,
149 }155 }
150 }156 }
151 157
crates/client/src/gui/builder/messages.rsmodified+37 -17
@@ -11,13 +11,11 @@ use crate::gui::{
11 auth::field,11 auth::field,
12 avatar,12 avatar,
13 community_settings::{search_text, user_name},13 community_settings::{search_text, user_name},
14- entity_action, id_time, notify_error, text,14+ entity_action, id_time, notify_error,
15+ profile::user_link,
16+ text,
15 };17 };
16 18
17-fn fixed(width: f32, control: impl IntoElement) -> Div {
18- div().w(px(width)).flex_shrink_0().child(control)
19-}
20-
21 fn message_hit_row(19 fn message_hit_row(
22 hit: &MessageHit,20 hit: &MessageHit,
23 pending: bool,21 pending: bool,
@@ -27,6 +25,17 @@ fn message_hit_row(
27 palette: Palette,25 palette: Palette,
28 ) -> Div {26 ) -> Div {
29 let message_id = hit.message.id.clone();27 let message_id = hit.message.id.clone();
28+ let community_id = hit.message.community_id.clone();
29+ let open = icon_button(
30+ format!("open_message_{}", hit.message.id),
31+ IconName::MessageSquare,
32+ "Open chat",
33+ palette.muted,
34+ palette,
35+ entity_action(entity, move |yumush, window, cx| {
36+ yumush.jump_to(community_id.clone(), false, window, cx)
37+ }),
38+ );
30 let delete = icon_button(39 let delete = icon_button(
31 format!("delete_message_{}", hit.message.id),40 format!("delete_message_{}", hit.message.id),
32 IconName::Trash,41 IconName::Trash,
@@ -43,7 +52,7 @@ fn message_hit_row(
43 let purge = hit.author.as_ref().map(|author| {52 let purge = hit.author.as_ref().map(|author| {
44 let user_id = author.id.clone();53 let user_id = author.id.clone();
45 icon_button(54 icon_button(
46- format!("purge_message_user_{}", author.id),55+ format!("purge_message_user_{}", hit.message.id),
47 IconName::UserX,56 IconName::UserX,
48 if purge_pending {57 if purge_pending {
49 "Confirm purge"58 "Confirm purge"
@@ -62,7 +71,12 @@ fn message_hit_row(
62 });71 });
63 72
64 list_row()73 list_row()
65- .child(picture)74+ .child(user_link(
75+ format!("hit_picture_{}", hit.message.id),
76+ hit.author.as_ref(),
77+ entity,
78+ picture,
79+ ))
66 .child(80 .child(
67 div()81 div()
68 .flex_1()82 .flex_1()
@@ -76,15 +90,17 @@ fn message_hit_row(
76 .items_center()90 .items_center()
77 .gap(px(6.))91 .gap(px(6.))
78 .min_w_0()92 .min_w_0()
79- .child(93+ .child(user_link(
94+ format!("hit_author_{}", hit.message.id),
95+ hit.author.as_ref(),
96+ entity,
80 div()97 div()
81- .min_w_0()
82 .truncate()98 .truncate()
83 .text_size(text(13.))99 .text_size(text(13.))
84 .font_weight(FontWeight::MEDIUM)100 .font_weight(FontWeight::MEDIUM)
85 .text_color(palette.text)101 .text_color(palette.text)
86 .child(user_name(&hit.author).to_string()),102 .child(user_name(&hit.author).to_string()),
87- )103+ ))
88 .child(104 .child(
89 div()105 div()
90 .min_w_0()106 .min_w_0()
@@ -115,6 +131,7 @@ fn message_hit_row(
115 .items_center()131 .items_center()
116 .gap(px(4.))132 .gap(px(4.))
117 .flex_shrink_0()133 .flex_shrink_0()
134+ .child(open)
118 .child(delete)135 .child(delete)
119 .children(purge),136 .children(purge),
120 )137 )
@@ -139,15 +156,18 @@ impl Yumush {
139 .child(156 .child(
140 div()157 div()
141 .flex()158 .flex()
159+ .flex_wrap()
142 .items_center()160 .items_center()
143 .gap(px(8.))161 .gap(px(8.))
144- .child(fixed(180., field(palette, &self.chat.builder_message_user)))162+ .children(
145- .child(fixed(163+ [
146- 180.,164+ &self.chat.builder_message_user,
147- field(palette, &self.chat.builder_message_community),165+ &self.chat.builder_message_community,
148- ))166+ &self.chat.builder_message_from,
149- .child(fixed(150., field(palette, &self.chat.builder_message_from)))167+ &self.chat.builder_message_to,
150- .child(fixed(150., field(palette, &self.chat.builder_message_to)))168+ ]
169+ .map(|input| div().flex_1().min_w(px(140.)).child(field(palette, input))),
170+ )
151 .child(accent_button(171 .child(accent_button(
152 "search_messages",172 "search_messages",
153 "Search",173 "Search",
crates/client/src/gui/builder/reports.rsmodified+21 -9
@@ -16,6 +16,7 @@ use crate::{
16 Palette, Yumush, avatar, badge, clickable,16 Palette, Yumush, avatar, badge, clickable,
17 community_settings::user_name,17 community_settings::user_name,
18 entity_action, id_time, notify_error,18 entity_action, id_time, notify_error,
19+ profile::user_link,
19 settings_page::{segment, segment_track},20 settings_page::{segment, segment_track},
20 text,21 text,
21 },22 },
@@ -235,26 +236,37 @@ impl Yumush {
235 .flex()236 .flex()
236 .items_center()237 .items_center()
237 .gap(px(8.))238 .gap(px(8.))
238- .child(target_avatar)239+ .child(user_link(
239- .child(240+ format!("report_target_{}", report.id),
241+ report.target.as_ref(),
242+ entity,
240 div()243 div()
241- .font_weight(FontWeight::MEDIUM)244+ .flex()
242- .truncate()245+ .items_center()
243- .child(user_name(&report.target).to_string()),246+ .gap(px(8.))
244- )247+ .child(target_avatar)
248+ .child(
249+ div()
250+ .font_weight(FontWeight::MEDIUM)
251+ .truncate()
252+ .child(user_name(&report.target).to_string()),
253+ ),
254+ ))
245 .child(pill(255 .child(pill(
246 status_label(report.status),256 status_label(report.status),
247 status_color(report.status, palette),257 status_color(report.status, palette),
248 palette,258 palette,
249 ))259 ))
250- .child(260+ .child(user_link(
261+ format!("report_reporter_{}", report.id),
262+ report.reporter.as_ref(),
263+ entity,
251 div()264 div()
252- .min_w_0()
253 .text_size(text(11.))265 .text_size(text(11.))
254 .text_color(palette.muted)266 .text_color(palette.muted)
255 .truncate()267 .truncate()
256 .child(format!("reported by {}", user_name(&report.reporter))),268 .child(format!("reported by {}", user_name(&report.reporter))),
257- );269+ ));
258 let meta = div()270 let meta = div()
259 .flex_shrink_0()271 .flex_shrink_0()
260 .text_size(text(11.))272 .text_size(text(11.))
crates/client/src/gui/builder/storage.rsmodified+6 -1
@@ -256,7 +256,11 @@ impl Yumush {
256 .child(card_header("Attachments", vec![controls], palette))256 .child(card_header("Attachments", vec![controls], palette))
257 .child(body);257 .child(body);
258 258
259- vec![usage.into_any_element(), attachments.into_any_element()]259+ vec![
260+ usage.into_any_element(),
261+ attachments.into_any_element(),
262+ self.backups_card(entity, palette).into_any_element(),
263+ ]
260 }264 }
261 265
262 pub(super) fn load_storage(&self, window: &mut Window, cx: &mut Context<Self>) {266 pub(super) fn load_storage(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -264,6 +268,7 @@ impl Yumush {
264 return;268 return;
265 }269 }
266 self.search_attachments(window, cx);270 self.search_attachments(window, cx);
271+ self.load_backups(window, cx);
267 let network = self.network.clone();272 let network = self.network.clone();
268 273
269 cx.spawn_in(window, async move |this, cx| {274 cx.spawn_in(window, async move |this, cx| {
crates/client/src/gui/builder/ui.rsmodified+89 -0
@@ -53,6 +53,95 @@ pub(super) fn icon_button(
53 .child(Icon::new(icon).w(px(14.)).h(px(14.)))53 .child(Icon::new(icon).w(px(14.)).h(px(14.)))
54 }54 }
55 55
56+pub(super) fn action_button(
57+ id: String,
58+ icon: IconName,
59+ label: &'static str,
60+ tip: &'static str,
61+ color: Hsla,
62+ palette: Palette,
63+ action: impl Fn(&mut Window, &mut App) + 'static,
64+) -> Stateful<Div> {
65+ clickable(id, palette, action)
66+ .tip(tip)
67+ .h(px(28.))
68+ .px(px(10.))
69+ .flex()
70+ .items_center()
71+ .gap(px(6.))
72+ .rounded(px(6.))
73+ .text_size(text(12.))
74+ .font_weight(FontWeight::MEDIUM)
75+ .text_color(color)
76+ .child(Icon::new(icon).w(px(14.)).h(px(14.)))
77+ .child(label)
78+}
79+
80+pub(super) fn confirm_button(
81+ id: String,
82+ icon: IconName,
83+ label: &'static str,
84+ tip: &'static str,
85+ pending: bool,
86+ palette: Palette,
87+ action: impl Fn(&mut Window, &mut App) + 'static,
88+) -> Stateful<Div> {
89+ action_button(
90+ id,
91+ icon,
92+ if pending { "Confirm" } else { label },
93+ if pending {
94+ "Click again to confirm"
95+ } else {
96+ tip
97+ },
98+ palette.danger,
99+ palette,
100+ action,
101+ )
102+ .when(pending, |this| {
103+ this.bg(palette.danger).text_color(palette.on_accent)
104+ })
105+}
106+
107+pub(super) fn action_group(
108+ title: &'static str,
109+ palette: Palette,
110+ children: Vec<AnyElement>,
111+) -> Option<Div> {
112+ if children.is_empty() {
113+ return None;
114+ }
115+
116+ Some(
117+ div()
118+ .flex()
119+ .items_start()
120+ .gap(px(12.))
121+ .child(
122+ div()
123+ .w(px(88.))
124+ .h(px(28.))
125+ .flex_shrink_0()
126+ .flex()
127+ .items_center()
128+ .text_size(text(11.))
129+ .font_weight(FontWeight::MEDIUM)
130+ .text_color(palette.muted)
131+ .child(title),
132+ )
133+ .child(
134+ div()
135+ .flex_1()
136+ .min_w_0()
137+ .flex()
138+ .flex_col()
139+ .gap(px(4.))
140+ .child(div().flex().flex_wrap().gap(px(4.)).children(children)),
141+ ),
142+ )
143+}
144+
56 pub(super) fn danger_button(145 pub(super) fn danger_button(
57 id: String,146 id: String,
58 label: &'static str,147 label: &'static str,
crates/client/src/gui/builder/users.rsmodified+129 -63
@@ -15,11 +15,14 @@ use gpui_kit::{
15 px,15 px,
16 };16 };
17 17
18-use super::ui::{accent_button, card, danger_button, pill, plain_button};18+use super::ui::{
19+ accent_button, action_button, action_group, card, confirm_button, pill, plain_button,
20+};
19 use crate::{21 use crate::{
20 gui::{22 gui::{
21 DATE, DAY, Palette, Tooltip as _, Yumush, auth::field, avatar, clickable,23 DATE, DAY, Palette, Tooltip as _, Yumush, auth::field, avatar, clickable,
22- community_settings::search_text, entity_action, id_time, millis_time, notify_error, text,24+ community_settings::search_text, entity_action, id_time, millis_time, notify_error,
25+ profile::user_link, text,
23 },26 },
24 network::NetworkHandle,27 network::NetworkHandle,
25 };28 };
@@ -45,10 +48,6 @@ fn status(label: &str, color: gpui_kit::Hsla, palette: Palette) -> Div {
45 div().flex_shrink_0().child(pill(label, color, palette))48 div().flex_shrink_0().child(pill(label, color, palette))
46 }49 }
47 50
48-fn divider(palette: Palette) -> Div {
49- div().w(px(1.)).h(px(16.)).mx(px(4.)).bg(palette.border)
50-}
51-
52 impl Yumush {51 impl Yumush {
53 pub(super) fn submit_new_user(&mut self, window: &mut Window, cx: &mut Context<Self>) {52 pub(super) fn submit_new_user(&mut self, window: &mut Window, cx: &mut Context<Self>) {
54 let username = self.chat.new_username.read(cx).text().to_string();53 let username = self.chat.new_username.read(cx).text().to_string();
@@ -419,6 +418,7 @@ impl Yumush {
419 .px(px(14.))418 .px(px(14.))
420 .py(px(10.))419 .py(px(10.))
421 .flex()420 .flex()
421+ .flex_wrap()
422 .items_center()422 .items_center()
423 .gap(px(8.))423 .gap(px(8.))
424 .border_b_1()424 .border_b_1()
@@ -426,19 +426,19 @@ impl Yumush {
426 .child(426 .child(
427 div()427 div()
428 .flex_1()428 .flex_1()
429- .min_w_0()429+ .min_w(px(160.))
430 .child(Input::new(&self.chat.builder_search)),430 .child(Input::new(&self.chat.builder_search)),
431 )431 )
432 .child(432 .child(
433 div()433 div()
434- .w(px(160.))434+ .flex_1()
435- .flex_shrink_0()435+ .min_w(px(120.))
436 .child(field(palette, &self.chat.new_username)),436 .child(field(palette, &self.chat.new_username)),
437 )437 )
438 .child(438 .child(
439 div()439 div()
440- .w(px(160.))440+ .flex_1()
441- .flex_shrink_0()441+ .min_w(px(120.))
442 .child(field(palette, &self.chat.new_password)),442 .child(field(palette, &self.chat.new_password)),
443 )443 )
444 .child(accent_button(444 .child(accent_button(
@@ -549,9 +549,12 @@ impl Yumush {
549 ) -> Div {549 ) -> Div {
550 let revoke_user_id = user_id.to_string();550 let revoke_user_id = user_id.to_string();
551 let session_id = session.id.clone();551 let session_id = session.id.clone();
552- let revoke_button = plain_button(552+ let revoke_button = action_button(
553 format!("revoke_session_{}", session.id),553 format!("revoke_session_{}", session.id),
554+ IconName::LogOut,
554 "Revoke",555 "Revoke",
556+ "End this session",
557+ palette.muted,
555 palette,558 palette,
556 entity_action(entity, move |yumush, window, cx| {559 entity_action(entity, move |yumush, window, cx| {
557 yumush.revoke_builder_session(&revoke_user_id, &session_id, window, cx)560 yumush.revoke_builder_session(&revoke_user_id, &session_id, window, cx)
@@ -564,15 +567,21 @@ impl Yumush {
564 };567 };
565 568
566 div()569 div()
567- .h(px(36.))570+ .w_full()
568- .pl(px(40.))571+ .h(px(28.))
569- .pr(px(12.))
570 .flex()572 .flex()
571 .items_center()573 .items_center()
572 .gap(px(8.))574 .gap(px(8.))
575+ .child(
576+ Icon::new(IconName::Monitor)
577+ .w(px(14.))
578+ .h(px(14.))
579+ .text_color(palette.muted),
580+ )
573 .child(581 .child(
574 div()582 div()
575 .flex_1()583 .flex_1()
584+ .text_size(text(12.))
576 .min_w_0()585 .min_w_0()
577 .truncate()586 .truncate()
578 .child(device.to_string()),587 .child(device.to_string()),
@@ -685,40 +694,65 @@ impl Yumush {
685 let seen = seen_text(account.last_seen);694 let seen = seen_text(account.last_seen);
686 let next_role = if builder { Role::User } else { Role::Builder };695 let next_role = if builder { Role::User } else { Role::Builder };
687 696
688- let role_button = plain_button(697+ let tone = palette.text;
698+ let role_button = action_button(
689 format!("role_{}", user.id),699 format!("role_{}", user.id),
700+ if builder {
701+ IconName::ShieldOff
702+ } else {
703+ IconName::Shield
704+ },
690 if builder {705 if builder {
691 "Remove builder"706 "Remove builder"
692 } else {707 } else {
693 "Make builder"708 "Make builder"
694 },709 },
710+ if builder {
711+ "Revoke admin tools"
712+ } else {
713+ "Grant admin tools"
714+ },
715+ tone,
695 palette,716 palette,
696 entity_action(entity, move |yumush, window, cx| {717 entity_action(entity, move |yumush, window, cx| {
697 yumush.set_builder_role(&role_id, next_role, window, cx)718 yumush.set_builder_role(&role_id, next_role, window, cx)
698 }),719 }),
699 );720 );
700 721
701- let suspend_button = plain_button(722+ let suspend_button = action_button(
702 format!("suspend_user_{}", user.id),723 format!("suspend_user_{}", user.id),
724+ IconName::CirclePause,
703 if suspended { "Unsuspend" } else { "Suspend" },725 if suspended { "Unsuspend" } else { "Suspend" },
726+ if suspended {
727+ "Allow sign in again"
728+ } else {
729+ "Block sign in until lifted"
730+ },
731+ tone,
704 palette,732 palette,
705 entity_action(entity, move |yumush, window, cx| {733 entity_action(entity, move |yumush, window, cx| {
706 yumush.suspend_builder_user(&suspend_id, !suspended, window, cx)734 yumush.suspend_builder_user(&suspend_id, !suspended, window, cx)
707 }),735 }),
708 );736 );
709 737
710- let sessions_button = plain_button(738+ let sessions_button = action_button(
711 format!("sessions_user_{}", user.id),739 format!("sessions_user_{}", user.id),
740+ IconName::LogOut,
712 "Sign out",741 "Sign out",
742+ "End every session",
743+ tone,
713 palette,744 palette,
714 entity_action(entity, move |yumush, window, cx| {745 entity_action(entity, move |yumush, window, cx| {
715 yumush.revoke_builder_sessions(&sessions_id, window, cx)746 yumush.revoke_builder_sessions(&sessions_id, window, cx)
716 }),747 }),
717 );748 );
718 749
719- let password_button = plain_button(750+ let password_button = action_button(
720 format!("password_user_{}", user.id),751 format!("password_user_{}", user.id),
721- "Reset password",752+ IconName::KeyRound,
753+ "Password",
754+ "Set a new password",
755+ tone,
722 palette,756 palette,
723 entity_action(entity, move |yumush, _, cx| {757 entity_action(entity, move |yumush, _, cx| {
724 yumush.toggle_builder_password(&password_id, cx)758 yumush.toggle_builder_password(&password_id, cx)
@@ -732,7 +766,7 @@ impl Yumush {
732 yumush.toggle_builder_sessions(&sessions_list_id, window, cx)766 yumush.toggle_builder_sessions(&sessions_list_id, window, cx)
733 }),767 }),
734 )768 )
735- .tip("Actions")769+ .tip("Manage")
736 .size(px(28.))770 .size(px(28.))
737 .flex_shrink_0()771 .flex_shrink_0()
738 .flex()772 .flex()
@@ -743,45 +777,59 @@ impl Yumush {
743 .when(expanded, |this| this.bg(palette.hover))777 .when(expanded, |this| this.bg(palette.hover))
744 .child(Icon::new(IconName::Ellipsis).w(px(16.)).h(px(16.)));778 .child(Icon::new(IconName::Ellipsis).w(px(16.)).h(px(16.)));
745 779
746- let rename_button = plain_button(780+ let rename_button = action_button(
747 format!("rename_user_{}", user.id),781 format!("rename_user_{}", user.id),
782+ IconName::Pencil,
748 "Rename",783 "Rename",
784+ "Change username",
785+ tone,
749 palette,786 palette,
750 entity_action(entity, move |yumush, _, cx| {787 entity_action(entity, move |yumush, _, cx| {
751 yumush.toggle_builder_rename(&rename_id, cx)788 yumush.toggle_builder_rename(&rename_id, cx)
752 }),789 }),
753 );790 );
754 791
755- let timeout_button = plain_button(792+ let timeout_button = action_button(
756 format!("timeout_user_{}", user.id),793 format!("timeout_user_{}", user.id),
794+ IconName::Timer,
757 "Timeout",795 "Timeout",
796+ "Block sign in for a while",
797+ tone,
758 palette,798 palette,
759 entity_action(entity, move |yumush, _, cx| {799 entity_action(entity, move |yumush, _, cx| {
760 yumush.toggle_builder_timeout(&timeout_id, cx)800 yumush.toggle_builder_timeout(&timeout_id, cx)
761 }),801 }),
762 );802 );
763 803
764- let ban_button = plain_button(804+ let ban_button = action_button(
765 format!("ban_user_{}", user.id),805 format!("ban_user_{}", user.id),
806+ IconName::Ban,
766 "Ban",807 "Ban",
808+ "Ban username or IP from the server",
809+ tone,
767 palette,810 palette,
768 entity_action(entity, move |yumush, _, cx| {811 entity_action(entity, move |yumush, _, cx| {
769 yumush.toggle_builder_ban(&ban_id, cx)812 yumush.toggle_builder_ban(&ban_id, cx)
770 }),813 }),
771 );814 );
772 815
773- let profile_button = plain_button(816+ let profile_button = action_button(
774 format!("profile_user_{}", user.id),817 format!("profile_user_{}", user.id),
818+ IconName::Eraser,
775 "Clear profile",819 "Clear profile",
820+ "Remove avatar and status",
821+ palette.danger,
776 palette,822 palette,
777 entity_action(entity, move |yumush, window, cx| {823 entity_action(entity, move |yumush, window, cx| {
778 yumush.clear_builder_profile(&profile_id, window, cx)824 yumush.clear_builder_profile(&profile_id, window, cx)
779 }),825 }),
780 );826 );
781 827
782- let purge_button = danger_button(828+ let purge_button = confirm_button(
783 format!("purge_user_{}", user.id),829 format!("purge_user_{}", user.id),
830+ IconName::MessageSquareX,
784 "Purge",831 "Purge",
832+ "Delete all their messages",
785 pending_purge,833 pending_purge,
786 palette,834 palette,
787 entity_action(entity, move |yumush, window, cx| {835 entity_action(entity, move |yumush, window, cx| {
@@ -789,9 +837,11 @@ impl Yumush {
789 }),837 }),
790 );838 );
791 839
792- let delete_button = danger_button(840+ let delete_button = confirm_button(
793 format!("delete_user_{}", user.id),841 format!("delete_user_{}", user.id),
842+ IconName::UserX,
794 "Delete",843 "Delete",
844+ "Delete the account",
795 pending_delete,845 pending_delete,
796 palette,846 palette,
797 entity_action(entity, move |yumush, window, cx| {847 entity_action(entity, move |yumush, window, cx| {
@@ -805,12 +855,11 @@ impl Yumush {
805 .flex()855 .flex()
806 .items_center()856 .items_center()
807 .gap(px(10.))857 .gap(px(10.))
808- .child(avatar(858+ .child(user_link(
809- palette,859+ format!("builder_user_avatar_{}", user.id),
810- user,860+ Some(user),
811- px(28.),861+ entity,
812- text(11.),862+ avatar(palette, user, px(28.), text(11.), &self.chat.avatars),
813- &self.chat.avatars,
814 ))863 ))
815 .child(864 .child(
816 div()865 div()
@@ -825,15 +874,17 @@ impl Yumush {
825 .flex()874 .flex()
826 .items_center()875 .items_center()
827 .gap(px(6.))876 .gap(px(6.))
828- .child(877+ .child(user_link(
878+ format!("builder_user_name_{}", user.id),
879+ Some(user),
880+ entity,
829 div()881 div()
830- .min_w_0()
831 .truncate()882 .truncate()
832 .text_size(text(13.))883 .text_size(text(13.))
833 .font_weight(FontWeight::MEDIUM)884 .font_weight(FontWeight::MEDIUM)
834 .text_color(palette.text)885 .text_color(palette.text)
835 .child(user.username.clone()),886 .child(user.username.clone()),
836- )887+ ))
837 .when(builder, |this| {888 .when(builder, |this| {
838 this.child(status("Builder", palette.accent, palette))889 this.child(status("Builder", palette.accent, palette))
839 })890 })
@@ -865,46 +916,61 @@ impl Yumush {
865 let timeout_open = self.chat.pending_builder_timeout.as_deref() == Some(open_id);916 let timeout_open = self.chat.pending_builder_timeout.as_deref() == Some(open_id);
866 let ban_open = self.chat.pending_builder_ban.as_deref() == Some(open_id);917 let ban_open = self.chat.pending_builder_ban.as_deref() == Some(open_id);
867 918
868- let actions = div()919+ let account_actions = [
869- .px(px(14.))920+ manage.then(|| rename_button.into_any_element()),
870- .flex()921+ manage.then(|| password_button.into_any_element()),
871- .flex_wrap()922+ can_role.then(|| role_button.into_any_element()),
872- .items_center()923+ ];
873- .gap(px(6.))924+ let moderation_actions = [
874- .children(manage.then_some(rename_button))925+ manage.then(|| timeout_button.into_any_element()),
875- .children(manage.then_some(password_button))926+ manage.then(|| suspend_button.into_any_element()),
876- .children(can_role.then_some(role_button))927+ manage.then(|| ban_button.into_any_element()),
877- .children(manage.then(|| divider(palette)))928+ manage.then(|| sessions_button.into_any_element()),
878- .children(manage.then_some(timeout_button))929+ ];
879- .children(manage.then_some(suspend_button))930+ let danger_actions = [
880- .children(manage.then_some(ban_button))931+ manage.then(|| profile_button.into_any_element()),
881- .children(manage.then_some(sessions_button))932+ manage.then(|| purge_button.into_any_element()),
882- .children(manage.then(|| divider(palette)))933+ can_delete.then(|| delete_button.into_any_element()),
883- .children(manage.then_some(profile_button))934+ ];
884- .children(manage.then_some(purge_button))935+ let sessions: Vec<AnyElement> = sessions
885- .children(can_delete.then_some(delete_button));936+ .iter()
937+ .map(|session| {
938+ self.builder_session_row(&user.id, session, entity, palette)
939+ .into_any_element()
940+ })
941+ .collect();
886 942
887 div()943 div()
888 .flex()944 .flex()
889 .flex_col()945 .flex_col()
890- .gap(px(6.))946+ .gap(px(8.))
891- .pt(px(4.))947+ .px(px(14.))
892- .pb(px(10.))948+ .py(px(10.))
893 .bg(palette.window)949 .bg(palette.window)
894 .border_t_1()950 .border_t_1()
895 .border_color(palette.border)951 .border_color(palette.border)
896- .child(actions)952+ .children(action_group(
953+ "Account",
954+ palette,
955+ account_actions.into_iter().flatten().collect(),
956+ ))
897 .children(957 .children(
898 password_open.then(|| self.builder_password_row(&user.id, entity, palette)),958 password_open.then(|| self.builder_password_row(&user.id, entity, palette)),
899 )959 )
900 .children(rename_open.then(|| self.builder_rename_row(&user.id, entity, palette)))960 .children(rename_open.then(|| self.builder_rename_row(&user.id, entity, palette)))
961+ .children(action_group(
962+ "Moderation",
963+ palette,
964+ moderation_actions.into_iter().flatten().collect(),
965+ ))
901 .children(timeout_open.then(|| self.builder_timeout_row(&user.id, entity, palette)))966 .children(timeout_open.then(|| self.builder_timeout_row(&user.id, entity, palette)))
902 .children(ban_open.then(|| self.builder_ban_row(&user.id, entity, palette)))967 .children(ban_open.then(|| self.builder_ban_row(&user.id, entity, palette)))
903- .children(968+ .children(action_group(
904- sessions.iter().map(|session| {969+ "Danger",
905- self.builder_session_row(&user.id, session, entity, palette)970+ palette,
906- }),971+ danger_actions.into_iter().flatten().collect(),
907- )972+ ))
973+ .children(action_group("Sessions", palette, sessions))
908 });974 });
909 975
910 div().flex().flex_col().child(row).children(panel)976 div().flex().flex_col().child(row).children(panel)
crates/client/src/gui/builder/voice.rsmodified+42 -15
@@ -11,7 +11,7 @@ use gpui_kit::{
11 11
12 use super::ui::{card, card_header, icon_button, list_card, pill};12 use super::ui::{card, card_header, icon_button, list_card, pill};
13 use crate::{13 use crate::{
14- gui::{Palette, Yumush, avatar, entity_action, notify_error, text},14+ gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text},
15 network::NetworkHandle,15 network::NetworkHandle,
16 };16 };
17 17
@@ -134,8 +134,25 @@ impl Yumush {
134 .find(|summary| summary.community.id == id)134 .find(|summary| summary.community.id == id)
135 .map(|summary| summary.community.voice_enabled);135 .map(|summary| summary.community.voice_enabled);
136 136
137+ let joined = self.chat.in_voice(&id);
138+ let join_id = id.clone();
137 let mut actions =139 let mut actions =
138 vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()];140 vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()];
141+ if !joined {
142+ actions.push(
143+ icon_button(
144+ format!("room_join_{id}"),
145+ IconName::Headphones,
146+ "Join",
147+ palette.ok,
148+ palette,
149+ entity_action(entity, move |yumush, window, cx| {
150+ yumush.jump_to(join_id.clone(), true, window, cx)
151+ }),
152+ )
153+ .into_any_element(),
154+ );
155+ }
139 if let Some(enabled) = voice {156 if let Some(enabled) = voice {
140 actions.push(157 actions.push(
141 icon_button(158 icon_button(
@@ -194,21 +211,31 @@ impl Yumush {
194 .flex()211 .flex()
195 .items_center()212 .items_center()
196 .gap(px(10.))213 .gap(px(10.))
197- .child(avatar(
198- palette,
199- user,
200- px(24.),
201- text(10.),
202- &self.chat.avatars,
203- ))
204 .child(214 .child(
205- div()215+ div().flex_1().min_w_0().flex().child(user_link(
206- .flex_1()216+ format!("voice_user_{id}"),
207- .min_w_0()217+ Some(user),
208- .truncate()218+ entity,
209- .text_size(text(13.))219+ div()
210- .text_color(palette.text)220+ .flex()
211- .child(user.username.clone()),221+ .items_center()
222+ .gap(px(10.))
223+ .child(avatar(
224+ palette,
225+ user,
226+ px(24.),
227+ text(10.),
228+ &self.chat.avatars,
229+ ))
230+ .child(
231+ div()
232+ .min_w_0()
233+ .truncate()
234+ .text_size(text(13.))
235+ .text_color(palette.text)
236+ .child(user.username.clone()),
237+ ),
238+ )),
212 )239 )
213 .children(muted.then(|| pill("Muted", palette.danger, palette)))240 .children(muted.then(|| pill("Muted", palette.danger, palette)))
214 .children(ghost.then(|| pill("Ghost", palette.muted, palette)))241 .children(ghost.then(|| pill("Ghost", palette.muted, palette)))
crates/client/src/gui/chat.rsmodified+1214 -220
@@ -1,34 +1,37 @@
1 use super::text;1 use super::text;
2 use crate::gui::CLOCK;2 use crate::gui::CLOCK;
3 use std::{3 use std::{
4- collections::{HashMap, HashSet},4+ collections::{HashMap, HashSet, VecDeque},
5 sync::Arc,5 sync::Arc,
6- time::Duration,6+ time::{Duration, Instant},
7 };7 };
8 8
9 use crate::gui::social::InviteLookup;9 use crate::gui::social::InviteLookup;
10+use crate::gui::voice_stats::SAMPLE_HISTORY;
10 use crate::gui::{11 use crate::gui::{
11 FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge,12 FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge,
12 builder::{BuilderTab, Transfer},13 builder::{BuilderTab, Transfer},
13- clickable, community_icon, community_name,14+ clickable, community_name,
14- community_settings::{BanSort, LogSort},15+ community_settings::{BanSort, LogSort, search_text},
15 composer::{self, Composer},16 composer::{self, Composer},
16 entity_action, hoverable, id_time,17 entity_action, hoverable, id_time,
17 media_view::{self, Media},18 media_view::{self, Media},
18- message_actions, new_input, notify_error, palette, primary_button,19+ message_actions, new_input, notify_error, palette, poll, pop_in, presence_avatar,
20+ primary_button,
19 profile::profile_popover,21 profile::profile_popover,
20 rank_tag,22 rank_tag,
21 sidebar::SidebarTab,23 sidebar::SidebarTab,
22 snippet,24 snippet,
25+ voice_note::{self, VoiceNote},
23 };26 };
24 use common::{27 use common::{
25 constant::MESSAGE_PAGE_LIMIT,28 constant::MESSAGE_PAGE_LIMIT,
26 event::Event,29 event::Event,
27 model::{30 model::{
28- ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, Community, CommunityKind,31+ ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, CallLog, Community,
29- CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,32+ CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode,
30- Member, Message, MessageHit, Overview, Rank, Report, ReportStatus, ServerBan, SessionInfo,33+ LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus,
31- Usage, User, VoiceRoom,34+ ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions,
32 },35 },
33 permission,36 permission,
34 };37 };
@@ -96,6 +99,13 @@ pub enum ReportTarget {
96 User(String),99 User(String),
97 }100 }
98 101
102+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103+pub enum CardMenu {
104+ Main,
105+ Accounts,
106+ Presence,
107+}
108+
99 pub struct Chat {109 pub struct Chat {
100 pub(super) communities: Vec<Community>,110 pub(super) communities: Vec<Community>,
101 pub(super) selected_community_id: Option<String>,111 pub(super) selected_community_id: Option<String>,
@@ -103,15 +113,29 @@ pub struct Chat {
103 pub(super) ghost: bool,113 pub(super) ghost: bool,
104 members: Vec<Member>,114 members: Vec<Member>,
105 pub(super) messages: Vec<Message>,115 pub(super) messages: Vec<Message>,
116+ pub(super) pins: Vec<Message>,
106 history: History,117 history: History,
107- pub(super) unread: HashSet<String>,118+ pub(super) unread: HashMap<String, Unread>,
119+ pub(super) unread_anchor: Option<(String, u32)>,
120+ unseen: u32,
121+ pub(super) muted: HashSet<String>,
108 pub(super) message_input: Entity<InputState>,122 pub(super) message_input: Entity<InputState>,
109 pub(super) search_input: Entity<InputState>,123 pub(super) search_input: Entity<InputState>,
124+ pub(super) community_search: Entity<InputState>,
125+ pub(super) community_hits: Vec<MessageHit>,
110 pub(super) found: Option<User>,126 pub(super) found: Option<User>,
111 pub(super) invite: InviteLookup,127 pub(super) invite: InviteLookup,
112 pub(super) tab: SidebarTab,128 pub(super) tab: SidebarTab,
129+ pub(super) sidebar_collapsed: bool,
113 pub(super) composer: Composer,130 pub(super) composer: Composer,
131+ pub(super) drafts: HashMap<String, String>,
132+ pub(super) poll_question: Entity<InputState>,
133+ pub(super) poll_options: Vec<Entity<InputState>>,
134+ pub(super) poll_multiple: bool,
135+ pub(super) poll_expanded: bool,
114 scroll: ScrollHandle,136 scroll: ScrollHandle,
137+ pub(super) jump: Option<String>,
138+ highlight: Option<(String, Instant)>,
115 pub(super) view: View,139 pub(super) view: View,
116 pub(super) username_input: Entity<InputState>,140 pub(super) username_input: Entity<InputState>,
117 pub(super) community_name_input: Entity<InputState>,141 pub(super) community_name_input: Entity<InputState>,
@@ -131,6 +155,9 @@ pub struct Chat {
131 pub(super) friends: Friends,155 pub(super) friends: Friends,
132 pub(super) invitations: Vec<Invitation>,156 pub(super) invitations: Vec<Invitation>,
133 pub(super) pending_user_delete: Option<String>,157 pub(super) pending_user_delete: Option<String>,
158+ pub(super) card_menu: CardMenu,
159+ pub(super) presences: HashMap<String, Presence>,
160+ pub(super) slowed_until: Option<u64>,
134 pub(super) pending_builder_delete: Option<String>,161 pub(super) pending_builder_delete: Option<String>,
135 pub(super) builder_users: Vec<Account>,162 pub(super) builder_users: Vec<Account>,
136 pub(super) pending_builder_password: Option<String>,163 pub(super) pending_builder_password: Option<String>,
@@ -202,17 +229,34 @@ pub struct Chat {
202 pub(super) server_muted: HashSet<String>,229 pub(super) server_muted: HashSet<String>,
203 pub(super) builder_voice_rooms: Vec<VoiceRoom>,230 pub(super) builder_voice_rooms: Vec<VoiceRoom>,
204 pub(super) voice_task: Option<Task<()>>,231 pub(super) voice_task: Option<Task<()>>,
232+ pub(super) voice_samples: VecDeque<crate::voice::VoiceSample>,
233+ pub(super) ringing: HashSet<String>,
234+ pub(super) ring_task: Option<Task<()>>,
205 pub(super) media: Media,235 pub(super) media: Media,
236+ pub(super) typing: HashMap<String, HashMap<String, Instant>>,
237+ pub(super) typing_sent: HashMap<String, Instant>,
206 }238 }
207 239
240+const RING_LIMIT: usize = 15;
241+const RING_INTERVAL: Duration = Duration::from_secs(2);
242+const VOICE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);
243+const DELETE_CONFIRM: Duration = Duration::from_secs(3);
244+pub const TYPING_SEND_INTERVAL: Duration = Duration::from_secs(3);
245+pub const TYPING_TTL: Duration = Duration::from_secs(5);
246+const HIGHLIGHT_TTL: Duration = Duration::from_secs(2);
247+
208 impl Chat {248 impl Chat {
209 pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {249 pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {
210 let message_input = new_input("Message", window, cx);250 let message_input = new_input("Message", window, cx);
211- cx.subscribe_in(&message_input, window, |this, input, event, window, cx| {251+ cx.subscribe_in(
212- if matches!(event, InputEvent::PressEnter { .. }) {252+ &message_input,
213- this.submit_composer(input, window, cx);253+ window,
214- }254+ |this, input, event, window, cx| match event {
215- })255+ InputEvent::PressEnter { .. } => this.submit_composer(input, window, cx),
256+ InputEvent::Change => this.send_typing(cx),
257+ _ => {}
258+ },
259+ )
216 .detach();260 .detach();
217 261
218 let username_input = editable_input("Username...", Yumush::save_username, window, cx);262 let username_input = editable_input("Username...", Yumush::save_username, window, cx);
@@ -232,6 +276,14 @@ impl Chat {
232 )276 )
233 .detach();277 .detach();
234 278
279+ let community_search = new_input("Search messages", window, cx);
280+ cx.subscribe_in(&community_search, window, |this, _, event, window, cx| {
281+ if matches!(event, InputEvent::PressEnter { .. }) {
282+ this.search_community(window, cx);
283+ }
284+ })
285+ .detach();
286+
235 let ban_search = new_input("Search...", window, cx);287 let ban_search = new_input("Search...", window, cx);
236 let log_search = new_input("Search...", window, cx);288 let log_search = new_input("Search...", window, cx);
237 let builder_search = new_input("Search...", window, cx);289 let builder_search = new_input("Search...", window, cx);
@@ -306,14 +358,30 @@ impl Chat {
306 friends: Friends::default(),358 friends: Friends::default(),
307 invitations: vec![],359 invitations: vec![],
308 messages: vec![],360 messages: vec![],
361+ pins: vec![],
362+ poll_question: new_input("Question", window, cx),
363+ poll_options: vec![
364+ new_input("Option", window, cx),
365+ new_input("Option", window, cx),
366+ ],
367+ poll_multiple: false,
368+ poll_expanded: false,
309 history: History::End,369 history: History::End,
310 scroll: ScrollHandle::new(),370 scroll: ScrollHandle::new(),
311- unread: HashSet::new(),371+ jump: None,
372+ highlight: None,
373+ unread: HashMap::new(),
374+ unread_anchor: None,
375+ unseen: 0,
376+ muted: HashSet::new(),
312 message_input,377 message_input,
313 search_input,378 search_input,
379+ community_search,
380+ community_hits: vec![],
314 found: None,381 found: None,
315 invite: InviteLookup::Idle,382 invite: InviteLookup::Idle,
316 tab: SidebarTab::Communities,383 tab: SidebarTab::Communities,
384+ sidebar_collapsed: false,
317 view: View::Chat,385 view: View::Chat,
318 username_input,386 username_input,
319 community_name_input,387 community_name_input,
@@ -325,6 +393,9 @@ impl Chat {
325 user_requests: HashSet::new(),393 user_requests: HashSet::new(),
326 delete_step: DeleteStep::Idle,394 delete_step: DeleteStep::Idle,
327 pending_user_delete: None,395 pending_user_delete: None,
396+ card_menu: CardMenu::Main,
397+ presences: HashMap::new(),
398+ slowed_until: None,
328 pending_builder_delete: None,399 pending_builder_delete: None,
329 builder_users: vec![],400 builder_users: vec![],
330 builder_tab: BuilderTab::Overview,401 builder_tab: BuilderTab::Overview,
@@ -391,21 +462,35 @@ impl Chat {
391 report: None,462 report: None,
392 report_reason,463 report_reason,
393 voice: HashMap::new(),464 voice: HashMap::new(),
465+ drafts: HashMap::new(),
394 voice_state: VoiceState::Off,466 voice_state: VoiceState::Off,
395 speaking: HashSet::new(),467 speaking: HashSet::new(),
396 server_muted: HashSet::new(),468 server_muted: HashSet::new(),
397 builder_voice_rooms: Vec::new(),469 builder_voice_rooms: Vec::new(),
398 voice_task: None,470 voice_task: None,
471+ voice_samples: VecDeque::new(),
472+ ringing: HashSet::new(),
473+ ring_task: None,
474+ typing: HashMap::new(),
475+ typing_sent: HashMap::new(),
399 media: Media::default(),476 media: Media::default(),
400 composer: Composer::Compose { reply: None },477 composer: Composer::Compose { reply: None },
401 }478 }
402 }479 }
403 480
404- pub(super) fn has_unread(&self, direct: bool) -> bool {481+ pub(super) fn unread_total(&self, group: bool) -> Unread {
405- self.communities.iter().any(|community| {482+ self.communities
406- self.unread.contains(&community.id)483+ .iter()
407- && matches!(community.kind, CommunityKind::Direct { .. }) == direct484+ .filter(|community| {
408- })485+ !self.muted.contains(&community.id)
486+ && matches!(community.kind, CommunityKind::Group) == group
487+ })
488+ .filter_map(|community| self.unread.get(&community.id))
489+ .fold(Unread::default(), |total, unread| Unread {
490+ messages: total.messages + unread.messages,
491+ mentions: total.mentions + unread.mentions,
492+ ..total
493+ })
409 }494 }
410 495
411 pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {496 pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {
@@ -422,18 +507,25 @@ impl Chat {
422 .update(cx, |input, cx| input.focus(window, cx));507 .update(cx, |input, cx| input.focus(window, cx));
423 }508 }
424 509
425- pub fn apply_event(&mut self, event: Event) {510+ pub fn slow_seconds(&self) -> Option<u64> {
511+ let remaining = self.slowed_until?.saturating_sub(common::time::now_ms());
512+ (remaining > 0).then(|| remaining.div_ceil(1000))
513+ }
514+
515+ pub fn apply_event(&mut self, event: Event, me: Option<&str>) {
426 match event {516 match event {
427 Event::MessageCreated(message) => {517 Event::MessageCreated(message) => {
518+ if let Some(users) = self.typing.get_mut(&message.community_id) {
519+ users.remove(&message.user_id);
520+ }
428 if self.is_selected(&message.community_id) {521 if self.is_selected(&message.community_id) {
429- self.insert_messages([message]);522+ self.insert_messages([message], me);
430- } else {
431- self.unread.insert(message.community_id);
432 }523 }
433 }524 }
434 Event::MessageUpdated(message) => {525 Event::MessageUpdated(message) => {
435 if self.is_selected(&message.community_id) {526 if self.is_selected(&message.community_id) {
436- self.insert_messages([message]);527+ self.update_pin(&message);
528+ self.insert_messages([message], me);
437 }529 }
438 }530 }
439 Event::MessageDeleted(message) => {531 Event::MessageDeleted(message) => {
@@ -479,6 +571,9 @@ impl Chat {
479 self.messages.retain(|message| message.user_id != user_id);571 self.messages.retain(|message| message.user_id != user_id);
480 }572 }
481 Event::UserUpdated(user) => self.update_member(&user),573 Event::UserUpdated(user) => self.update_member(&user),
574+ Event::PresenceChanged { user_id, presence } => {
575+ self.presences.insert(user_id, presence);
576+ }
482 Event::VoiceJoined {577 Event::VoiceJoined {
483 community_id,578 community_id,
484 user_id,579 user_id,
@@ -494,6 +589,9 @@ impl Chat {
494 } => {589 } => {
495 if let Some(ids) = self.voice.get_mut(&community_id) {590 if let Some(ids) = self.voice.get_mut(&community_id) {
496 ids.retain(|id| *id != user_id);591 ids.retain(|id| *id != user_id);
592+ if ids.is_empty() {
593+ self.ringing.remove(&community_id);
594+ }
497 }595 }
498 }596 }
499 Event::VoiceMuted { user_id, muted } => {597 Event::VoiceMuted { user_id, muted } => {
@@ -503,6 +601,15 @@ impl Chat {
503 self.server_muted.remove(&user_id);601 self.server_muted.remove(&user_id);
504 }602 }
505 }603 }
604+ Event::Typing {
605+ community_id,
606+ user_id,
607+ } => {
608+ self.typing
609+ .entry(community_id)
610+ .or_default()
611+ .insert(user_id, Instant::now());
612+ }
506 Event::ReportCreated | Event::Announcement { .. } => {}613 Event::ReportCreated | Event::Announcement { .. } => {}
507 }614 }
508 }615 }
@@ -511,9 +618,38 @@ impl Chat {
511 self.selected_community_id.as_deref() == Some(community_id)618 self.selected_community_id.as_deref() == Some(community_id)
512 }619 }
513 620
621+ pub fn typing_label(&self) -> Option<String> {
622+ let community_id = self.selected_community_id.as_ref()?;
623+ let names: Vec<&str> = self
624+ .typing
625+ .get(community_id)?
626+ .iter()
627+ .filter(|(_, at)| at.elapsed() < TYPING_TTL)
628+ .map(|(user_id, _)| {
629+ self.author(user_id)
630+ .map_or("Someone", |user| user.username.as_str())
631+ })
632+ .collect();
633+ match names.as_slice() {
634+ [] => None,
635+ [name] => Some(format!("{name} is typing…")),
636+ names => Some(format!("{} people are typing…", names.len())),
637+ }
638+ }
639+
514 fn select(&mut self, community_id: Option<String>) {640 fn select(&mut self, community_id: Option<String>) {
515- if let Some(community_id) = &community_id {641+ if community_id != self.selected_community_id {
516- self.unread.remove(community_id);642+ self.unread_anchor = community_id
643+ .as_ref()
644+ .and_then(|community_id| self.unread.get(community_id))
645+ .filter(|unread| unread.messages > 0)
646+ .and_then(|unread| {
647+ unread
648+ .last_read
649+ .clone()
650+ .map(|last_read| (last_read, unread.messages))
651+ });
652+ self.unseen = 0;
517 }653 }
518 if self.opened.as_ref().map(|opened| &opened.id) != community_id.as_ref() {654 if self.opened.as_ref().map(|opened| &opened.id) != community_id.as_ref() {
519 self.opened = None;655 self.opened = None;
@@ -528,12 +664,16 @@ impl Chat {
528 self.logs.clear();664 self.logs.clear();
529 self.pending_user_delete = None;665 self.pending_user_delete = None;
530 self.messages.clear();666 self.messages.clear();
667+ self.jump = None;
668+ self.pins.clear();
669+ self.poll_expanded = false;
670+ self.community_hits.clear();
531 self.history = History::End;671 self.history = History::End;
532 self.media.leave();672 self.media.leave();
533 self.composer = Composer::Compose { reply: None };673 self.composer = Composer::Compose { reply: None };
534 }674 }
535 675
536- fn joined(&self, community_id: &str) -> bool {676+ pub fn joined(&self, community_id: &str) -> bool {
537 self.communities677 self.communities
538 .iter()678 .iter()
539 .any(|community| community.id == community_id)679 .any(|community| community.id == community_id)
@@ -559,7 +699,13 @@ impl Chat {
559 &self.communities699 &self.communities
560 }700 }
561 701
562- fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>) {702+ pub fn notes(&self) -> Option<&Community> {
703+ self.communities
704+ .iter()
705+ .find(|community| matches!(community.kind, CommunityKind::Notes))
706+ }
707+
708+ fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>, me: Option<&str>) {
563 let newest = self.messages.last().map(|message| message.id.clone());709 let newest = self.messages.last().map(|message| message.id.clone());
564 for message in messages {710 for message in messages {
565 self.messages.retain(|existing| existing.id != message.id);711 self.messages.retain(|existing| existing.id != message.id);
@@ -567,13 +713,96 @@ impl Chat {
567 }713 }
568 self.messages.sort_by(|left, right| left.id.cmp(&right.id));714 self.messages.sort_by(|left, right| left.id.cmp(&right.id));
569 if self.messages.last().map(|message| &message.id) != newest.as_ref() {715 if self.messages.last().map(|message| &message.id) != newest.as_ref() {
570- self.scroll.scroll_to_bottom();716+ let mine = self
717+ .messages
718+ .last()
719+ .is_some_and(|message| Some(message.user_id.as_str()) == me);
720+ if newest.is_none() {
721+ match self.unread_divider(me) {
722+ Some(index) => self.scroll_to_index(index),
723+ None => self.scroll.scroll_to_bottom(),
724+ }
725+ } else if mine || !self.away() {
726+ self.jump_to_bottom();
727+ } else {
728+ self.unseen += 1;
729+ }
571 }730 }
731+ self.reveal_jump();
572 }732 }
573 733
574- fn add_page(&mut self, page: Vec<Message>) {734+ fn reveal_jump(&mut self) {
735+ let Some(message_id) = self.jump.as_ref() else {
736+ return;
737+ };
738+ let Some(position) = self
739+ .messages
740+ .iter()
741+ .position(|message| &message.id == message_id)
742+ else {
743+ return;
744+ };
745+ self.scroll_to_index(position);
746+ self.highlight = self
747+ .jump
748+ .take()
749+ .map(|message_id| (message_id, Instant::now()));
750+ }
751+
752+ fn scroll_to_index(&self, position: usize) {
753+ let spacer = 1;
754+ let older = usize::from(self.history == History::More);
755+ self.scroll.scroll_to_item(spacer + older + position);
756+ }
757+
758+ fn away(&self) -> bool {
759+ self.scroll.max_offset().y + self.scroll.offset().y > self.scroll.bounds().size.height
760+ }
761+
762+ pub(super) fn jump_to_bottom(&mut self) {
763+ self.scroll.scroll_to_bottom();
764+ self.unseen = 0;
765+ }
766+
767+ pub(super) fn settle_scroll(&mut self) {
768+ if !self.away() {
769+ self.unseen = 0;
770+ }
771+ }
772+
773+ fn unread_covered(&self) -> bool {
774+ match (&self.unread_anchor, self.messages.first()) {
775+ (Some((anchor, _)), Some(first)) => self.history == History::End || first.id <= *anchor,
776+ _ => true,
777+ }
778+ }
779+
780+ fn unread_divider(&self, me: Option<&str>) -> Option<usize> {
781+ let (anchor, _) = self.unread_anchor.as_ref()?;
782+ if !self.unread_covered() {
783+ return None;
784+ }
785+ self.messages
786+ .iter()
787+ .position(|message| message.id > *anchor && Some(message.user_id.as_str()) != me)
788+ }
789+
790+ pub(super) fn mark_read(&mut self, community_id: &str, message_id: &str) {
791+ let unread = self
792+ .unread
793+ .entry(community_id.to_string())
794+ .or_insert_with(|| Unread {
795+ community_id: community_id.to_string(),
796+ ..Default::default()
797+ });
798+ unread.messages = 0;
799+ unread.mentions = 0;
800+ unread.last_read = Some(message_id.to_string());
801+ }
802+
803+ fn add_page(&mut self, page: Vec<Message>, me: Option<&str>) {
575 self.history = History::of_page(page.len());804 self.history = History::of_page(page.len());
576- self.insert_messages(page);805+ self.insert_messages(page, me);
577 }806 }
578 807
579 fn insert_member(&mut self, member: Member) {808 fn insert_member(&mut self, member: Member) {
@@ -659,6 +888,21 @@ impl Chat {
659 self.member(user_id).and_then(|user| self.rank_of(user))888 self.member(user_id).and_then(|user| self.rank_of(user))
660 }889 }
661 890
891+ pub fn can_pin(&self, me: &User) -> bool {
892+ let direct = self
893+ .selected_community()
894+ .is_some_and(|community| matches!(community.kind, CommunityKind::Direct { .. }));
895+ permission::can_pin(self.my_rank(me), direct)
896+ }
897+
898+ fn update_pin(&mut self, message: &Message) {
899+ self.pins.retain(|pin| pin.id != message.id);
900+ if message.pinned {
901+ self.pins.push(message.clone());
902+ self.pins.sort_by(|left, right| right.id.cmp(&left.id));
903+ }
904+ }
905+
662 pub fn can_delete(&self, message: &Message, me: &User) -> bool {906 pub fn can_delete(&self, message: &Message, me: &User) -> bool {
663 permission::can_delete_message(907 permission::can_delete_message(
664 self.my_rank(me),908 self.my_rank(me),
@@ -681,7 +925,7 @@ impl Chat {
681 .iter_mut()925 .iter_mut()
682 .filter_map(|community| match &mut community.kind {926 .filter_map(|community| match &mut community.kind {
683 CommunityKind::Direct { peer } => Some(peer),927 CommunityKind::Direct { peer } => Some(peer),
684- CommunityKind::Group => None,928+ CommunityKind::Group | CommunityKind::Notes => None,
685 });929 });
686 let known = self930 let known = self
687 .friends931 .friends
@@ -739,11 +983,14 @@ impl Chat {
739 983
740 pub fn reset(&mut self) {984 pub fn reset(&mut self) {
741 self.communities.clear();985 self.communities.clear();
986+ self.presences.clear();
987+ self.slowed_until = None;
742 self.friends = Friends::default();988 self.friends = Friends::default();
743 self.invitations.clear();989 self.invitations.clear();
744 self.found = None;990 self.found = None;
745 self.select(None);991 self.select(None);
746 self.unread.clear();992 self.unread.clear();
993+ self.muted.clear();
747 self.builder_users.clear();994 self.builder_users.clear();
748 self.builder_tab = BuilderTab::Overview;995 self.builder_tab = BuilderTab::Overview;
749 self.builder_overview = None;996 self.builder_overview = None;
@@ -778,6 +1025,8 @@ impl Chat {
778 self.voice.clear();1025 self.voice.clear();
779 self.server_muted.clear();1026 self.server_muted.clear();
780 self.builder_voice_rooms.clear();1027 self.builder_voice_rooms.clear();
1028+ self.ringing.clear();
1029+ self.ring_task = None;
781 self.set_voice_off();1030 self.set_voice_off();
782 }1031 }
783 1032
@@ -788,6 +1037,14 @@ impl Chat {
788 }1037 }
789 }1038 }
790 1039
1040+ pub fn voice_room(&self) -> Option<&Community> {
1041+ let community_id = self.voice_community()?;
1042+ self.communities
1043+ .iter()
1044+ .chain(self.opened.as_ref())
1045+ .find(|community| community.id == community_id)
1046+ }
1047+
791 pub fn in_voice(&self, community_id: &str) -> bool {1048 pub fn in_voice(&self, community_id: &str) -> bool {
792 self.voice_community() == Some(community_id)1049 self.voice_community() == Some(community_id)
793 }1050 }
@@ -819,6 +1076,7 @@ impl Chat {
819 self.voice_state = VoiceState::Off;1076 self.voice_state = VoiceState::Off;
820 self.speaking.clear();1077 self.speaking.clear();
821 self.voice_task = None;1078 self.voice_task = None;
1079+ self.voice_samples.clear();
822 }1080 }
823 }1081 }
824 1082
@@ -947,6 +1205,7 @@ impl Yumush {
947 .bg(palette.panel)1205 .bg(palette.panel)
948 .overflow_hidden()1206 .overflow_hidden()
949 .children(self.announcement_banner(entity, palette))1207 .children(self.announcement_banner(entity, palette))
1208+ .children(self.call_banner(entity, palette))
950 .map(|panel| match self.chat.view {1209 .map(|panel| match self.chat.view {
951 View::Settings => panel.child(self.settings_page(entity, palette, cx)),1210 View::Settings => panel.child(self.settings_page(entity, palette, cx)),
952 View::Builder => panel.child(self.builder_page(entity, palette, cx)),1211 View::Builder => panel.child(self.builder_page(entity, palette, cx)),
@@ -956,7 +1215,9 @@ impl Yumush {
956 View::Chat => match self.chat.selected_community_id {1215 View::Chat => match self.chat.selected_community_id {
957 Some(_) => panel1216 Some(_) => panel
958 .child(self.header(entity, themed))1217 .child(self.header(entity, themed))
959- .child(self.message_list(entity, themed))1218+ .children(self.unread_bar(entity, themed))
1219+ .children(self.poll_banner(entity, themed))
1220+ .child(self.message_area(entity, themed))
960 .child(self.composer(entity, themed)),1221 .child(self.composer(entity, themed)),
961 None => panel.child(empty_state(palette)),1222 None => panel.child(empty_state(palette)),
962 },1223 },
@@ -1003,9 +1264,10 @@ impl Yumush {
1003 .gap(px(8.))1264 .gap(px(8.))
1004 .border_b_2()1265 .border_b_2()
1005 .border_color(palette.accent)1266 .border_color(palette.accent)
1006- .children(community.map(|community| {1267+ .children(
1007- community_icon(palette, community, px(20.), text(10.), &self.chat.avatars)1268+ community
1008- }))1269+ .map(|community| self.community_badge(community, px(20.), text(10.), palette)),
1270+ )
1009 .child(1271 .child(
1010 div()1272 div()
1011 .font_weight(FontWeight::SEMIBOLD)1273 .font_weight(FontWeight::SEMIBOLD)
@@ -1018,11 +1280,124 @@ impl Yumush {
1018 .then(|| self.voice_stack(entity, palette))1280 .then(|| self.voice_stack(entity, palette))
1019 .flatten(),1281 .flatten(),
1020 )1282 )
1283+ .children(self.calling_hint(palette))
1021 .children(self.voice_button(entity, palette))1284 .children(self.voice_button(entity, palette))
1022- .children(group.then(|| members_popover(entity, &self.chat, palette)))1285+ .children(
1286+ community
1287+ .is_some_and(|community| self.chat.joined(&community.id))
1288+ .then(|| message_actions::search_popover(&self.chat, entity, palette)),
1289+ )
1290+ .children(
1291+ (community.is_some() && !self.chat.pins.is_empty())
1292+ .then(|| message_actions::pins_popover(&self.chat, entity, palette)),
1293+ )
1294+ .children(group.then(|| members_popover(entity, self, palette)))
1295+ }
1296+
1297+ fn message_area(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
1298+ div()
1299+ .flex()
1300+ .flex_col()
1301+ .flex_1()
1302+ .min_h_0()
1303+ .relative()
1304+ .child(self.message_list(entity, palette))
1305+ .children(self.jump_bottom(entity, palette))
1306+ }
1307+
1308+ fn unread_bar(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
1309+ let (anchor, count) = self.chat.unread_anchor.clone()?;
1310+ if self.chat.unread_covered() {
1311+ return None;
1312+ }
1313+ Some(
1314+ div()
1315+ .flex()
1316+ .items_center()
1317+ .justify_between()
1318+ .gap(px(8.))
1319+ .px(px(12.))
1320+ .py(px(6.))
1321+ .bg(palette.accent)
1322+ .text_color(palette.on_accent)
1323+ .child(format!("{count} new messages"))
1324+ .child(
1325+ div()
1326+ .flex()
1327+ .gap(px(8.))
1328+ .child(
1329+ clickable(
1330+ "jump_unread",
1331+ palette,
1332+ entity_action(entity, move |yumush, window, cx| {
1333+ yumush.go_to_message(anchor.clone(), window, cx)
1334+ }),
1335+ )
1336+ .child("↑"),
1337+ )
1338+ .child(
1339+ clickable(
1340+ "dismiss_unread",
1341+ palette,
1342+ entity_action(entity, |yumush, _, cx| {
1343+ yumush.chat.unread_anchor = None;
1344+ cx.notify();
1345+ }),
1346+ )
1347+ .child("×"),
1348+ ),
1349+ ),
1350+ )
1351+ }
1352+
1353+ fn jump_bottom(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
1354+ if !self.chat.away() {
1355+ return None;
1356+ }
1357+ let unseen = self.chat.unseen;
1358+ Some(
1359+ clickable(
1360+ "jump_bottom",
1361+ palette,
1362+ entity_action(entity, |yumush, _, cx| {
1363+ yumush.chat.jump_to_bottom();
1364+ cx.notify();
1365+ }),
1366+ )
1367+ .absolute()
1368+ .right(px(16.))
1369+ .bottom(px(12.))
1370+ .size(px(36.))
1371+ .flex()
1372+ .items_center()
1373+ .justify_center()
1374+ .rounded_full()
1375+ .border_1()
1376+ .border_color(palette.border)
1377+ .bg(palette.panel)
1378+ .child(Icon::new(IconName::ArrowDown).w(px(16.)).h(px(16.)))
1379+ .children((unseen > 0).then(|| {
1380+ div()
1381+ .absolute()
1382+ .top(px(-6.))
1383+ .right(px(-6.))
1384+ .children(super::sidebar::badge(
1385+ palette,
1386+ false,
1387+ Some(&Unread {
1388+ messages: unseen,
1389+ ..Default::default()
1390+ }),
1391+ ))
1392+ })),
1393+ )
1023 }1394 }
1024 1395
1025 fn message_list(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {1396 fn message_list(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
1397+ let divider = self
1398+ .chat
1399+ .unread_divider(self.user.as_ref().map(|user| user.id.as_str()));
1400+ let entity_scroll = entity.clone();
1026 div()1401 div()
1027 .id("chat_messages")1402 .id("chat_messages")
1028 .track_scroll(&self.chat.scroll)1403 .track_scroll(&self.chat.scroll)
@@ -1034,6 +1409,15 @@ impl Yumush {
1034 .px(px(24.))1409 .px(px(24.))
1035 .py(px(20.))1410 .py(px(20.))
1036 .gap(px(2.))1411 .gap(px(2.))
1412+ .on_scroll(move |_, window, _| {
1413+ let entity = entity_scroll.clone();
1414+ window.on_next_frame(move |_, cx| {
1415+ entity.update(cx, |yumush, cx| {
1416+ yumush.chat.settle_scroll();
1417+ cx.notify();
1418+ })
1419+ });
1420+ })
1037 .child(div().flex_1())1421 .child(div().flex_1())
1038 .children((self.chat.history == History::More).then(|| older_button(entity, palette)))1422 .children((self.chat.history == History::More).then(|| older_button(entity, palette)))
1039 .children(1423 .children(
@@ -1041,10 +1425,12 @@ impl Yumush {
1041 .messages1425 .messages
1042 .iter()1426 .iter()
1043 .enumerate()1427 .enumerate()
1044- .map(|(index, message)| {1428+ .flat_map(|(index, message)| {
1045 let first =1429 let first =
1046 index == 0 || self.chat.messages[index - 1].user_id != message.user_id;1430 index == 0 || self.chat.messages[index - 1].user_id != message.user_id;
1047- render_message(1431+ let divider = (divider == Some(index))
1432+ .then(|| new_divider(palette).into_any_element());
1433+ divider.into_iter().chain([render_message(
1048 message,1434 message,
1049 first,1435 first,
1050 index > 0,1436 index > 0,
@@ -1052,7 +1438,7 @@ impl Yumush {
1052 self.user.as_ref(),1438 self.user.as_ref(),
1053 entity,1439 entity,
1054 palette,1440 palette,
1055- )1441+ )])
1056 }),1442 }),
1057 )1443 )
1058 }1444 }
@@ -1071,10 +1457,30 @@ impl Yumush {
1071 let bar = composer::mode_bar(&self.chat, entity, palette);1457 let bar = composer::mode_bar(&self.chat, entity, palette);
1072 let entity = entity.clone();1458 let entity = entity.clone();
1073 1459
1074- div()1460+ if let VoiceNote::Recording {
1075- .p(px(16.))1461+ started, levels, ..
1462+ } = &self.chat.media.voice_note
1463+ {
1464+ return div()
1465+ .p(px(16.))
1466+ .children(pending)
1467+ .child(voice_note::recording_row(
1468+ *started, levels, &entity, palette,
1469+ ))
1470+ .into_any_element();
1471+ }
1472+
1473+ composer::format_actions(&self.chat.message_input, div().p(px(16.)))
1076 .children(pending)1474 .children(pending)
1077 .children(bar)1475 .children(bar)
1476+ .children(self.chat.typing_label().map(|label| {
1477+ div()
1478+ .pl(px(4.))
1479+ .pb(px(4.))
1480+ .text_size(text(12.))
1481+ .text_color(palette.muted)
1482+ .child(label)
1483+ }))
1078 .child(1484 .child(
1079 div()1485 div()
1080 .min_h(px(40.))1486 .min_h(px(40.))
@@ -1101,6 +1507,8 @@ impl Yumush {
1101 .text_color(palette.muted)1507 .text_color(palette.muted)
1102 .child(Icon::new(IconName::Plus).w(px(16.)).h(px(16.))),1508 .child(Icon::new(IconName::Plus).w(px(16.)).h(px(16.))),
1103 )1509 )
1510+ .child(composer::format_popover(palette))
1511+ .child(composer::poll_popover(&self.chat, &entity, palette))
1104 .child(1512 .child(
1105 Input::new(&self.chat.message_input)1513 Input::new(&self.chat.message_input)
1106 .appearance(false)1514 .appearance(false)
@@ -1108,6 +1516,7 @@ impl Yumush {
1108 .flex_1()1516 .flex_1()
1109 .min_w_0(),1517 .min_w_0(),
1110 )1518 )
1519+ .child(voice_note::mic_button(&entity, palette))
1111 .child(1520 .child(
1112 primary_button("send_button", palette, move |window, cx| {1521 primary_button("send_button", palette, move |window, cx| {
1113 entity1522 entity
@@ -1132,9 +1541,12 @@ impl Yumush {
1132 cx: &mut Context<Self>,1541 cx: &mut Context<Self>,
1133 ) {1542 ) {
1134 self.stop_playing(cx);1543 self.stop_playing(cx);
1135- self.chat.select(Some(community_id));1544+ self.save_draft(cx);
1545+ self.chat.select(Some(community_id.clone()));
1546+ self.restore_draft(&community_id, window, cx);
1136 self.chat.focus(window, cx);1547 self.chat.focus(window, cx);
1137 self.load_members(window, cx);1548 self.load_members(window, cx);
1549+ self.load_pins(window, cx);
1138 self.load_voice(window, cx);1550 self.load_voice(window, cx);
1139 self.load_latest_messages(window, cx);1551 self.load_latest_messages(window, cx);
1140 cx.notify();1552 cx.notify();
@@ -1173,8 +1585,13 @@ impl Yumush {
1173 return;1585 return;
1174 }1586 }
1175 };1587 };
1588+ let unreads = network.unreads().await.unwrap_or_default();
1176 1589
1177 let _ = this.update_in(cx, |yumush, window, cx| {1590 let _ = this.update_in(cx, |yumush, window, cx| {
1591+ yumush.chat.unread = unreads
1592+ .into_iter()
1593+ .map(|unread| (unread.community_id.clone(), unread))
1594+ .collect();
1178 yumush.chat.replace_communities(communities);1595 yumush.chat.replace_communities(communities);
1179 yumush.request_social_avatars(cx);1596 yumush.request_social_avatars(cx);
1180 1597
@@ -1194,6 +1611,60 @@ impl Yumush {
1194 .detach();1611 .detach();
1195 }1612 }
1196 1613
1614+ fn search_community(&self, window: &mut Window, cx: &mut Context<Self>) {
1615+ let Some(community_id) = self.chat.selected_community_id.clone() else {
1616+ return;
1617+ };
1618+ let text = search_text(&self.chat.community_search, cx);
1619+ if text.is_empty() {
1620+ return;
1621+ }
1622+ let network = self.network.clone();
1623+
1624+ cx.spawn_in(window, async move |this, cx| {
1625+ let hits = match network.search_community(community_id.clone(), text).await {
1626+ Ok(hits) => hits,
1627+ Err(error) => {
1628+ notify_error(&this, cx, error);
1629+ return;
1630+ }
1631+ };
1632+
1633+ let _ = this.update(cx, |yumush, cx| {
1634+ if yumush.chat.is_selected(&community_id) {
1635+ yumush.chat.community_hits = hits;
1636+ cx.notify();
1637+ }
1638+ });
1639+ })
1640+ .detach();
1641+ }
1642+
1643+ fn load_pins(&self, window: &mut Window, cx: &mut Context<Self>) {
1644+ let Some(community_id) = self.chat.selected_community_id.clone() else {
1645+ return;
1646+ };
1647+ let network = self.network.clone();
1648+
1649+ cx.spawn_in(window, async move |this, cx| {
1650+ let pins = match network.pins(&community_id).await {
1651+ Ok(pins) => pins,
1652+ Err(error) => {
1653+ notify_error(&this, cx, error);
1654+ return;
1655+ }
1656+ };
1657+
1658+ let _ = this.update(cx, |yumush, cx| {
1659+ if yumush.chat.is_selected(&community_id) {
1660+ yumush.chat.pins = pins;
1661+ cx.notify();
1662+ }
1663+ });
1664+ })
1665+ .detach();
1666+ }
1667+
1197 fn load_members(&self, window: &mut Window, cx: &mut Context<Self>) {1668 fn load_members(&self, window: &mut Window, cx: &mut Context<Self>) {
1198 let Some(community_id) = self.chat.selected_community_id.clone() else {1669 let Some(community_id) = self.chat.selected_community_id.clone() else {
1199 return;1670 return;
@@ -1216,7 +1687,7 @@ impl Yumush {
1216 }1687 }
1217 yumush.chat.members = members;1688 yumush.chat.members = members;
1218 yumush.load_bans(window, cx);1689 yumush.load_bans(window, cx);
1219- yumush.request_authors(window, cx);1690+ yumush.request_authors(cx);
1220 cx.notify();1691 cx.notify();
1221 }1692 }
1222 });1693 });
@@ -1224,7 +1695,7 @@ impl Yumush {
1224 .detach();1695 .detach();
1225 }1696 }
1226 1697
1227- fn request_authors(&mut self, window: &mut Window, cx: &mut Context<Self>) {1698+ pub(super) fn request_authors(&mut self, cx: &mut Context<Self>) {
1228 let missing = self.chat.missing_authors();1699 let missing = self.chat.missing_authors();
1229 if missing.is_empty() {1700 if missing.is_empty() {
1230 return;1701 return;
@@ -1232,7 +1703,7 @@ impl Yumush {
1232 self.chat.user_requests.extend(missing.iter().cloned());1703 self.chat.user_requests.extend(missing.iter().cloned());
1233 let network = self.network.clone();1704 let network = self.network.clone();
1234 1705
1235- cx.spawn_in(window, async move |this, cx| {1706+ cx.spawn(async move |this, cx| {
1236 for user_id in missing {1707 for user_id in missing {
1237 let Ok(user) = network.read_user(&user_id).await else {1708 let Ok(user) = network.read_user(&user_id).await else {
1238 continue;1709 continue;
@@ -1278,6 +1749,32 @@ impl Yumush {
1278 .detach();1749 .detach();
1279 }1750 }
1280 1751
1752+ pub(super) fn go_to_message(
1753+ &mut self,
1754+ message_id: String,
1755+ window: &mut Window,
1756+ cx: &mut Context<Self>,
1757+ ) {
1758+ self.chat.jump = Some(message_id);
1759+ self.chat.reveal_jump();
1760+ if self.chat.jump.is_none() {
1761+ Self::fade_highlight(cx);
1762+ } else if self.chat.history == History::More {
1763+ self.load_older_messages(window, cx);
1764+ } else {
1765+ self.chat.jump = None;
1766+ }
1767+ cx.notify();
1768+ }
1769+
1770+ fn fade_highlight(cx: &mut Context<Self>) {
1771+ cx.spawn(async move |this, cx| {
1772+ cx.background_executor().timer(HIGHLIGHT_TTL).await;
1773+ let _ = this.update(cx, |_, cx| cx.notify());
1774+ })
1775+ .detach();
1776+ }
1777+
1281 fn load_latest_messages(&self, window: &mut Window, cx: &mut Context<Self>) {1778 fn load_latest_messages(&self, window: &mut Window, cx: &mut Context<Self>) {
1282 self.load_messages(None, window, cx);1779 self.load_messages(None, window, cx);
1283 }1780 }
@@ -1294,6 +1791,7 @@ impl Yumush {
1294 return;1791 return;
1295 };1792 };
1296 let network = self.network.clone();1793 let network = self.network.clone();
1794+ let latest = before.is_none() && window.is_window_active();
1297 1795
1298 cx.spawn_in(window, async move |this, cx| {1796 cx.spawn_in(window, async move |this, cx| {
1299 let page = match network1797 let page = match network
@@ -1309,9 +1807,25 @@ impl Yumush {
1309 1807
1310 let _ = this.update_in(cx, |yumush, window, cx| {1808 let _ = this.update_in(cx, |yumush, window, cx| {
1311 if yumush.chat.is_selected(&community_id) {1809 if yumush.chat.is_selected(&community_id) {
1312- yumush.chat.add_page(page);1810+ let newest = page.last().map(|message| message.id.clone());
1811+ let seeking = yumush.chat.jump.is_some();
1812+ yumush
1813+ .chat
1814+ .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str()));
1815+ if seeking {
1816+ if yumush.chat.jump.is_none() {
1817+ Self::fade_highlight(cx);
1818+ } else if yumush.chat.history == History::More {
1819+ yumush.load_older_messages(window, cx);
1820+ } else {
1821+ yumush.chat.jump = None;
1822+ }
1823+ }
1824+ if let Some(message_id) = newest.filter(|_| latest) {
1825+ yumush.mark_read(&community_id, &message_id, cx);
1826+ }
1313 yumush.request_media(cx);1827 yumush.request_media(cx);
1314- yumush.request_authors(window, cx);1828+ yumush.request_authors(cx);
1315 cx.notify();1829 cx.notify();
1316 }1830 }
1317 });1831 });
@@ -1319,6 +1833,31 @@ impl Yumush {
1319 .detach();1833 .detach();
1320 }1834 }
1321 1835
1836+ pub(super) fn request_message_delete(
1837+ &mut self,
1838+ message_id: String,
1839+ window: &mut Window,
1840+ cx: &mut Context<Self>,
1841+ ) {
1842+ if self.chat.pending_message_delete.as_ref() == Some(&message_id) {
1843+ self.chat.pending_message_delete = None;
1844+ self.delete_message(&message_id, window, cx);
1845+ } else {
1846+ self.chat.pending_message_delete = Some(message_id.clone());
1847+ cx.spawn(async move |this, cx| {
1848+ cx.background_executor().timer(DELETE_CONFIRM).await;
1849+ let _ = this.update(cx, |yumush, cx| {
1850+ if yumush.chat.pending_message_delete.as_ref() == Some(&message_id) {
1851+ yumush.chat.pending_message_delete = None;
1852+ cx.notify();
1853+ }
1854+ });
1855+ })
1856+ .detach();
1857+ }
1858+ cx.notify();
1859+ }
1860+
1322 pub(super) fn delete_message(1861 pub(super) fn delete_message(
1323 &self,1862 &self,
1324 message_id: &str,1863 message_id: &str,
@@ -1382,7 +1921,12 @@ impl Yumush {
1382 .detach();1921 .detach();
1383 }1922 }
1384 1923
1385- fn toggle_voice(&mut self, community_id: String, window: &mut Window, cx: &mut Context<Self>) {1924+ pub(super) fn toggle_voice(
1925+ &mut self,
1926+ community_id: String,
1927+ window: &mut Window,
1928+ cx: &mut Context<Self>,
1929+ ) {
1386 if self.chat.in_voice(&community_id) {1930 if self.chat.in_voice(&community_id) {
1387 self.end_voice(cx);1931 self.end_voice(cx);
1388 return;1932 return;
@@ -1393,6 +1937,17 @@ impl Yumush {
1393 if was_in {1937 if was_in {
1394 self.chat.set_voice_off();1938 self.chat.set_voice_off();
1395 }1939 }
1940+ self.join_voice(community_id, (muted, deafened), was_in, window, cx);
1941+ }
1942+
1943+ fn join_voice(
1944+ &mut self,
1945+ community_id: String,
1946+ (muted, deafened): (bool, bool),
1947+ was_in: bool,
1948+ window: &mut Window,
1949+ cx: &mut Context<Self>,
1950+ ) {
1396 let network = self.network.clone();1951 let network = self.network.clone();
1397 1952
1398 cx.spawn_in(window, async move |this, cx| {1953 cx.spawn_in(window, async move |this, cx| {
@@ -1404,7 +1959,7 @@ impl Yumush {
1404 Ok(participants) => {1959 Ok(participants) => {
1405 network.set_deafened(deafened);1960 network.set_deafened(deafened);
1406 let _ = this.update_in(cx, |yumush, _, cx| {1961 let _ = this.update_in(cx, |yumush, _, cx| {
1407- let muted = muted || yumush.mic_locked();1962+ let muted = muted || yumush.mic_locked() || yumush.hidden_in(&community_id);
1408 yumush.network.set_muted(muted);1963 yumush.network.set_muted(muted);
1409 yumush.chat.voice.insert(community_id.clone(), participants);1964 yumush.chat.voice.insert(community_id.clone(), participants);
1410 yumush.chat.voice_state = VoiceState::In {1965 yumush.chat.voice_state = VoiceState::In {
@@ -1441,6 +1996,28 @@ impl Yumush {
1441 .detach();1996 .detach();
1442 }1997 }
1443 1998
1999+ pub(super) fn rejoin_voice(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2000+ let Some(community_id) = self.chat.voice_community().map(str::to_string) else {
2001+ return;
2002+ };
2003+ let flags = self.chat.voice_flags().unwrap_or((false, false));
2004+ self.chat.set_voice_off();
2005+ let network = self.network.clone();
2006+
2007+ cx.spawn_in(window, async move |this, cx| {
2008+ let Ok(participants) = network.voice_participants(&community_id).await else {
2009+ return;
2010+ };
2011+ let _ = this.update_in(cx, |yumush, window, cx| {
2012+ if participants.iter().any(|id| !yumush.is_me(id)) {
2013+ yumush.join_voice(community_id, flags, false, window, cx);
2014+ }
2015+ cx.notify();
2016+ });
2017+ })
2018+ .detach();
2019+ }
2020+
1444 pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context<Self>) {2021 pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context<Self>) {
1445 if self.chat.in_voice(community_id) {2022 if self.chat.in_voice(community_id) {
1446 self.end_voice(cx);2023 self.end_voice(cx);
@@ -1454,7 +2031,17 @@ impl Yumush {
1454 }2031 }
1455 2032
1456 pub(super) fn mic_locked(&self) -> bool {2033 pub(super) fn mic_locked(&self) -> bool {
1457- self.is_server_muted() || self.chat.ghost2034+ self.is_server_muted()
2035+ }
2036+
2037+ fn hidden_in(&self, community_id: &str) -> bool {
2038+ self.chat.ghost || !self.chat.joined(community_id)
2039+ }
2040+
2041+ fn hidden_in_voice(&self) -> bool {
2042+ self.chat
2043+ .voice_community()
2044+ .is_some_and(|community_id| self.hidden_in(community_id))
1458 }2045 }
1459 2046
1460 pub(super) fn force_mute(&mut self, cx: &mut Context<Self>) {2047 pub(super) fn force_mute(&mut self, cx: &mut Context<Self>) {
@@ -1465,17 +2052,83 @@ impl Yumush {
1465 cx.notify();2052 cx.notify();
1466 }2053 }
1467 2054
1468- fn toggle_mute(&mut self, cx: &mut Context<Self>) {2055+ fn toggle_mute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1469 if self.mic_locked() {2056 if self.mic_locked() {
1470 return;2057 return;
1471 }2058 }
2059+ let Some((muted, _)) = self.chat.voice_flags() else {
2060+ return;
2061+ };
2062+ if muted && self.hidden_in_voice() {
2063+ self.confirm_ghost_speak(window, cx);
2064+ return;
2065+ }
2066+ self.set_muted(!muted, cx);
2067+ }
2068+
2069+ fn set_muted(&mut self, value: bool, cx: &mut Context<Self>) {
1472 if let VoiceState::In { muted, .. } = &mut self.chat.voice_state {2070 if let VoiceState::In { muted, .. } = &mut self.chat.voice_state {
1473- *muted = !*muted;2071+ *muted = value;
1474- self.network.set_muted(*muted);2072+ self.network.set_muted(value);
1475 }2073 }
1476 cx.notify();2074 cx.notify();
1477 }2075 }
1478 2076
2077+ fn confirm_ghost_speak(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2078+ let entity = cx.entity();
2079+ window.open_dialog(cx, move |dialog, _, cx| {
2080+ let palette = entity.read(cx).themed(cx);
2081+ let speak = entity.clone();
2082+
2083+ dialog.title("Speak as ghost?").child(
2084+ div()
2085+ .flex()
2086+ .flex_col()
2087+ .gap(px(14.))
2088+ .child(
2089+ div()
2090+ .text_size(text(13.))
2091+ .text_color(palette.muted)
2092+ .child("Everyone in the call will hear you."),
2093+ )
2094+ .child(
2095+ div()
2096+ .flex()
2097+ .justify_end()
2098+ .gap(px(8.))
2099+ .child(
2100+ clickable("ghost_speak_cancel", palette, |window, cx| {
2101+ window.close_dialog(cx)
2102+ })
2103+ .h(px(30.))
2104+ .px(px(14.))
2105+ .flex()
2106+ .items_center()
2107+ .rounded(px(8.))
2108+ .text_color(palette.muted)
2109+ .child("Cancel"),
2110+ )
2111+ .child(
2112+ primary_button(
2113+ "ghost_speak_confirm",
2114+ palette,
2115+ move |window, cx| {
2116+ window.close_dialog(cx);
2117+ speak.update(cx, |yumush, cx| yumush.set_muted(false, cx));
2118+ },
2119+ )
2120+ .h(px(30.))
2121+ .px(px(14.))
2122+ .flex()
2123+ .items_center()
2124+ .rounded(px(8.))
2125+ .child("Speak"),
2126+ ),
2127+ ),
2128+ )
2129+ });
2130+ }
2131+
1479 fn toggle_deafen(&mut self, cx: &mut Context<Self>) {2132 fn toggle_deafen(&mut self, cx: &mut Context<Self>) {
1480 if let VoiceState::In { deafened, .. } = &mut self.chat.voice_state {2133 if let VoiceState::In { deafened, .. } = &mut self.chat.voice_state {
1481 *deafened = !*deafened;2134 *deafened = !*deafened;
@@ -1488,15 +2141,30 @@ impl Yumush {
1488 let network = self.network.clone();2141 let network = self.network.clone();
1489 2142
1490 self.chat.voice_task = Some(cx.spawn(async move |this, cx| {2143 self.chat.voice_task = Some(cx.spawn(async move |this, cx| {
2144+ let mut sampled = Instant::now();
1491 loop {2145 loop {
1492 cx.background_executor()2146 cx.background_executor()
1493 .timer(Duration::from_millis(150))2147 .timer(Duration::from_millis(150))
1494 .await;2148 .await;
1495 let speaking = network.speaking();2149 let speaking = network.speaking();
2150+ let sample = (sampled.elapsed() >= VOICE_SAMPLE_INTERVAL)
2151+ .then(|| network.voice_sample())
2152+ .flatten();
2153+ if sample.is_some() {
2154+ sampled = Instant::now();
2155+ }
1496 let polling = this.update(cx, |yumush, cx| {2156 let polling = this.update(cx, |yumush, cx| {
1497 if yumush.chat.voice_community().is_none() {2157 if yumush.chat.voice_community().is_none() {
1498 return false;2158 return false;
1499 }2159 }
2160+ if let Some(sample) = sample {
2161+ let samples = &mut yumush.chat.voice_samples;
2162+ samples.push_back(sample);
2163+ while samples.len() > SAMPLE_HISTORY {
2164+ samples.pop_front();
2165+ }
2166+ cx.notify();
2167+ }
1500 yumush.update_speaking(speaking, cx);2168 yumush.update_speaking(speaking, cx);
1501 true2169 true
1502 });2170 });
@@ -1525,10 +2193,15 @@ impl Yumush {
1525 2193
1526 fn voice_button(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {2194 fn voice_button(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
1527 let community_id = self.chat.selected_community_id.clone()?;2195 let community_id = self.chat.selected_community_id.clone()?;
2196+ let direct = self.is_direct(&community_id);
1528 let in_voice = self.chat.in_voice(&community_id);2197 let in_voice = self.chat.in_voice(&community_id);
1529 if !in_voice2198 if !in_voice
1530 && (!permission::can_join_voice(self.actor_rank())2199 && (!permission::can_join_voice(self.actor_rank())
1531- || !self.chat.voice_enabled(&community_id))2200+ || !(self.is_builder() || self.chat.voice_enabled(&community_id))
2201+ || self
2202+ .chat
2203+ .notes()
2204+ .is_some_and(|notes| notes.id == community_id))
1532 {2205 {
1533 return None;2206 return None;
1534 }2207 }
@@ -1544,14 +2217,21 @@ impl Yumush {
1544 } else {2217 } else {
1545 clickable("voice_button", palette, on_click)2218 clickable("voice_button", palette, on_click)
1546 };2219 };
2220+ let button = if direct && in_voice {
2221+ button.bg(palette.danger)
2222+ } else {
2223+ button
2224+ };
2225+ let (icon, tip) = match (direct, in_voice) {
2226+ (true, false) => (IconName::Phone, "Call"),
2227+ (true, true) => (IconName::PhoneOff, "Hang up"),
2228+ (false, false) => (IconName::Headphones, "Join voice"),
2229+ (false, true) => (IconName::Headphones, "Leave voice"),
2230+ };
1547 2231
1548 Some(2232 Some(
1549 button2233 button
1550- .tip(if in_voice {2234+ .tip(tip)
1551- "Leave voice"
1552- } else {
1553- "Join voice"
1554- })
1555 .size(px(28.))2235 .size(px(28.))
1556 .flex()2236 .flex()
1557 .items_center()2237 .items_center()
@@ -1562,10 +2242,159 @@ impl Yumush {
1562 } else {2242 } else {
1563 palette.accent2243 palette.accent
1564 })2244 })
1565- .child(Icon::new(IconName::Headphones).w(px(14.)).h(px(14.))),2245+ .child(Icon::new(icon).w(px(14.)).h(px(14.))),
1566 )2246 )
1567 }2247 }
1568 2248
2249+ fn calling_hint(&self, palette: Palette) -> Option<Div> {
2250+ let community = self.chat.selected_community()?;
2251+ let direct = self.is_direct(&community.id);
2252+ let alone = self.chat.in_voice(&community.id)
2253+ && self
2254+ .chat
2255+ .voice_ids(&community.id)
2256+ .iter()
2257+ .all(|id| self.is_me(id));
2258+
2259+ (direct && alone).then(|| {
2260+ div()
2261+ .text_color(palette.muted)
2262+ .text_size(text(11.))
2263+ .child("Calling…")
2264+ })
2265+ }
2266+
2267+ fn call_banner(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
2268+ let (community_id, caller) = self.incoming_call()?;
2269+ let accept_id = community_id.clone();
2270+
2271+ Some(
2272+ div()
2273+ .flex()
2274+ .items_center()
2275+ .justify_between()
2276+ .gap(px(8.))
2277+ .px(px(12.))
2278+ .py(px(6.))
2279+ .bg(palette.accent)
2280+ .text_color(palette.on_accent)
2281+ .child(
2282+ div()
2283+ .flex()
2284+ .items_center()
2285+ .gap(px(6.))
2286+ .child(Icon::new(IconName::PhoneIncoming).w(px(14.)).h(px(14.)))
2287+ .child(format!("{} is calling", caller.username)),
2288+ )
2289+ .child(
2290+ div()
2291+ .flex()
2292+ .gap(px(6.))
2293+ .child(
2294+ primary_button(
2295+ "accept_call",
2296+ palette,
2297+ entity_action(entity, move |yumush, window, cx| {
2298+ yumush.accept_call(accept_id.clone(), window, cx)
2299+ }),
2300+ )
2301+ .bg(palette.ok)
2302+ .px(px(8.))
2303+ .rounded(px(4.))
2304+ .child("Accept"),
2305+ )
2306+ .child(
2307+ clickable(
2308+ "decline_call",
2309+ palette,
2310+ entity_action(entity, move |yumush, window, cx| {
2311+ yumush.decline_call(community_id.clone(), window, cx)
2312+ }),
2313+ )
2314+ .bg(palette.danger)
2315+ .text_color(palette.on_accent)
2316+ .px(px(8.))
2317+ .rounded(px(4.))
2318+ .child("Decline"),
2319+ ),
2320+ ),
2321+ )
2322+ }
2323+
2324+ fn incoming_call(&self) -> Option<(String, User)> {
2325+ self.chat.communities().iter().find_map(|community| {
2326+ let CommunityKind::Direct { peer } = &community.kind else {
2327+ return None;
2328+ };
2329+ let calling = self.user.is_some()
2330+ && self
2331+ .chat
2332+ .voice_ids(&community.id)
2333+ .iter()
2334+ .any(|id| !self.is_me(id));
2335+ let ringing = calling
2336+ && !self.chat.in_voice(&community.id)
2337+ && self.chat.ringing.contains(&community.id);
2338+ ringing.then(|| (community.id.clone(), peer.clone()))
2339+ })
2340+ }
2341+
2342+ fn ring_allowed(&self, community_id: &str) -> bool {
2343+ self.user
2344+ .as_ref()
2345+ .is_some_and(|me| self.presence_of(&me.id) == Presence::Online)
2346+ && !self.chat.muted.contains(community_id)
2347+ }
2348+
2349+ pub(super) fn update_ringing(&mut self, cx: &mut Context<Self>) {
2350+ if self.incoming_call().is_none() {
2351+ self.chat.ring_task = None;
2352+ return;
2353+ }
2354+ if self.chat.ring_task.is_some() {
2355+ return;
2356+ }
2357+
2358+ self.chat.ring_task = Some(cx.spawn(async move |this, cx| {
2359+ for _ in 0..RING_LIMIT {
2360+ let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() {
2361+ Some((community_id, _)) => {
2362+ if yumush.ring_allowed(&community_id) {
2363+ yumush.network.play_ring();
2364+ }
2365+ true
2366+ }
2367+ None => false,
2368+ });
2369+ if !matches!(ringing, Ok(true)) {
2370+ break;
2371+ }
2372+ cx.background_executor().timer(RING_INTERVAL).await;
2373+ }
2374+ }));
2375+ }
2376+
2377+ fn accept_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context<Self>) {
2378+ self.chat.ringing.remove(&community_id);
2379+ self.select_community(community_id.clone(), window, cx);
2380+ self.toggle_voice(community_id, window, cx);
2381+ self.update_ringing(cx);
2382+ }
2383+
2384+ fn decline_call(&mut self, community_id: String, window: &mut Window, cx: &mut Context<Self>) {
2385+ self.chat.ringing.remove(&community_id);
2386+ self.update_ringing(cx);
2387+ cx.notify();
2388+
2389+ let network = self.network.clone();
2390+ cx.spawn_in(window, async move |this, cx| {
2391+ if let Err(error) = network.decline_call(&community_id).await {
2392+ notify_error(&this, cx, error);
2393+ }
2394+ })
2395+ .detach();
2396+ }
2397+
1569 fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {2398 fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
1570 let community_id = self.chat.selected_community_id.as_deref()?;2399 let community_id = self.chat.selected_community_id.as_deref()?;
1571 let users: Vec<&User> = self2400 let users: Vec<&User> = self
@@ -1618,7 +2447,7 @@ impl Yumush {
1618 IconName::Mic2447 IconName::Mic
1619 };2448 };
1620 let deafen_icon = if deafened {2449 let deafen_icon = if deafened {
1621- IconName::VolumeX2450+ IconName::HeadphoneOff
1622 } else {2451 } else {
1623 IconName::Headphones2452 IconName::Headphones
1624 };2453 };
@@ -1628,10 +2457,14 @@ impl Yumush {
1628 .flex()2457 .flex()
1629 .items_center()2458 .items_center()
1630 .child(2459 .child(
1631- clickable("mic_button", palette, move |_, cx| {2460+ clickable("mic_button", palette, move |window, cx| {
1632- mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(cx))2461+ mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(window, cx))
2462+ })
2463+ .tip(match (muted, self.hidden_in_voice()) {
2464+ (true, true) => "Speak as ghost",
2465+ (true, false) => "Unmute",
2466+ (false, _) => "Mute",
1633 })2467 })
1634- .tip(if muted { "Unmute" } else { "Mute" })
1635 .size(px(26.))2468 .size(px(26.))
1636 .flex()2469 .flex()
1637 .items_center()2470 .items_center()
@@ -1672,14 +2505,15 @@ impl Yumush {
1672 }2505 }
1673 }2506 }
1674 2507
1675-fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> impl IntoElement {2508+fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> impl IntoElement {
2509+ let chat = &yumush.chat;
1676 let entity = entity.clone();2510 let entity = entity.clone();
1677 let voice: Vec<String> = chat2511 let voice: Vec<String> = chat
1678 .selected_community_id2512 .selected_community_id
1679 .as_deref()2513 .as_deref()
1680 .map(|community_id| chat.voice_ids(community_id).to_vec())2514 .map(|community_id| chat.voice_ids(community_id).to_vec())
1681 .unwrap_or_default();2515 .unwrap_or_default();
1682- let members: Vec<(User, Option<Rank>, bool, bool)> = chat2516+ let members: Vec<(User, Option<Rank>, bool, bool, Presence)> = chat
1683 .members2517 .members
1684 .iter()2518 .iter()
1685 .map(|member| {2519 .map(|member| {
@@ -1688,6 +2522,7 @@ fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> im
1688 chat.rank_of(&member.user),2522 chat.rank_of(&member.user),
1689 voice.contains(&member.user.id),2523 voice.contains(&member.user.id),
1690 chat.server_muted.contains(&member.user.id),2524 chat.server_muted.contains(&member.user.id),
2525+ yumush.presence_of(&member.user.id),
1691 )2526 )
1692 })2527 })
1693 .collect();2528 .collect();
@@ -1698,78 +2533,111 @@ fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> im
1698 .appearance(false)2533 .appearance(false)
1699 .trigger(MembersTrigger {2534 .trigger(MembersTrigger {
1700 palette,2535 palette,
1701- members: members.iter().map(|(user, _, _, _)| user.clone()).collect(),2536+ members: members
2537+ .iter()
2538+ .map(|(user, _, _, _, _)| user.clone())
2539+ .collect(),
1702 avatars: avatars.clone(),2540 avatars: avatars.clone(),
1703 })2541 })
1704 .content(move |_, _, _| {2542 .content(move |_, _, _| {
1705 let entity = entity.clone();2543 let entity = entity.clone();
1706 2544
1707- div()2545+ pop_in(
1708- .w(px(200.))2546+ "members_list",
1709- .p(px(4.))2547+ div()
1710- .flex()2548+ .w(px(200.))
1711- .flex_col()2549+ .p(px(4.))
1712- .rounded(px(8.))2550+ .flex()
1713- .border_1()2551+ .flex_col()
1714- .border_color(palette.border)2552+ .rounded(px(8.))
1715- .bg(palette.panel)2553+ .border_1()
1716- .children(members.iter().map(|(user, rank, in_voice, muted)| {2554+ .border_color(palette.border)
1717- profile_popover(2555+ .bg(palette.panel)
1718- format!("member_{}", user.id),2556+ .children(
1719- Anchor::TopRight,2557+ members
1720- user,2558+ .iter()
1721- &entity,2559+ .map(|(user, rank, in_voice, muted, presence)| {
1722- hoverable(2560+ profile_popover(
1723- format!("member_trigger_{}", user.id),2561+ format!("member_{}", user.id),
1724- div()2562+ Anchor::TopRight,
1725- .h(px(30.))2563+ user,
1726- .px(px(8.))2564+ &entity,
1727- .flex()2565+ hoverable(
1728- .items_center()2566+ format!("member_trigger_{}", user.id),
1729- .gap(px(8.))2567+ div()
1730- .rounded(px(6.))2568+ .h(px(30.))
1731- .child(avatar(palette, user, px(18.), text(9.), &avatars))2569+ .px(px(8.))
1732- .child(2570+ .flex()
1733- div()2571+ .items_center()
1734- .flex_1()2572+ .gap(px(8.))
1735- .min_w_0()2573+ .rounded(px(6.))
1736- .flex()2574+ .child(presence_avatar(
1737- .flex_col()2575+ avatar(palette, user, px(18.), text(9.), &avatars),
1738- .child(2576+ *presence,
1739- div()2577+ px(18.),
1740- .flex()2578+ palette,
1741- .items_center()2579+ ))
1742- .gap(px(6.))2580+ .child(
1743- .child(user.username.clone())2581+ div()
1744- .children(rank_tag(*rank, palette))2582+ .flex_1()
1745- .children(in_voice.then(|| {2583+ .min_w_0()
1746- Icon::new(IconName::Headphones)2584+ .flex()
1747- .w(px(12.))2585+ .flex_col()
1748- .h(px(12.))2586+ .child(
1749- .text_color(palette.muted)2587+ div()
1750- }))2588+ .flex()
1751- .children(muted.then(|| {2589+ .items_center()
1752- Icon::new(IconName::MicOff)2590+ .gap(px(6.))
1753- .w(px(12.))2591+ .child(user.username.clone())
1754- .h(px(12.))2592+ .children(rank_tag(*rank, palette))
1755- .text_color(palette.danger)2593+ .children(in_voice.then(|| {
1756- })),2594+ Icon::new(IconName::Headphones)
1757- )2595+ .w(px(12.))
1758- .children((!user.status.is_empty()).then(|| {2596+ .h(px(12.))
1759- div()2597+ .text_color(palette.muted)
1760- .text_size(text(11.))2598+ }))
1761- .text_color(palette.muted)2599+ .children(muted.then(|| {
1762- .truncate()2600+ Icon::new(IconName::MicOff)
1763- .child(user.status.clone())2601+ .w(px(12.))
1764- })),2602+ .h(px(12.))
1765- ),2603+ .text_color(palette.danger)
1766- palette,2604+ })),
1767- ),2605+ )
1768- )2606+ .children((!user.status.is_empty()).then(
1769- }))2607+ || {
2608+ div()
2609+ .text_size(text(11.))
2610+ .text_color(palette.muted)
2611+ .truncate()
2612+ .child(user.status.clone())
2613+ },
2614+ )),
2615+ ),
2616+ palette,
2617+ ),
2618+ )
2619+ }),
2620+ ),
2621+ Anchor::TopRight,
2622+ )
1770 })2623 })
1771 }2624 }
1772 2625
2626+fn new_divider(palette: Palette) -> impl IntoElement {
2627+ div()
2628+ .flex()
2629+ .items_center()
2630+ .gap(px(8.))
2631+ .my(px(6.))
2632+ .child(div().flex_1().h(px(1.)).bg(palette.accent))
2633+ .child(
2634+ div()
2635+ .text_size(text(10.))
2636+ .text_color(palette.accent)
2637+ .child("New"),
2638+ )
2639+}
2640+
1773 fn older_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {2641 fn older_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
1774 let entity = entity.clone();2642 let entity = entity.clone();
1775 2643
@@ -1786,6 +2654,55 @@ fn older_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
1786 .child("↑")2654 .child("↑")
1787 }2655 }
1788 2656
2657+fn call_duration(seconds: u64) -> String {
2658+ let (hours, minutes, seconds) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
2659+ if hours > 0 {
2660+ format!("{hours}h {minutes}m")
2661+ } else if minutes > 0 {
2662+ format!("{minutes}m {seconds}s")
2663+ } else {
2664+ format!("{seconds}s")
2665+ }
2666+}
2667+
2668+fn render_call(
2669+ message: &Message,
2670+ call: CallLog,
2671+ chat: &Chat,
2672+ me: Option<&User>,
2673+ palette: Palette,
2674+) -> AnyElement {
2675+ let mine = me.is_some_and(|me| me.id == message.user_id);
2676+ let author = chat
2677+ .author(&message.user_id)
2678+ .map_or("unknown", |user| user.username.as_str());
2679+ let who = if mine { "You" } else { author };
2680+ let (icon, color) = match call {
2681+ CallLog::Started | CallLog::Ended { .. } => (IconName::Phone, palette.ok),
2682+ CallLog::Declined => (IconName::PhoneOff, palette.danger),
2683+ CallLog::Missed => (IconName::PhoneMissed, palette.danger),
2684+ };
2685+ let label = match call {
2686+ CallLog::Started => format!("{who} started a call"),
2687+ CallLog::Declined => format!("{who} declined the call"),
2688+ CallLog::Missed if mine => "You called, no answer".to_string(),
2689+ CallLog::Missed => format!("Missed call from {author}"),
2690+ CallLog::Ended { seconds } => format!("Call ended · {}", call_duration(seconds)),
2691+ };
2692+
2693+ div()
2694+ .id(format!("message_row_{}", message.id))
2695+ .flex()
2696+ .items_center()
2697+ .gap(px(6.))
2698+ .pl(px(28.))
2699+ .text_size(text(12.))
2700+ .text_color(palette.muted)
2701+ .child(Icon::new(icon).w(px(14.)).h(px(14.)).text_color(color))
2702+ .child(label)
2703+ .into_any_element()
2704+}
2705+
1789 fn render_message(2706 fn render_message(
1790 message: &Message,2707 message: &Message,
1791 first: bool,2708 first: bool,
@@ -1795,6 +2712,9 @@ fn render_message(
1795 entity: &Entity<Yumush>,2712 entity: &Entity<Yumush>,
1796 palette: Palette,2713 palette: Palette,
1797 ) -> AnyElement {2714 ) -> AnyElement {
2715+ if let Some(call) = message.call {
2716+ return render_call(message, call, chat, me, palette);
2717+ }
1798 let author = chat.author(&message.user_id);2718 let author = chat.author(&message.user_id);
1799 let username = author2719 let username = author
1800 .map(|user| user.username.as_str())2720 .map(|user| user.username.as_str())
@@ -1817,97 +2737,139 @@ fn render_message(
1817 })2737 })
1818 .child(username.to_string()),2738 .child(username.to_string()),
1819 );2739 );
2740+ let mentioned = me.is_some_and(|me| mentions(&message.body, &me.username));
1820 let group = format!("message_{}", message.id);2741 let group = format!("message_{}", message.id);
1821 let selecting = matches!(chat.composer, Composer::Select { .. });2742 let selecting = matches!(chat.composer, Composer::Select { .. });
1822 let selected = matches!(&chat.composer, Composer::Select { ids } if ids.contains(&message.id));2743 let selected = matches!(&chat.composer, Composer::Select { ids } if ids.contains(&message.id));
1823-2744+ let highlighted = chat
1824- let row =2745+ .highlight
1825- div()2746+ .as_ref()
1826- .id(format!("message_row_{}", message.id))2747+ .is_some_and(|(id, at)| id == &message.id && at.elapsed() < HIGHLIGHT_TTL);
1827- .group(group.clone())2748+
1828- .flex()2749+ let row = div()
1829- .flex_col()2750+ .id(format!("message_row_{}", message.id))
1830- .min_w_0()2751+ .group(group.clone())
1831- .when(first && spaced, |this| this.mt(px(14.)))2752+ .flex()
1832- .when(first, |this| {2753+ .flex_col()
1833- let author = match author {2754+ .min_w_0()
1834- Some(user) => profile_popover(2755+ .when(first && spaced && !selecting, |this| this.mt(px(14.)))
1835- format!("author_{}", message.id),2756+ .when(highlighted, |this| this.bg(palette.accent.opacity(0.2)))
1836- Anchor::TopLeft,2757+ .when(mentioned, |this| {
1837- user,2758+ this.bg(palette.accent.opacity(0.08))
1838- entity,2759+ .border_l_2()
1839- name.cursor_pointer(),2760+ .border_color(palette.accent)
1840- )2761+ })
1841- .into_any_element(),2762+ .when(first, |this| {
1842- None => name.into_any_element(),2763+ let author = match author {
1843- };2764+ Some(user) => profile_popover(
1844-2765+ format!("author_{}", message.id),
1845- this.child(2766+ Anchor::TopLeft,
1846- div()2767+ user,
1847- .flex()2768+ entity,
1848- .items_center()2769+ name.cursor_pointer(),
1849- .gap(px(8.))
1850- .mb(px(2.))
1851- .child(author)
1852- .child(
1853- div()
1854- .text_size(text(12.))
1855- .text_color(palette.muted)
1856- .child(id_time(&message.id, CLOCK)),
1857- ),
1858 )2770 )
1859- })2771+ .into_any_element(),
1860- .child(2772+ None => name.into_any_element(),
2773+ };
2774+
2775+ this.child(
1861 div()2776 div()
1862- .pl(px(28.))
1863 .flex()2777 .flex()
1864 .items_center()2778 .items_center()
1865 .gap(px(8.))2779 .gap(px(8.))
2780+ .mb(px(2.))
2781+ .child(author)
1866 .child(2782 .child(
1867 div()2783 div()
1868- .max_w(px(720.))2784+ .text_size(text(12.))
1869- .flex()2785+ .text_color(palette.muted)
1870- .flex_col()2786+ .child(id_time(&message.id, CLOCK)),
1871- .gap(px(6.))2787+ ),
1872- .children(message_actions::quote_line(message, chat, palette))2788+ )
1873- .when(!message.body.is_empty(), |this| {2789+ })
1874- this.child(2790+ .child(
1875- div()2791+ div()
1876- .flex()2792+ .relative()
1877- .flex_wrap()2793+ .pl(px(28.))
1878- .items_baseline()2794+ .min_w_0()
1879- .gap(px(4.))2795+ .flex()
1880- .line_height(relative(1.55))2796+ .items_center()
1881- .text_color(palette.body)2797+ .gap(px(8.))
1882- .child(message.body.clone())2798+ .child(
1883- .when(message.edited, |this| {2799+ div()
1884- this.child(2800+ .min_w_0()
1885- div()2801+ .max_w(px(720.))
1886- .text_size(text(11.))2802+ .flex()
1887- .text_color(palette.muted)2803+ .flex_col()
1888- .child("(edited)"),2804+ .gap(px(6.))
2805+ .children(message_actions::quote_line(message, chat, palette))
2806+ .when(!message.body.is_empty(), |this| {
2807+ this.child(
2808+ div()
2809+ .min_w_0()
2810+ .flex()
2811+ .flex_wrap()
2812+ .items_baseline()
2813+ .gap(px(4.))
2814+ .line_height(relative(1.55))
2815+ .text_color(palette.body)
2816+ .child(
2817+ div().min_w_0().child(
2818+ gpui_kit::component::text::TextView::markdown(
2819+ format!("message-body-{}", message.id),
2820+ hard_breaks(&message.body),
1889 )2821 )
1890- }),2822+ .selectable(true),
1891- )2823+ ),
1892- })2824+ )
1893- .children(media_view::attachments(2825+ .when(message.edited, |this| {
1894- &message.attachments,2826+ this.child(
1895- &chat.media,2827+ div()
2828+ .text_size(text(11.))
2829+ .text_color(palette.muted)
2830+ .child("(edited)"),
2831+ )
2832+ }),
2833+ )
2834+ })
2835+ .children(media_view::attachments(
2836+ &message.attachments,
2837+ &chat.media,
2838+ entity,
2839+ palette,
2840+ ))
2841+ .children(snippet::snippet_card(message, chat, entity, palette))
2842+ .children(message.poll.as_ref().map(|poll| {
2843+ poll::poll_card(
2844+ poll,
2845+ poll::PollMode::Live(message),
2846+ me,
2847+ chat,
1896 entity,2848 entity,
1897 palette,2849 palette,
1898- ))2850+ )
1899- .children(snippet::snippet_card(message, chat, entity, palette))2851+ }))
1900- .children(media_view::embeds(message, &chat.media, palette)),2852+ .children(media_view::embeds(message, &chat.media, palette))
1901- )2853+ .children(
1902- .child(div().flex_1())2854+ (!message.reactions.is_empty())
1903- .children((!selecting).then(|| {2855+ .then(|| message_actions::reactions(message, me, entity, palette)),
1904- message_actions::actions(message, chat, me, entity, palette, group)2856+ ),
1905- })),2857+ )
1906- )2858+ .children(message.pinned.then(|| message_actions::pin_mark(palette)))
1907- .children(2859+ .children((!selecting).then(|| {
1908- (chat.report == Some(ReportTarget::Message(message.id.clone())))2860+ div()
1909- .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)),2861+ .absolute()
1910- );2862+ .right_0()
2863+ .top(px(-18.))
2864+ .child(message_actions::actions(
2865+ message, chat, me, entity, palette, group,
2866+ ))
2867+ })),
2868+ )
2869+ .children(
2870+ (chat.report == Some(ReportTarget::Message(message.id.clone())))
2871+ .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)),
2872+ );
1911 2873
1912 if !selecting {2874 if !selecting {
1913 return row.into_any_element();2875 return row.into_any_element();
@@ -1915,20 +2877,34 @@ fn render_message(
1915 2877
1916 let message_id = message.id.clone();2878 let message_id = message.id.clone();
1917 let select_entity = entity.clone();2879 let select_entity = entity.clone();
1918- let row = row2880+ let mark_line = if first {
1919- .flex_1()2881+ div().h(px(20.))
1920- .cursor_pointer()2882+ } else {
1921- .when(selected, |this| this.bg(palette.hover))2883+ div().line_height(relative(1.55)).child("\u{200b}")
1922- .on_click(move |_, _, cx| {2884+ };
1923- select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx));
1924- });
1925 2885
1926 div()2886 div()
2887+ .id(format!("select_row_{}", message.id))
2888+ .when(first && spaced, |this| this.mt(px(14.)))
1927 .flex()2889 .flex()
1928 .items_start()2890 .items_start()
1929 .gap(px(8.))2891 .gap(px(8.))
1930- .child(message_actions::selection_mark(selected, palette))2892+ .px(px(6.))
1931- .child(row)2893+ .rounded(px(6.))
2894+ .cursor_pointer()
2895+ .hover(|style| style.bg(palette.hover.opacity(0.5)))
2896+ .when(selected, |this| this.bg(palette.hover))
2897+ .on_click(move |_, _, cx| {
2898+ select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx));
2899+ })
2900+ .child(
2901+ mark_line
2902+ .flex_shrink_0()
2903+ .flex()
2904+ .items_center()
2905+ .child(message_actions::selection_mark(selected, palette)),
2906+ )
2907+ .child(row.flex_1())
1932 .into_any_element()2908 .into_any_element()
1933 }2909 }
1934 2910
@@ -1951,3 +2927,21 @@ fn editable_input(
1951 .detach();2927 .detach();
1952 input2928 input
1953 }2929 }
2930+
2931+fn hard_breaks(body: &str) -> String {
2932+ let mut fenced = false;
2933+ let lines: Vec<String> = body
2934+ .lines()
2935+ .map(|line| {
2936+ if line.trim_start().starts_with("```") {
2937+ fenced = !fenced;
2938+ return line.to_string();
2939+ }
2940+ match fenced || line.trim().is_empty() {
2941+ true => line.to_string(),
2942+ false => format!("{line} "),
2943+ }
2944+ })
2945+ .collect();
2946+ lines.join("\n")
2947+}
crates/client/src/gui/community_settings.rsmodified+13 -2
@@ -26,6 +26,7 @@ use super::{
26 Palette, Yumush, avatar,26 Palette, Yumush, avatar,
27 chat::{DeleteStep, View},27 chat::{DeleteStep, View},
28 clickable, community_icon, entity_action, id_time, notify_error,28 clickable, community_icon, entity_action, id_time, notify_error,
29+ profile::user_link,
29 settings_page::{30 settings_page::{
30 Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file,31 Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file,
31 row, section, text_row,32 row, section, text_row,
@@ -701,14 +702,24 @@ fn ban_row(
701 .flex()702 .flex()
702 .items_center()703 .items_center()
703 .gap(px(8.))704 .gap(px(8.))
704- .child(avatar(palette, user, px(20.), text(10.), avatars))705+ .child(user_link(
706+ format!("ban_avatar_{user_id}"),
707+ Some(user),
708+ &entity,
709+ avatar(palette, user, px(20.), text(10.), avatars),
710+ ))
705 .child(711 .child(
706 div()712 div()
707 .flex_1()713 .flex_1()
708 .min_w_0()714 .min_w_0()
709 .flex()715 .flex()
710 .flex_col()716 .flex_col()
711- .child(user.username.clone())717+ .child(user_link(
718+ format!("ban_name_{user_id}"),
719+ Some(user),
720+ &entity,
721+ div().truncate().child(user.username.clone()),
722+ ))
712 .children(ban.reason.clone().map(|reason| {723 .children(ban.reason.clone().map(|reason| {
713 div()724 div()
714 .text_size(text(11.))725 .text_size(text(11.))
crates/client/src/gui/composer.rsmodified+412 -7
@@ -1,16 +1,46 @@
1 use super::text;1 use super::text;
2+use std::time::{Duration, Instant};
3+
2 use common::{4 use common::{
3- constant::MAXIMUM_FORWARD_MESSAGES,5+ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_POLL_OPTIONS, MINIMUM_POLL_OPTIONS},
4- validate::{validate_message_body, validate_new_message},6+ error::Error,
7+ model::Attachment,
8+ time::now_ms,
9+ validate::{validate_message_body, validate_new_message, validate_poll},
5 };10 };
6 use gpui_kit::{11 use gpui_kit::{
7- AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,12+ Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement,
13+ KeyBinding, ParentElement, Styled, Window, actions,
8 assets::IconName,14 assets::IconName,
9- component::{Icon, WindowExt, input::InputState, notification::Notification},15+ component::{
16+ Icon, WindowExt,
17+ checkbox::Checkbox,
18+ input::{Input, InputState},
19+ notification::Notification,
20+ popover::Popover,
21+ text::TextView,
22+ },
10 div, px,23 div, px,
11 };24 };
12 25
13-use super::{Palette, Tooltip as _, Yumush, chat::Chat, clickable, notify_error, primary_button};26+use super::{
27+ Palette, Tooltip as _, Trigger, Yumush,
28+ chat::{Chat, TYPING_SEND_INTERVAL},
29+ clickable, hoverable, new_input, notify_error, pop_in, primary_button,
30+};
31+
32+actions!(composer, [Bold, Italic, Code, Strike]);
33+
34+pub const CONTEXT: &str = "MessageComposer";
35+
36+const FORMAT_ROWS: [(&str, &str); 6] = [
37+ ("**bold**", "Ctrl+B"),
38+ ("*italic*", "Ctrl+I"),
39+ ("`code`", "Ctrl+E"),
40+ ("~~strike~~", "Ctrl+Shift+X"),
41+ ("> quote", ""),
42+ ("- list", ""),
43+];
14 44
15 #[derive(Debug, Clone, PartialEq, Eq)]45 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub enum Composer {46 pub enum Composer {
@@ -19,7 +49,13 @@ pub enum Composer {
19 Select { ids: Vec<String> },49 Select { ids: Vec<String> },
20 }50 }
21 51
52+const SLOW_TICK: Duration = Duration::from_secs(1);
53+
22 pub fn mode_bar(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> Option<AnyElement> {54 pub fn mode_bar(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> Option<AnyElement> {
55+ if let Some(seconds) = chat.slow_seconds() {
56+ return Some(slow_bar(seconds, palette).into_any_element());
57+ }
58+
23 match &chat.composer {59 match &chat.composer {
24 Composer::Compose {60 Composer::Compose {
25 reply: Some(message_id),61 reply: Some(message_id),
@@ -110,6 +146,13 @@ fn reply_bar(
110 .child(cancel_button(entity, palette))146 .child(cancel_button(entity, palette))
111 }147 }
112 148
149+fn slow_bar(seconds: u64, palette: Palette) -> impl IntoElement {
150+ bar(palette)
151+ .text_color(palette.danger)
152+ .child(Icon::new(IconName::Hourglass).w(px(12.)).h(px(12.)))
153+ .child(format!("Slow down, you can send again in {seconds}s"))
154+}
155+
113 fn edit_bar(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {156 fn edit_bar(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
114 bar(palette)157 bar(palette)
115 .child(Icon::new(IconName::Pencil).w(px(12.)).h(px(12.)))158 .child(Icon::new(IconName::Pencil).w(px(12.)).h(px(12.)))
@@ -155,6 +198,35 @@ impl Yumush {
155 }198 }
156 }199 }
157 200
201+ pub(super) fn send_typing(&mut self, cx: &mut Context<Self>) {
202+ let Some(community_id) = self.chat.selected_community_id.clone() else {
203+ return;
204+ };
205+ if self
206+ .chat
207+ .message_input
208+ .read(cx)
209+ .text()
210+ .to_string()
211+ .is_empty()
212+ || self
213+ .chat
214+ .typing_sent
215+ .get(&community_id)
216+ .is_some_and(|at| at.elapsed() < TYPING_SEND_INTERVAL)
217+ {
218+ return;
219+ }
220+ self.chat
221+ .typing_sent
222+ .insert(community_id.clone(), Instant::now());
223+ let network = self.network.clone();
224+ cx.spawn(async move |_, _| {
225+ let _ = network.typing(&community_id).await;
226+ })
227+ .detach();
228+ }
229+
158 fn create_message(230 fn create_message(
159 &mut self,231 &mut self,
160 reply: Option<String>,232 reply: Option<String>,
@@ -171,6 +243,9 @@ impl Yumush {
171 .map(|attachment| attachment.id.clone())243 .map(|attachment| attachment.id.clone())
172 .collect();244 .collect();
173 245
246+ if self.chat.slow_seconds().is_some() {
247+ return;
248+ }
174 let maximum = self.max_message_length();249 let maximum = self.max_message_length();
175 if let Err(error) = validate_new_message(&body, attachments.len(), maximum) {250 if let Err(error) = validate_new_message(&body, attachments.len(), maximum) {
176 window.push_notification(Notification::error(error.to_string()), cx);251 window.push_notification(Notification::error(error.to_string()), cx);
@@ -181,13 +256,24 @@ impl Yumush {
181 return;256 return;
182 };257 };
183 let network = self.network.clone();258 let network = self.network.clone();
259+ let restore = input.clone();
260+ let pending = self.chat.media.pending.clone();
261+ self.chat.drafts.remove(&community_id);
184 262
185 cx.spawn_in(window, async move |this, cx| {263 cx.spawn_in(window, async move |this, cx| {
186- if let Err(error) = network264+ match network
187 .create_message(&community_id, &body, attachments, reply)265 .create_message(&community_id, &body, attachments, reply)
188 .await266 .await
189 {267 {
190- notify_error(&this, cx, error);268+ Ok(_) => {}
269+ Err(Error::RateLimited {
270+ retry_after_seconds,
271+ }) => {
272+ let _ = this.update_in(cx, |yumush, window, cx| {
273+ yumush.slow_down(retry_after_seconds, &restore, body, pending, window, cx)
274+ });
275+ }
276+ Err(error) => notify_error(&this, cx, error),
191 }277 }
192 })278 })
193 .detach();279 .detach();
@@ -197,6 +283,39 @@ impl Yumush {
197 self.chat.composer = Composer::Compose { reply: None };283 self.chat.composer = Composer::Compose { reply: None };
198 }284 }
199 285
286+ fn slow_down(
287+ &mut self,
288+ seconds: u64,
289+ input: &Entity<InputState>,
290+ body: String,
291+ pending: Vec<Attachment>,
292+ window: &mut Window,
293+ cx: &mut Context<Self>,
294+ ) {
295+ if input.read(cx).text().len() == 0 {
296+ input.update(cx, |state, cx| state.set_value(body, window, cx));
297+ }
298+ if self.chat.media.pending.is_empty() {
299+ self.chat.media.pending = pending;
300+ }
301+ self.chat.slowed_until = Some(now_ms() + seconds * 1000);
302+ cx.notify();
303+
304+ cx.spawn_in(window, async move |this, cx| {
305+ loop {
306+ cx.background_executor().timer(SLOW_TICK).await;
307+ let slowed = this.update(cx, |yumush, cx| {
308+ cx.notify();
309+ yumush.chat.slow_seconds().is_some()
310+ });
311+ if !matches!(slowed, Ok(true)) {
312+ break;
313+ }
314+ }
315+ })
316+ .detach();
317+ }
318+
200 fn update_message(319 fn update_message(
201 &mut self,320 &mut self,
202 message_id: String,321 message_id: String,
@@ -223,6 +342,35 @@ impl Yumush {
223 cx.notify();342 cx.notify();
224 }343 }
225 344
345+ pub(super) fn save_draft(&mut self, cx: &mut Context<Self>) {
346+ let Some(community_id) = self.chat.selected_community_id.clone() else {
347+ return;
348+ };
349+ let text = self.chat.message_input.read(cx).text().to_string();
350+ if text.is_empty() || !matches!(self.chat.composer, Composer::Compose { .. }) {
351+ self.chat.drafts.remove(&community_id);
352+ } else {
353+ self.chat.drafts.insert(community_id, text);
354+ }
355+ }
356+
357+ pub(super) fn restore_draft(
358+ &mut self,
359+ community_id: &str,
360+ window: &mut Window,
361+ cx: &mut Context<Self>,
362+ ) {
363+ let text = self
364+ .chat
365+ .drafts
366+ .get(community_id)
367+ .cloned()
368+ .unwrap_or_default();
369+ self.chat
370+ .message_input
371+ .update(cx, |input, cx| input.set_value(text, window, cx));
372+ }
373+
226 pub(super) fn reply(374 pub(super) fn reply(
227 &mut self,375 &mut self,
228 message_id: String,376 message_id: String,
@@ -294,3 +442,260 @@ impl Yumush {
294 cx.notify();442 cx.notify();
295 }443 }
296 }444 }
445+
446+pub fn bind_keys(cx: &mut App) {
447+ let scope = format!("{CONTEXT} > Input");
448+ cx.bind_keys([
449+ KeyBinding::new("ctrl-b", Bold, Some(scope.as_str())),
450+ KeyBinding::new("ctrl-i", Italic, Some(scope.as_str())),
451+ KeyBinding::new("ctrl-e", Code, Some(scope.as_str())),
452+ KeyBinding::new("ctrl-shift-x", Strike, Some(scope.as_str())),
453+ ]);
454+}
455+
456+pub fn format_actions(input: &Entity<InputState>, row: Div) -> Div {
457+ let (bold, italic, code, strike) = (input.clone(), input.clone(), input.clone(), input.clone());
458+ row.key_context(CONTEXT)
459+ .on_action(move |_: &Bold, window, cx| wrap(&bold, "**", window, cx))
460+ .on_action(move |_: &Italic, window, cx| wrap(&italic, "*", window, cx))
461+ .on_action(move |_: &Code, window, cx| wrap(&code, "`", window, cx))
462+ .on_action(move |_: &Strike, window, cx| wrap(&strike, "~~", window, cx))
463+}
464+
465+fn wrap(input: &Entity<InputState>, mark: &str, window: &mut Window, cx: &mut App) {
466+ input.update(cx, |state, cx| {
467+ let start = state.selected_range().start + mark.len();
468+ let selected = state.selected_text().to_string();
469+ state.replace(format!("{mark}{selected}{mark}"), window, cx);
470+ state.set_selected_range(start..start + selected.len(), cx);
471+ });
472+}
473+
474+pub fn format_popover(palette: Palette) -> impl IntoElement {
475+ Popover::new("format_popover")
476+ .anchor(Anchor::BottomLeft)
477+ .appearance(false)
478+ .trigger(Trigger::new(hoverable(
479+ "format_trigger",
480+ div()
481+ .size(px(28.))
482+ .flex()
483+ .items_center()
484+ .justify_center()
485+ .rounded(px(6.))
486+ .text_color(palette.muted)
487+ .child(Icon::new(IconName::Type).w(px(14.)).h(px(14.))),
488+ palette,
489+ )))
490+ .content(move |_, _, _| {
491+ pop_in(
492+ "format_list",
493+ div()
494+ .w(px(340.))
495+ .p(px(8.))
496+ .flex()
497+ .flex_col()
498+ .gap(px(6.))
499+ .rounded(px(8.))
500+ .border_1()
501+ .border_color(palette.border)
502+ .bg(palette.panel)
503+ .text_size(text(12.))
504+ .children(FORMAT_ROWS.map(|(syntax, shortcut)| {
505+ div()
506+ .flex()
507+ .items_center()
508+ .gap(px(12.))
509+ .child(div().w(px(100.)).text_color(palette.muted).child(syntax))
510+ .child(div().flex_1().child(TextView::markdown(syntax, syntax)))
511+ .child(div().text_color(palette.muted).child(shortcut))
512+ })),
513+ Anchor::BottomLeft,
514+ )
515+ })
516+}
517+
518+fn poll_field(input: &Entity<InputState>, palette: Palette) -> impl IntoElement {
519+ div()
520+ .h(px(30.))
521+ .px(px(10.))
522+ .flex()
523+ .items_center()
524+ .rounded(px(8.))
525+ .border_1()
526+ .border_color(palette.border)
527+ .bg(palette.field)
528+ .child(
529+ Input::new(input)
530+ .appearance(false)
531+ .text_color(palette.text)
532+ .flex_1()
533+ .min_w_0(),
534+ )
535+}
536+
537+pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
538+ let question = chat.poll_question.clone();
539+ let options = chat.poll_options.clone();
540+ let multiple = chat.poll_multiple;
541+ let entity = entity.clone();
542+
543+ Popover::new("poll_popover")
544+ .anchor(Anchor::BottomLeft)
545+ .appearance(false)
546+ .trigger(Trigger::new(hoverable(
547+ "poll_trigger",
548+ div()
549+ .size(px(28.))
550+ .flex()
551+ .items_center()
552+ .justify_center()
553+ .rounded(px(6.))
554+ .text_color(palette.muted)
555+ .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))),
556+ palette,
557+ )))
558+ .content(move |_, _, cx| {
559+ let popover = cx.entity();
560+ let toggle = entity.clone();
561+ let add = entity.clone();
562+ let submit = entity.clone();
563+ pop_in(
564+ "poll_form",
565+ div()
566+ .w(px(300.))
567+ .p(px(8.))
568+ .flex()
569+ .flex_col()
570+ .gap(px(6.))
571+ .rounded(px(8.))
572+ .border_1()
573+ .border_color(palette.border)
574+ .bg(palette.panel)
575+ .text_size(text(12.))
576+ .child(poll_field(&question, palette))
577+ .children(options.iter().enumerate().map(|(index, option)| {
578+ let remove = entity.clone();
579+ div()
580+ .flex()
581+ .items_center()
582+ .gap(px(6.))
583+ .child(div().flex_1().min_w_0().child(poll_field(option, palette)))
584+ .children((options.len() > MINIMUM_POLL_OPTIONS).then(|| {
585+ clickable(format!("poll_remove_{index}"), palette, move |_, cx| {
586+ remove.update(cx, |yumush, cx| {
587+ yumush.remove_poll_option(index, cx)
588+ });
589+ })
590+ .size(px(24.))
591+ .flex()
592+ .items_center()
593+ .justify_center()
594+ .rounded(px(6.))
595+ .text_color(palette.muted)
596+ .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.)))
597+ }))
598+ }))
599+ .child(
600+ div()
601+ .flex()
602+ .items_center()
603+ .justify_between()
604+ .child(
605+ Checkbox::new("poll_multiple")
606+ .label("Multiple answers")
607+ .checked(multiple)
608+ .on_click(move |_, _, cx| {
609+ toggle.update(cx, |yumush, cx| {
610+ yumush.chat.poll_multiple = !yumush.chat.poll_multiple;
611+ cx.notify();
612+ })
613+ }),
614+ )
615+ .children((options.len() < MAXIMUM_POLL_OPTIONS).then(|| {
616+ clickable("poll_add", palette, move |window, cx| {
617+ add.update(cx, |yumush, cx| yumush.add_poll_option(window, cx));
618+ })
619+ .size(px(24.))
620+ .flex()
621+ .items_center()
622+ .justify_center()
623+ .rounded(px(6.))
624+ .text_color(palette.muted)
625+ .child(Icon::new(IconName::Plus).w(px(14.)).h(px(14.)))
626+ })),
627+ )
628+ .child(
629+ primary_button("poll_create", palette, move |window, cx| {
630+ if submit.update(cx, |yumush, cx| yumush.send_poll(window, cx)) {
631+ popover.update(cx, |state, cx| state.dismiss(window, cx));
632+ }
633+ })
634+ .h(px(28.))
635+ .flex()
636+ .items_center()
637+ .justify_center()
638+ .rounded(px(6.))
639+ .child("Create"),
640+ ),
641+ Anchor::BottomLeft,
642+ )
643+ })
644+}
645+
646+impl Yumush {
647+ pub(super) fn add_poll_option(&mut self, window: &mut Window, cx: &mut Context<Self>) {
648+ if self.chat.poll_options.len() < MAXIMUM_POLL_OPTIONS {
649+ let input = new_input("Option", window, cx);
650+ self.chat.poll_options.push(input);
651+ cx.notify();
652+ }
653+ }
654+
655+ pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context<Self>) {
656+ if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS {
657+ self.chat.poll_options.remove(index);
658+ cx.notify();
659+ }
660+ }
661+
662+ pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
663+ let Some(community_id) = self.chat.selected_community_id.clone() else {
664+ return false;
665+ };
666+ let question = self.chat.poll_question.read(cx).text().to_string();
667+ let options: Vec<String> = self
668+ .chat
669+ .poll_options
670+ .iter()
671+ .map(|input| input.read(cx).text().to_string())
672+ .collect();
673+ if let Err(error) = validate_poll(&question, &options) {
674+ window.push_notification(Notification::error(error.to_string()), cx);
675+ return false;
676+ }
677+ let multiple = self.chat.poll_multiple;
678+ let network = self.network.clone();
679+
680+ cx.spawn_in(window, async move |this, cx| {
681+ if let Err(error) = network
682+ .create_poll(&community_id, &question, options, multiple)
683+ .await
684+ {
685+ notify_error(&this, cx, error);
686+ }
687+ })
688+ .detach();
689+
690+ self.chat
691+ .poll_question
692+ .update(cx, |state, cx| state.set_value("", window, cx));
693+ self.chat.poll_options.truncate(MINIMUM_POLL_OPTIONS);
694+ for input in &self.chat.poll_options {
695+ input.update(cx, |state, cx| state.set_value("", window, cx));
696+ }
697+ self.chat.poll_multiple = false;
698+ cx.notify();
699+ true
700+ }
701+}
crates/client/src/gui/forward.rsmodified+2 -10
@@ -10,9 +10,7 @@ use gpui_kit::{
10 div, px,10 div, px,
11 };11 };
12 12
13-use super::{13+use super::{Yumush, clickable, community_name, composer::Composer, notify_error, palette};
14- Yumush, clickable, community_icon, community_name, composer::Composer, notify_error, palette,
15-};
16 14
17 pub struct Forward {15 pub struct Forward {
18 yumush: Entity<Yumush>,16 yumush: Entity<Yumush>,
@@ -82,13 +80,7 @@ impl Render for Forward {
82 .items_center()80 .items_center()
83 .gap(px(8.))81 .gap(px(8.))
84 .rounded(px(6.))82 .rounded(px(6.))
85- .child(community_icon(83+ .child(yumush.community_badge(community, px(16.), text(9.), palette))
86- palette,
87- community,
88- px(16.),
89- text(9.),
90- &yumush.chat.avatars,
91- ))
92 .child(84 .child(
93 div()85 div()
94 .flex_1()86 .flex_1()
crates/client/src/gui/media_view.rsmodified+104 -14
@@ -22,10 +22,13 @@ use gpui_kit::{
22 px,22 px,
23 };23 };
24 24
25-use super::{Palette, Tooltip as _, Yumush, clickable, notify_error, storage};25+use super::{
26+ Palette, Tooltip as _, Yumush, clickable, notify_error, storage,
27+ voice_note::{VoiceNote, bars},
28+};
26 use crate::{29 use crate::{
27 embed::{self, Embed, EmbedKind},30 embed::{self, Embed, EmbedKind},
28- media::Player,31+ media::{Player, voice_note as note},
29 };32 };
30 33
31 const FRAME_TICK: Duration = Duration::from_millis(16);34 const FRAME_TICK: Duration = Duration::from_millis(16);
@@ -58,8 +61,10 @@ pub struct Playing {
58 #[derive(Default)]61 #[derive(Default)]
59 pub struct Media {62 pub struct Media {
60 pub pending: Vec<Attachment>,63 pub pending: Vec<Attachment>,
61- uploading: usize,64+ pub(super) uploading: usize,
65+ pub(super) voice_note: VoiceNote,
62 thumbnails: HashMap<String, Arc<Image>>,66 thumbnails: HashMap<String, Arc<Image>>,
67+ waveforms: HashMap<String, note::Waveform>,
63 embeds: HashMap<String, LoadedEmbed>,68 embeds: HashMap<String, LoadedEmbed>,
64 requested: HashSet<String>,69 requested: HashSet<String>,
65 playing: Option<Playing>,70 playing: Option<Playing>,
@@ -73,6 +78,7 @@ impl Media {
73 pub fn leave(&mut self) {78 pub fn leave(&mut self) {
74 self.pending.clear();79 self.pending.clear();
75 self.playing = None;80 self.playing = None;
81+ self.voice_note = VoiceNote::Idle;
76 }82 }
77 }83 }
78 84
@@ -124,7 +130,7 @@ fn cache_path(attachment: &Attachment) -> Option<PathBuf> {
124 Some(directory.join(format!("{}{extension}", attachment.id)))130 Some(directory.join(format!("{}{extension}", attachment.id)))
125 }131 }
126 132
127-fn time_text(time: Duration) -> String {133+pub fn time_text(time: Duration) -> String {
128 let seconds = time.as_secs();134 let seconds = time.as_secs();
129 format!("{}:{:02}", seconds / 60, seconds % 60)135 format!("{}:{:02}", seconds / 60, seconds % 60)
130 }136 }
@@ -139,6 +145,7 @@ impl Yumush {
139 let mut thumbnails = Vec::new();145 let mut thumbnails = Vec::new();
140 let mut links = Vec::new();146 let mut links = Vec::new();
141 let mut avatars = Vec::new();147 let mut avatars = Vec::new();
148+ let mut voices = Vec::new();
142 for message in &self.chat.messages {149 for message in &self.chat.messages {
143 let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages);150 let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages);
144 for item in forwarded.clone() {151 for item in forwarded.clone() {
@@ -156,6 +163,11 @@ impl Yumush {
156 {163 {
157 thumbnails.push(attachment.id.clone());164 thumbnails.push(attachment.id.clone());
158 }165 }
166+ if note::is_voice_note(attachment)
167+ && self.chat.media.requested.insert(attachment.id.clone())
168+ {
169+ voices.push(attachment.clone());
170+ }
159 }171 }
160 for url in embed::urls(&message.body) {172 for url in embed::urls(&message.body) {
161 if self.chat.media.requested.insert(url.clone()) {173 if self.chat.media.requested.insert(url.clone()) {
@@ -184,6 +196,28 @@ impl Yumush {
184 .detach();196 .detach();
185 }197 }
186 198
199+ for attachment in voices {
200+ let fetched = self.fetch_file(&attachment, cx);
201+ let attachment_id = attachment.id.clone();
202+ cx.spawn(async move |this, cx| {
203+ let Ok(path) = fetched.await else {
204+ return;
205+ };
206+ let Some(waveform) = cx
207+ .background_executor()
208+ .spawn(async move { note::waveform(&path) })
209+ .await
210+ else {
211+ return;
212+ };
213+ let _ = this.update(cx, |yumush, cx| {
214+ yumush.chat.media.waveforms.insert(attachment_id, waveform);
215+ cx.notify();
216+ });
217+ })
218+ .detach();
219+ }
220+
187 for url in links {221 for url in links {
188 cx.spawn(async move |this, cx| {222 cx.spawn(async move |this, cx| {
189 let fetched = cx223 let fetched = cx
@@ -394,14 +428,7 @@ impl Yumush {
394 let SliderEvent::Release(value) = event else {428 let SliderEvent::Release(value) = event else {
395 return;429 return;
396 };430 };
397- if let Some(Playing {431+ yumush.seek_playing(value.start(), cx);
398- state: PlayState::Ready { player, .. },
399- ..
400- }) = &yumush.chat.media.playing
401- {
402- player.seek(Duration::from_secs_f32(value.start().max(0.)));
403- }
404- cx.notify();
405 });432 });
406 let tick = cx.spawn_in(window, async move |this, cx| {433 let tick = cx.spawn_in(window, async move |this, cx| {
407 loop {434 loop {
@@ -459,6 +486,17 @@ impl Yumush {
459 cx.notify();486 cx.notify();
460 }487 }
461 488
489+ fn seek_playing(&mut self, seconds: f32, cx: &mut Context<Self>) {
490+ if let Some(Playing {
491+ state: PlayState::Ready { player, .. },
492+ ..
493+ }) = &self.chat.media.playing
494+ {
495+ player.seek(Duration::from_secs_f32(seconds.max(0.)));
496+ }
497+ cx.notify();
498+ }
499+
462 pub(super) fn stop_playing(&mut self, cx: &mut Context<Self>) {500 pub(super) fn stop_playing(&mut self, cx: &mut Context<Self>) {
463 if let Some(Playing {501 if let Some(Playing {
464 state: PlayState::Ready {502 state: PlayState::Ready {
@@ -646,6 +684,7 @@ fn player_view(
646 yumush.play(attachment, window, cx)684 yumush.play(attachment, window, cx)
647 }),685 }),
648 );686 );
687+ let voice = note::is_voice_note(attachment);
649 let detail = match state {688 let detail = match state {
650 Some(PlayState::Loading) => "…".to_string(),689 Some(PlayState::Loading) => "…".to_string(),
651 Some(PlayState::Ready { player, .. }) => format!(690 Some(PlayState::Ready { player, .. }) => format!(
@@ -653,14 +692,29 @@ fn player_view(
653 time_text(player.position()),692 time_text(player.position()),
654 time_text(player.info().duration.unwrap_or_default())693 time_text(player.info().duration.unwrap_or_default())
655 ),694 ),
695+ None if voice => media
696+ .waveforms
697+ .get(&attachment.id)
698+ .map_or("…".to_string(), |waveform| time_text(waveform.duration)),
656 None => storage(attachment.size),699 None => storage(attachment.size),
657 };700 };
658 let controls = card(palette)701 let controls = card(palette)
659 .child(toggle)702 .child(toggle)
660- .child(name_block(attachment, detail, palette))703+ .when(voice, |this| {
704+ this.child(waveform_view(attachment, media, entity, state, palette))
705+ .child(
706+ div()
707+ .text_size(text(12.))
708+ .text_color(palette.muted)
709+ .child(detail.clone()),
710+ )
711+ })
712+ .when(!voice, |this| {
713+ this.child(name_block(attachment, detail, palette))
714+ })
661 .when_some(715 .when_some(
662 match state {716 match state {
663- Some(PlayState::Ready { seek, .. }) => Some(seek),717+ Some(PlayState::Ready { seek, .. }) if !voice => Some(seek),
664 _ => None,718 _ => None,
665 },719 },
666 |this, seek| this.child(div().w(px(140.)).child(Slider::new(seek))),720 |this, seek| this.child(div().w(px(140.)).child(Slider::new(seek))),
@@ -693,6 +747,42 @@ fn player_view(
693 .child(controls)747 .child(controls)
694 }748 }
695 749
750+fn waveform_view(
751+ attachment: &Attachment,
752+ media: &Media,
753+ entity: &Entity<Yumush>,
754+ state: Option<&PlayState>,
755+ palette: Palette,
756+) -> impl IntoElement {
757+ let levels = media
758+ .waveforms
759+ .get(&attachment.id)
760+ .map_or(&[][..], |waveform| waveform.peaks.as_slice());
761+ match state {
762+ Some(PlayState::Ready { player, .. }) => {
763+ let duration = player
764+ .info()
765+ .duration
766+ .unwrap_or_default()
767+ .as_secs_f32()
768+ .max(0.1);
769+ let progress = player.position().as_secs_f32() / duration;
770+ let entity = entity.clone();
771+ bars(levels, progress, palette, move |index, _, cx| {
772+ entity.update(cx, |yumush, cx| {
773+ yumush.seek_playing(index as f32 / note::BARS as f32 * duration, cx)
774+ })
775+ })
776+ }
777+ _ => {
778+ let play = on_attachment(entity, attachment, |yumush, attachment, window, cx| {
779+ yumush.play(attachment, window, cx)
780+ });
781+ bars(levels, 0., palette, move |_, window, cx| play(window, cx))
782+ }
783+ }
784+}
785+
696 pub fn embeds(message: &Message, media: &Media, palette: Palette) -> Vec<impl IntoElement> {786 pub fn embeds(message: &Message, media: &Media, palette: Palette) -> Vec<impl IntoElement> {
697 embed::urls(&message.body)787 embed::urls(&message.body)
698 .into_iter()788 .into_iter()
crates/client/src/gui/message_actions.rsmodified+385 -11
@@ -1,20 +1,150 @@
1 use super::text;1 use super::text;
2-use common::model::{Message, User};2+use common::{
3+ constant::REACTIONS,
4+ model::{Message, User},
5+};
3 use gpui_kit::{6 use gpui_kit::{
4- Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window,7+ Anchor, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement,
8+ Stateful, Styled, Window,
5 assets::IconName,9 assets::IconName,
6- component::{Icon, input::InputState},10+ component::{Icon, input::InputState, popover::Popover},
7- div, px,11+ div,
12+ prelude::FluentBuilder as _,
13+ px,
8 };14 };
9 15
10 use super::{16 use super::{
11- Palette, Tooltip as _, Yumush,17+ CLOCK, Palette, Tooltip as _, Trigger, Yumush,
12 auth::field,18 auth::field,
13 avatar,19 avatar,
14 chat::{Chat, ReportTarget},20 chat::{Chat, ReportTarget},
15- clickable, entity_action, notify_error, primary_button,21+ clickable, entity_action, hoverable, id_time, notify_error, pop_in, primary_button, sidebar,
16 };22 };
17 23
24+pub fn reactions(
25+ message: &Message,
26+ me: Option<&User>,
27+ entity: &Entity<Yumush>,
28+ palette: Palette,
29+) -> impl IntoElement {
30+ let me_id = me.map(|me| me.id.clone());
31+
32+ div()
33+ .flex()
34+ .flex_wrap()
35+ .gap(px(4.))
36+ .children(message.reactions.iter().map(|reaction| {
37+ let mine = me_id
38+ .as_ref()
39+ .is_some_and(|id| reaction.user_ids.contains(id));
40+ let entity = entity.clone();
41+ let message_id = message.id.clone();
42+ let emoji = reaction.emoji.clone();
43+ let chip_emoji = reaction.emoji.clone();
44+ let count = reaction.user_ids.len();
45+
46+ clickable(
47+ format!("reaction_{}_{}", message.id, reaction.emoji),
48+ palette,
49+ move |window, cx| {
50+ let message_id = message_id.clone();
51+ let emoji = emoji.clone();
52+ entity.update(cx, |yumush, cx| {
53+ yumush.toggle_reaction(message_id, emoji, window, cx)
54+ });
55+ },
56+ )
57+ .flex()
58+ .items_center()
59+ .gap(px(4.))
60+ .h(px(22.))
61+ .px(px(6.))
62+ .rounded_full()
63+ .border_1()
64+ .border_color(if mine { palette.accent } else { palette.border })
65+ .bg(if mine {
66+ palette.accent.opacity(0.15)
67+ } else {
68+ palette.panel
69+ })
70+ .text_size(text(12.))
71+ .child(chip_emoji)
72+ .child(div().text_color(palette.muted).child(count.to_string()))
73+ }))
74+}
75+
76+pub fn react_popover(
77+ message: &Message,
78+ entity: &Entity<Yumush>,
79+ palette: Palette,
80+) -> impl IntoElement {
81+ let message_id = message.id.clone();
82+ let entity = entity.clone();
83+
84+ Popover::new(format!("react_{}", message.id))
85+ .anchor(Anchor::TopRight)
86+ .appearance(false)
87+ .trigger(Trigger::new(hoverable(
88+ format!("react_trigger_{}", message.id),
89+ div()
90+ .size(px(24.))
91+ .flex()
92+ .items_center()
93+ .justify_center()
94+ .rounded(px(6.))
95+ .text_color(palette.muted)
96+ .child(
97+ Icon::new(IconName::FaceSlightlySmiling)
98+ .w(px(14.))
99+ .h(px(14.)),
100+ ),
101+ palette,
102+ )))
103+ .content(move |_, _, cx| {
104+ let popover = cx.entity();
105+ pop_in(
106+ "react_list",
107+ div()
108+ .flex()
109+ .gap(px(2.))
110+ .p(px(4.))
111+ .rounded(px(8.))
112+ .border_1()
113+ .border_color(palette.border)
114+ .bg(palette.panel)
115+ .children(REACTIONS.map(|emoji| {
116+ let entity = entity.clone();
117+ let message_id = message_id.clone();
118+ let popover = popover.clone();
119+ clickable(
120+ format!("react_{emoji}_{message_id}"),
121+ palette,
122+ move |window, cx| {
123+ popover.update(cx, |state, cx| state.dismiss(window, cx));
124+ let message_id = message_id.clone();
125+ entity.update(cx, |yumush, cx| {
126+ yumush.toggle_reaction(
127+ message_id,
128+ emoji.to_string(),
129+ window,
130+ cx,
131+ )
132+ });
133+ },
134+ )
135+ .size(px(28.))
136+ .flex()
137+ .items_center()
138+ .justify_center()
139+ .rounded(px(6.))
140+ .text_size(text(16.))
141+ .child(emoji)
142+ })),
143+ Anchor::TopRight,
144+ )
145+ })
146+}
147+
18 pub fn quote_text(body: &str, attachments: usize) -> String {148 pub fn quote_text(body: &str, attachments: usize) -> String {
19 if body.is_empty() {149 if body.is_empty() {
20 format!("{attachments} attachments")150 format!("{attachments} attachments")
@@ -57,7 +187,6 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<im
57 187
58 pub fn selection_mark(selected: bool, palette: Palette) -> impl IntoElement {188 pub fn selection_mark(selected: bool, palette: Palette) -> impl IntoElement {
59 div()189 div()
60- .mt(px(3.))
61 .size(px(16.))190 .size(px(16.))
62 .flex_shrink_0()191 .flex_shrink_0()
63 .flex()192 .flex()
@@ -83,6 +212,192 @@ pub fn selection_mark(selected: bool, palette: Palette) -> impl IntoElement {
83 }))212 }))
84 }213 }
85 214
215+pub fn pin_mark(palette: Palette) -> impl IntoElement {
216+ div()
217+ .flex_shrink_0()
218+ .text_color(palette.muted)
219+ .child(Icon::new(IconName::Pin).w(px(12.)).h(px(12.)))
220+}
221+
222+pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
223+ let entity = entity.clone();
224+ let input = chat.community_search.clone();
225+ let hits: Vec<(String, String, String, String)> = chat
226+ .community_hits
227+ .iter()
228+ .map(|hit| {
229+ let name = hit
230+ .author
231+ .as_ref()
232+ .map(|user| user.username.clone())
233+ .unwrap_or_default();
234+ (
235+ hit.message.id.clone(),
236+ name,
237+ id_time(&hit.message.id, CLOCK),
238+ quote_text(&hit.message.body, hit.message.attachments.len()),
239+ )
240+ })
241+ .collect();
242+
243+ Popover::new("search_popover")
244+ .anchor(Anchor::TopRight)
245+ .appearance(false)
246+ .trigger(Trigger::new(hoverable(
247+ "search_trigger",
248+ div()
249+ .size(px(24.))
250+ .flex()
251+ .items_center()
252+ .justify_center()
253+ .rounded(px(6.))
254+ .text_color(palette.muted)
255+ .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))),
256+ palette,
257+ )))
258+ .content(move |_, _, cx| {
259+ let popover = cx.entity();
260+ pop_in(
261+ "search_list",
262+ div()
263+ .w(px(320.))
264+ .p(px(4.))
265+ .flex()
266+ .flex_col()
267+ .gap(px(4.))
268+ .rounded(px(8.))
269+ .border_1()
270+ .border_color(palette.border)
271+ .bg(palette.panel)
272+ .child(sidebar::input_box(&input, palette))
273+ .children(hits.iter().map(|(message_id, name, time, body)| {
274+ let entity = entity.clone();
275+ let popover = popover.clone();
276+ let message_id = message_id.clone();
277+ clickable(
278+ format!("search_hit_{message_id}"),
279+ palette,
280+ move |window, cx| {
281+ popover.update(cx, |state, cx| state.dismiss(window, cx));
282+ let message_id = message_id.clone();
283+ entity.update(cx, |yumush, cx| {
284+ yumush.go_to_message(message_id, window, cx)
285+ });
286+ },
287+ )
288+ .flex()
289+ .gap(px(6.))
290+ .px(px(8.))
291+ .py(px(4.))
292+ .rounded(px(6.))
293+ .text_size(text(12.))
294+ .child(
295+ div()
296+ .flex_shrink_0()
297+ .font_weight(FontWeight::SEMIBOLD)
298+ .child(name.clone()),
299+ )
300+ .child(
301+ div()
302+ .flex_shrink_0()
303+ .text_color(palette.muted)
304+ .child(time.clone()),
305+ )
306+ .child(div().flex_1().min_w_0().truncate().child(body.clone()))
307+ })),
308+ Anchor::TopRight,
309+ )
310+ })
311+}
312+
313+pub fn pins_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
314+ let entity = entity.clone();
315+ let pins: Vec<(String, String, String)> = chat
316+ .pins
317+ .iter()
318+ .map(|pin| {
319+ let name = chat
320+ .author(&pin.user_id)
321+ .map(|user| user.username.clone())
322+ .unwrap_or_default();
323+ (
324+ pin.id.clone(),
325+ name,
326+ quote_text(&pin.body, pin.attachments.len()),
327+ )
328+ })
329+ .collect();
330+
331+ Popover::new("pins_popover")
332+ .anchor(Anchor::TopRight)
333+ .appearance(false)
334+ .trigger(Trigger::new(hoverable(
335+ "pins_trigger",
336+ div()
337+ .size(px(24.))
338+ .flex()
339+ .items_center()
340+ .justify_center()
341+ .rounded(px(6.))
342+ .text_color(palette.muted)
343+ .child(Icon::new(IconName::Pin).w(px(14.)).h(px(14.))),
344+ palette,
345+ )))
346+ .content(move |_, _, cx| {
347+ let popover = cx.entity();
348+ pop_in(
349+ "pins_list",
350+ div()
351+ .w(px(260.))
352+ .p(px(4.))
353+ .flex()
354+ .flex_col()
355+ .gap(px(2.))
356+ .rounded(px(8.))
357+ .border_1()
358+ .border_color(palette.border)
359+ .bg(palette.panel)
360+ .children(pins.iter().map(|(message_id, name, body)| {
361+ let entity = entity.clone();
362+ let popover = popover.clone();
363+ let message_id = message_id.clone();
364+ clickable(
365+ format!("pin_hit_{message_id}"),
366+ palette,
367+ move |window, cx| {
368+ popover.update(cx, |state, cx| state.dismiss(window, cx));
369+ let message_id = message_id.clone();
370+ entity.update(cx, |yumush, cx| {
371+ yumush.go_to_message(message_id, window, cx)
372+ });
373+ },
374+ )
375+ .flex()
376+ .gap(px(6.))
377+ .px(px(8.))
378+ .py(px(4.))
379+ .rounded(px(6.))
380+ .text_size(text(12.))
381+ .child(
382+ div()
383+ .flex_shrink_0()
384+ .font_weight(FontWeight::SEMIBOLD)
385+ .child(name.clone()),
386+ )
387+ .child(
388+ div()
389+ .flex_1()
390+ .min_w_0()
391+ .truncate()
392+ .text_color(palette.muted)
393+ .child(body.clone()),
394+ )
395+ })),
396+ Anchor::TopRight,
397+ )
398+ })
399+}
400+
86 pub fn actions(401 pub fn actions(
87 message: &Message,402 message: &Message,
88 chat: &Chat,403 chat: &Chat,
@@ -94,8 +409,10 @@ pub fn actions(
94 let mine = me.is_some_and(|me| me.id == message.user_id);409 let mine = me.is_some_and(|me| me.id == message.user_id);
95 let editable = mine && !message.body.is_empty() && message.snippet.is_none();410 let editable = mine && !message.body.is_empty() && message.snippet.is_none();
96 let deletable = me.is_some_and(|me| chat.can_delete(message, me));411 let deletable = me.is_some_and(|me| chat.can_delete(message, me));
412+ let pinnable = me.is_some_and(|me| chat.can_pin(me));
97 let reportable = me.is_some_and(|me| me.id != message.user_id);413 let reportable = me.is_some_and(|me| me.id != message.user_id);
98 let id = message.id.as_str();414 let id = message.id.as_str();
415+ let armed = chat.pending_message_delete.as_deref() == Some(id);
99 416
100 div()417 div()
101 .flex()418 .flex()
@@ -106,7 +423,7 @@ pub fn actions(
106 .border_1()423 .border_1()
107 .border_color(palette.border)424 .border_color(palette.border)
108 .bg(palette.panel)425 .bg(palette.panel)
109- .invisible()426+ .when(!armed, |this| this.invisible())
110 .group_hover(group, |style| style.visible())427 .group_hover(group, |style| style.visible())
111 .child(action(428 .child(action(
112 entity,429 entity,
@@ -116,6 +433,7 @@ pub fn actions(
116 IconName::Reply,433 IconName::Reply,
117 |yumush, id, window, cx| yumush.reply(id, window, cx),434 |yumush, id, window, cx| yumush.reply(id, window, cx),
118 ))435 ))
436+ .child(react_popover(message, entity, palette))
119 .children(editable.then(|| {437 .children(editable.then(|| {
120 action(438 action(
121 entity,439 entity,
@@ -142,6 +460,20 @@ pub fn actions(
142 IconName::ListChecks,460 IconName::ListChecks,
143 |yumush, id, window, cx| yumush.start_select(id, window, cx),461 |yumush, id, window, cx| yumush.start_select(id, window, cx),
144 ))462 ))
463+ .children(pinnable.then(|| {
464+ action(
465+ entity,
466+ palette,
467+ id,
468+ if message.pinned { "Unpin" } else { "Pin" },
469+ if message.pinned {
470+ IconName::PinOff
471+ } else {
472+ IconName::Pin
473+ },
474+ |yumush, id, window, cx| yumush.toggle_pin(id, window, cx),
475+ )
476+ }))
145 .children(reportable.then(|| {477 .children(reportable.then(|| {
146 action(478 action(
147 entity,479 entity,
@@ -157,10 +489,14 @@ pub fn actions(
157 entity,489 entity,
158 palette,490 palette,
159 id,491 id,
160- "Delete",492+ if armed { "Confirm" } else { "Delete" },
161 IconName::Trash,493 IconName::Trash,
162- |yumush, id, window, cx| yumush.delete_message(&id, window, cx),494+ |yumush, id, window, cx| yumush.request_message_delete(id, window, cx),
163 )495 )
496+ .when(armed, |this| {
497+ this.text_color(palette.danger)
498+ .bg(palette.danger.opacity(0.15))
499+ })
164 }))500 }))
165 }501 }
166 502
@@ -190,6 +526,44 @@ pub fn report_bar(
190 }526 }
191 527
192 impl Yumush {528 impl Yumush {
529+ pub(super) fn toggle_pin(
530+ &mut self,
531+ message_id: String,
532+ window: &mut Window,
533+ cx: &mut Context<Self>,
534+ ) {
535+ let pinned = self
536+ .chat
537+ .messages
538+ .iter()
539+ .any(|message| message.id == message_id && message.pinned);
540+ let network = self.network.clone();
541+
542+ cx.spawn_in(window, async move |this, cx| {
543+ if let Err(error) = network.pin(&message_id, !pinned).await {
544+ notify_error(&this, cx, error);
545+ }
546+ })
547+ .detach();
548+ }
549+
550+ pub(super) fn toggle_reaction(
551+ &mut self,
552+ message_id: String,
553+ emoji: String,
554+ window: &mut Window,
555+ cx: &mut Context<Self>,
556+ ) {
557+ let network = self.network.clone();
558+
559+ cx.spawn_in(window, async move |this, cx| {
560+ if let Err(error) = network.react(&message_id, &emoji).await {
561+ notify_error(&this, cx, error);
562+ }
563+ })
564+ .detach();
565+ }
566+
193 pub(super) fn start_report(567 pub(super) fn start_report(
194 &mut self,568 &mut self,
195 target: ReportTarget,569 target: ReportTarget,
@@ -247,7 +621,7 @@ fn action(
247 tip: &'static str,621 tip: &'static str,
248 icon: IconName,622 icon: IconName,
249 run: fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>),623 run: fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>),
250-) -> impl IntoElement {624+) -> Stateful<Div> {
251 let entity = entity.clone();625 let entity = entity.clone();
252 let message_id = message_id.to_string();626 let message_id = message_id.to_string();
253 627
crates/client/src/gui/poll.rsadded+330 -0
@@ -0,0 +1,330 @@
1+use std::collections::HashSet;
2+
3+use common::model::{Message, Poll, Rank, User};
4+use gpui_kit::{
5+ Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled,
6+ Window, assets::IconName, component::Icon, div, px, relative,
7+};
8+
9+use super::{Palette, Yumush, chat::Chat, clickable, notify_error, text};
10+
11+pub fn voter_count(poll: &Poll) -> usize {
12+ poll.options
13+ .iter()
14+ .flat_map(|option| &option.voter_ids)
15+ .collect::<HashSet<_>>()
16+ .len()
17+}
18+
19+fn my_positions(poll: &Poll, user_id: &str) -> Vec<u32> {
20+ poll.options
21+ .iter()
22+ .enumerate()
23+ .filter(|(_, option)| option.voter_ids.iter().any(|id| id == user_id))
24+ .map(|(position, _)| position as u32)
25+ .collect()
26+}
27+
28+fn next_votes(poll: &Poll, user_id: &str, position: u32) -> Vec<u32> {
29+ let mut mine = my_positions(poll, user_id);
30+ if mine.contains(&position) {
31+ mine.retain(|mine| *mine != position);
32+ mine
33+ } else if poll.multiple {
34+ mine.push(position);
35+ mine
36+ } else {
37+ vec![position]
38+ }
39+}
40+
41+fn percent(count: usize, voters: usize) -> usize {
42+ count * 100 / voters.max(1)
43+}
44+
45+pub enum PollMode<'a> {
46+ Live(&'a Message),
47+ Snapshot(&'a str),
48+}
49+
50+pub fn poll_card(
51+ poll: &Poll,
52+ mode: PollMode,
53+ me: Option<&User>,
54+ chat: &Chat,
55+ entity: &Entity<Yumush>,
56+ palette: Palette,
57+) -> impl IntoElement {
58+ let voters = voter_count(poll);
59+ let me_id = me.map(|me| me.id.as_str());
60+ let mine = me_id.map(|id| my_positions(poll, id)).unwrap_or_default();
61+ let (key, live) = match mode {
62+ PollMode::Live(message) => (message.id.clone(), Some(message)),
63+ PollMode::Snapshot(id) => (format!("snapshot_{id}"), None),
64+ };
65+ let vote_id = live
66+ .filter(|_| !poll.closed && me_id.is_some())
67+ .map(|message| message.id.clone());
68+ let close_id = live
69+ .filter(|message| {
70+ !poll.closed
71+ && me.is_some_and(|me| {
72+ me.id == message.user_id || chat.my_rank(me) >= Some(Rank::Moderator)
73+ })
74+ })
75+ .map(|message| message.id.clone());
76+
77+ let rows = poll.options.iter().enumerate().map(|(position, option)| {
78+ let count = option.voter_ids.len();
79+ let share = percent(count, voters);
80+ let picked = mine.contains(&(position as u32));
81+ let next = me_id
82+ .map(|id| next_votes(poll, id, position as u32))
83+ .unwrap_or_default();
84+ let entity = entity.clone();
85+ let id = format!("poll_option_{key}_{position}");
86+ match vote_id.clone() {
87+ Some(message_id) => clickable(id, palette, move |window, cx| {
88+ let next = next.clone();
89+ let message_id = message_id.clone();
90+ entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx));
91+ }),
92+ None => div().id(id),
93+ }
94+ .relative()
95+ .h(px(30.))
96+ .px(px(10.))
97+ .flex()
98+ .items_center()
99+ .justify_between()
100+ .gap(px(8.))
101+ .rounded(px(6.))
102+ .overflow_hidden()
103+ .border_1()
104+ .border_color(if picked {
105+ palette.accent
106+ } else {
107+ palette.border
108+ })
109+ .child(
110+ div()
111+ .absolute()
112+ .left_0()
113+ .top_0()
114+ .h_full()
115+ .w(relative(share as f32 / 100.))
116+ .bg(palette.accent.opacity(0.18)),
117+ )
118+ .child(
119+ div()
120+ .flex()
121+ .items_center()
122+ .gap(px(6.))
123+ .min_w_0()
124+ .children(picked.then(|| {
125+ div()
126+ .flex_shrink_0()
127+ .text_color(palette.accent)
128+ .child(Icon::new(IconName::Check).w(px(12.)).h(px(12.)))
129+ }))
130+ .child(div().min_w_0().truncate().child(option.text.clone())),
131+ )
132+ .child(
133+ div()
134+ .flex_shrink_0()
135+ .text_size(text(12.))
136+ .text_color(palette.muted)
137+ .child(format!("{count} · {share}%")),
138+ )
139+ });
140+
141+ let footer = div()
142+ .flex()
143+ .items_center()
144+ .justify_between()
145+ .text_size(text(12.))
146+ .text_color(palette.muted)
147+ .child(match voters {
148+ 1 => "1 voter".to_string(),
149+ _ => format!("{voters} voters"),
150+ })
151+ .child(
152+ div()
153+ .flex()
154+ .items_center()
155+ .gap(px(8.))
156+ .children(poll.closed.then(|| "Closed"))
157+ .children(close_id.map(|close_id| {
158+ let close_entity = entity.clone();
159+ clickable(
160+ format!("poll_close_{close_id}"),
161+ palette,
162+ move |window, cx| {
163+ let close_id = close_id.clone();
164+ close_entity
165+ .update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx));
166+ },
167+ )
168+ .px(px(6.))
169+ .py(px(2.))
170+ .rounded(px(6.))
171+ .border_1()
172+ .border_color(palette.border)
173+ .child("Close")
174+ })),
175+ );
176+
177+ div()
178+ .flex()
179+ .flex_col()
180+ .gap(px(6.))
181+ .p(px(10.))
182+ .max_w(px(420.))
183+ .rounded(px(8.))
184+ .border_1()
185+ .border_color(palette.border)
186+ .bg(palette.panel)
187+ .child(
188+ div()
189+ .font_weight(FontWeight::SEMIBOLD)
190+ .child(poll.question.clone()),
191+ )
192+ .children(rows)
193+ .child(footer)
194+}
195+
196+impl Yumush {
197+ pub(super) fn poll_banner(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
198+ let (message, poll) = self.chat.pins.iter().find_map(|pin| {
199+ pin.poll
200+ .as_ref()
201+ .filter(|poll| !poll.closed)
202+ .map(|poll| (pin, poll))
203+ })?;
204+ let me = self.user.as_ref();
205+ let expanded = self.chat.poll_expanded;
206+ let toggle = entity.clone();
207+ let jump = entity.clone();
208+ let message_id = message.id.clone();
209+
210+ Some(
211+ div()
212+ .flex()
213+ .flex_col()
214+ .gap(px(6.))
215+ .px(px(16.))
216+ .py(px(8.))
217+ .border_b_1()
218+ .border_color(palette.border)
219+ .bg(palette.panel)
220+ .child(
221+ div()
222+ .flex()
223+ .items_center()
224+ .gap(px(8.))
225+ .child(
226+ clickable("poll_banner_toggle", palette, move |_, cx| {
227+ toggle.update(cx, |yumush, cx| {
228+ yumush.chat.poll_expanded = !yumush.chat.poll_expanded;
229+ cx.notify();
230+ })
231+ })
232+ .flex()
233+ .flex_1()
234+ .min_w_0()
235+ .items_center()
236+ .gap(px(8.))
237+ .text_size(text(12.))
238+ .child(
239+ div()
240+ .flex_shrink_0()
241+ .text_color(palette.muted)
242+ .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))),
243+ )
244+ .child(
245+ div()
246+ .min_w_0()
247+ .truncate()
248+ .font_weight(FontWeight::SEMIBOLD)
249+ .child(poll.question.clone()),
250+ )
251+ .child(
252+ div()
253+ .flex_shrink_0()
254+ .text_color(palette.muted)
255+ .child(format!("{} votes", voter_count(poll))),
256+ )
257+ .child(
258+ div().flex_shrink_0().text_color(palette.muted).child(
259+ Icon::new(if expanded {
260+ IconName::ChevronUp
261+ } else {
262+ IconName::ChevronDown
263+ })
264+ .w(px(14.))
265+ .h(px(14.)),
266+ ),
267+ ),
268+ )
269+ .child(
270+ clickable("poll_banner_jump", palette, move |window, cx| {
271+ let message_id = message_id.clone();
272+ jump.update(cx, |yumush, cx| {
273+ yumush.go_to_message(message_id, window, cx)
274+ });
275+ })
276+ .size(px(24.))
277+ .flex()
278+ .items_center()
279+ .justify_center()
280+ .rounded(px(6.))
281+ .text_color(palette.muted)
282+ .child(Icon::new(IconName::ArrowUpRight).w(px(14.)).h(px(14.))),
283+ ),
284+ )
285+ .children(expanded.then(|| {
286+ poll_card(
287+ poll,
288+ PollMode::Live(message),
289+ me,
290+ &self.chat,
291+ entity,
292+ palette,
293+ )
294+ })),
295+ )
296+ }
297+
298+ pub(super) fn vote(
299+ &mut self,
300+ message_id: String,
301+ positions: Vec<u32>,
302+ window: &mut Window,
303+ cx: &mut Context<Self>,
304+ ) {
305+ let network = self.network.clone();
306+
307+ cx.spawn_in(window, async move |this, cx| {
308+ if let Err(error) = network.vote(&message_id, positions).await {
309+ notify_error(&this, cx, error);
310+ }
311+ })
312+ .detach();
313+ }
314+
315+ pub(super) fn close_poll(
316+ &mut self,
317+ message_id: String,
318+ window: &mut Window,
319+ cx: &mut Context<Self>,
320+ ) {
321+ let network = self.network.clone();
322+
323+ cx.spawn_in(window, async move |this, cx| {
324+ if let Err(error) = network.close_poll(&message_id).await {
325+ notify_error(&this, cx, error);
326+ }
327+ })
328+ .detach();
329+ }
330+}
crates/client/src/gui/profile.rsmodified+233 -37
@@ -3,12 +3,13 @@ use crate::gui::DAY_YEAR;
3 use std::{collections::HashMap, sync::Arc};3 use std::{collections::HashMap, sync::Arc};
4 4
5 use common::{5 use common::{
6- model::{Rank, User},6+ model::{Presence, Rank, User},
7 permission,7 permission,
8 };8 };
9 use gpui_kit::{9 use gpui_kit::{
10- Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, IntoElement,10+ Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, Hsla, Image,
11- ParentElement, SharedString, Styled, Window,11+ InteractiveElement, IntoElement, ParentElement, SharedString, Stateful,
12+ StatefulInteractiveElement, StyleRefinement, Styled, Window,
12 assets::IconName,13 assets::IconName,
13 component::{14 component::{
14 Icon, WindowExt,15 Icon, WindowExt,
@@ -18,12 +19,12 @@ use gpui_kit::{
18 div, px,19 div, px,
19 };20 };
20 21
21-use super::chat::{ReportTarget, View};22+use super::chat::{CardMenu, ReportTarget, View};
22 use super::message_actions::report_bar;23 use super::message_actions::report_bar;
23 use super::social::Relation;24 use super::social::Relation;
24 use super::{25 use super::{
25 Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, palette,26 Palette, Trigger, Yumush, avatar, clickable, entity_action, id_time, input_dialog, palette,
26- rank_tag,27+ pop_in, presence_color, rank_tag, swap_in,
27 };28 };
28 29
29 #[derive(Debug, Clone, Copy, PartialEq, Eq)]30 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -41,6 +42,26 @@ impl Removal {
41 }42 }
42 }43 }
43 44
45+pub(super) fn user_link(
46+ id: impl Into<ElementId>,
47+ user: Option<&User>,
48+ entity: &Entity<Yumush>,
49+ trigger: impl IntoElement,
50+) -> AnyElement {
51+ match user {
52+ Some(user) => profile_popover(
53+ id,
54+ Anchor::TopLeft,
55+ user,
56+ entity,
57+ div().min_w_0().cursor_pointer().child(trigger),
58+ )
59+ .trigger_style(StyleRefinement::default().min_w_0())
60+ .into_any_element(),
61+ None => trigger.into_any_element(),
62+ }
63+}
64+
44 pub(super) fn profile_popover(65 pub(super) fn profile_popover(
45 id: impl Into<ElementId>,66 id: impl Into<ElementId>,
46 anchor: Anchor,67 anchor: Anchor,
@@ -55,7 +76,12 @@ pub(super) fn profile_popover(
55 Popover::new(id)76 Popover::new(id)
56 .anchor(anchor)77 .anchor(anchor)
57 .appearance(false)78 .appearance(false)
58- .on_open_change(move |_, _, cx| notify_entity.update(cx, |_, cx| cx.notify()))79+ .on_open_change(move |_, _, cx| {
80+ notify_entity.update(cx, |yumush, cx| {
81+ yumush.chat.card_menu = CardMenu::Main;
82+ cx.notify()
83+ })
84+ })
59 .trigger(Trigger::new(trigger))85 .trigger(Trigger::new(trigger))
60 .content(move |_, _, cx| {86 .content(move |_, _, cx| {
61 let yumush = entity.read(cx);87 let yumush = entity.read(cx);
@@ -64,6 +90,8 @@ pub(super) fn profile_popover(
64 actor: yumush.actor_rank(),90 actor: yumush.actor_rank(),
65 target: yumush.chat.rank_of(&user),91 target: yumush.chat.rank_of(&user),
66 relation: yumush.relation(&user.id),92 relation: yumush.relation(&user.id),
93+ card_menu: yumush.chat.card_menu,
94+ presence: yumush.presence_of(&user.id),
67 confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()),95 confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()),
68 reporting: yumush.chat.report == Some(ReportTarget::User(user.id.clone())),96 reporting: yumush.chat.report == Some(ReportTarget::User(user.id.clone())),
69 reason: yumush.chat.report_reason.clone(),97 reason: yumush.chat.report_reason.clone(),
@@ -75,7 +103,11 @@ pub(super) fn profile_popover(
75 user: user.clone(),103 user: user.clone(),
76 };104 };
77 105
78- card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars)106+ pop_in(
107+ "profile_card",
108+ card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars),
109+ anchor,
110+ )
79 })111 })
80 }112 }
81 113
@@ -85,6 +117,8 @@ struct Card {
85 actor: Option<Rank>,117 actor: Option<Rank>,
86 target: Option<Rank>,118 target: Option<Rank>,
87 relation: Relation,119 relation: Relation,
120+ card_menu: CardMenu,
121+ presence: Presence,
88 confirming: bool,122 confirming: bool,
89 reporting: bool,123 reporting: bool,
90 reason: Entity<InputState>,124 reason: Entity<InputState>,
@@ -161,7 +195,14 @@ impl Card {
161 .as_ref()195 .as_ref()
162 .is_some_and(|viewer| viewer.id == self.user.id);196 .is_some_and(|viewer| viewer.id == self.user.id);
163 let rows = if is_self {197 let rows = if is_self {
164- self_rows(&self.others, entity, &popover, palette)198+ self_rows(
199+ &self.others,
200+ self.card_menu,
201+ self.presence,
202+ entity,
203+ &popover,
204+ palette,
205+ )
165 } else {206 } else {
166 let mut rows = self.social_rows(entity, &popover, palette);207 let mut rows = self.social_rows(entity, &popover, palette);
167 rows.extend(self.moderation_rows(entity, &popover, palette));208 rows.extend(self.moderation_rows(entity, &popover, palette));
@@ -193,6 +234,16 @@ impl Card {
193 )234 )
194 .children(rank_tag(self.target, palette)),235 .children(rank_tag(self.target, palette)),
195 )236 )
237+ .children((!is_self).then(|| {
238+ div()
239+ .flex()
240+ .items_center()
241+ .gap(px(6.))
242+ .text_size(text(12.))
243+ .text_color(palette.muted)
244+ .child(presence_dot(self.presence, palette))
245+ .child(self.presence.label())
246+ }))
196 .children((!self.user.status.is_empty()).then(|| {247 .children((!self.user.status.is_empty()).then(|| {
197 div()248 div()
198 .text_size(text(12.))249 .text_size(text(12.))
@@ -210,7 +261,11 @@ impl Card {
210 .then(|| report_bar(&self.reason, entity, palette)),261 .then(|| report_bar(&self.reason, entity, palette)),
211 )262 )
212 .children(divider)263 .children(divider)
213- .children(rows)264+ .child(swap_in(
265+ ("profile_rows", self.card_menu as usize),
266+ div().flex().flex_col().gap(px(10.)).children(rows),
267+ self.card_menu != CardMenu::Main,
268+ ))
214 }269 }
215 270
216 fn moderation_rows(271 fn moderation_rows(
@@ -305,41 +360,46 @@ impl Card {
305 360
306 fn self_rows(361 fn self_rows(
307 others: &[(String, String)],362 others: &[(String, String)],
363+ card_menu: CardMenu,
364+ presence: Presence,
308 entity: &Entity<Yumush>,365 entity: &Entity<Yumush>,
309 popover: &Entity<PopoverState>,366 popover: &Entity<PopoverState>,
310 palette: Palette,367 palette: Palette,
311 ) -> Vec<AnyElement> {368 ) -> Vec<AnyElement> {
312- let mut rows: Vec<AnyElement> = others369+ match card_menu {
313- .iter()370+ CardMenu::Main => main_self_rows(presence, entity, popover, palette),
314- .map(|(user_id, username)| {371+ CardMenu::Accounts => accounts_rows(others, entity, popover, palette),
315- let user_id = user_id.clone();372+ CardMenu::Presence => presence_rows(entity, palette),
316- menu_row(373+ }
317- format!("switch_{user_id}"),374+}
318- username.clone(),375+
319- IconName::ArrowLeft,376+fn main_self_rows(
320- palette.text,377+ presence: Presence,
321- palette,378+ entity: &Entity<Yumush>,
322- yumush_action(entity, popover, move |yumush, window, cx| {379+ popover: &Entity<PopoverState>,
323- yumush.switch_account(user_id.clone(), window, cx)380+ palette: Palette,
324- }),381+) -> Vec<AnyElement> {
325- )382+ vec![
326- .into_any_element()383+ presence_row(
327- })384+ "profile_presence",
328- .collect();385+ presence,
329- rows.push(386+ palette,
387+ card_menu_action(entity, CardMenu::Presence),
388+ )
389+ .child(div().flex_1())
390+ .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.)))
391+ .into_any_element(),
330 menu_row(392 menu_row(
331- "profile_add_account",393+ "profile_accounts",
332- "Add account",394+ "Accounts",
333- IconName::UserPlus,395+ IconName::CircleUser,
334 palette.text,396 palette.text,
335 palette,397 palette,
336- yumush_action(entity, popover, |yumush, window, cx| {398+ card_menu_action(entity, CardMenu::Accounts),
337- yumush.add_account(window, cx)
338- }),
339 )399 )
400+ .child(div().flex_1())
401+ .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.)))
340 .into_any_element(),402 .into_any_element(),
341- );
342- rows.extend([
343 menu_row(403 menu_row(
344 "profile_settings",404 "profile_settings",
345 "Settings",405 "Settings",
@@ -362,10 +422,124 @@ fn self_rows(
362 }),422 }),
363 )423 )
364 .into_any_element(),424 .into_any_element(),
365- ]);425+ ]
426+}
427+
428+fn accounts_rows(
429+ others: &[(String, String)],
430+ entity: &Entity<Yumush>,
431+ popover: &Entity<PopoverState>,
432+ palette: Palette,
433+) -> Vec<AnyElement> {
434+ let accounts = others.iter().map(|(user_id, username)| {
435+ let user_id = user_id.clone();
436+ menu_row(
437+ format!("switch_{user_id}"),
438+ username.clone(),
439+ IconName::CircleUser,
440+ palette.text,
441+ palette,
442+ yumush_action(entity, popover, move |yumush, window, cx| {
443+ yumush.switch_account(user_id.clone(), window, cx)
444+ }),
445+ )
446+ });
447+
448+ vec![
449+ menu_row(
450+ "profile_accounts_back",
451+ "Accounts",
452+ IconName::ArrowLeft,
453+ palette.muted,
454+ palette,
455+ card_menu_action(entity, CardMenu::Main),
456+ )
457+ .into_any_element(),
458+ div()
459+ .id("profile_accounts")
460+ .max_h(px(180.))
461+ .overflow_y_scroll()
462+ .flex()
463+ .flex_col()
464+ .children(accounts)
465+ .into_any_element(),
466+ menu_row(
467+ "profile_add_account",
468+ "Add account",
469+ IconName::UserPlus,
470+ palette.text,
471+ palette,
472+ yumush_action(entity, popover, |yumush, window, cx| {
473+ yumush.add_account(window, cx)
474+ }),
475+ )
476+ .into_any_element(),
477+ ]
478+}
479+
480+fn presence_rows(entity: &Entity<Yumush>, palette: Palette) -> Vec<AnyElement> {
481+ let mut rows = vec![
482+ menu_row(
483+ "profile_presence_back",
484+ "Status",
485+ IconName::ArrowLeft,
486+ palette.muted,
487+ palette,
488+ card_menu_action(entity, CardMenu::Main),
489+ )
490+ .into_any_element(),
491+ ];
492+
493+ rows.extend(Presence::ALL.into_iter().map(|presence| {
494+ presence_row(
495+ format!("presence_{}", presence.as_str()),
496+ presence,
497+ palette,
498+ entity_action(entity, move |yumush, window, cx| {
499+ yumush.set_presence(presence, window, cx)
500+ }),
501+ )
502+ .into_any_element()
503+ }));
504+
366 rows505 rows
367 }506 }
368 507
508+fn card_menu_action(
509+ entity: &Entity<Yumush>,
510+ menu: CardMenu,
511+) -> impl Fn(&mut Window, &mut App) + 'static {
512+ entity_action(entity, move |yumush, _, cx| {
513+ yumush.chat.card_menu = menu;
514+ cx.notify();
515+ })
516+}
517+
518+fn presence_dot(presence: Presence, palette: Palette) -> Div {
519+ div()
520+ .size(px(8.))
521+ .rounded_full()
522+ .bg(presence_color(presence, palette))
523+}
524+
525+fn presence_row(
526+ id: impl Into<ElementId>,
527+ presence: Presence,
528+ palette: Palette,
529+ on_click: impl Fn(&mut Window, &mut App) + 'static,
530+) -> Stateful<Div> {
531+ clickable(id, palette, on_click)
532+ .h(px(30.))
533+ .px(px(8.))
534+ .flex()
535+ .items_center()
536+ .gap(px(8.))
537+ .rounded(px(6.))
538+ .text_color(palette.text)
539+ .child(presence_dot(presence, palette))
540+ .child(presence.label())
541+}
542+
369 fn yumush_action(543 fn yumush_action(
370 entity: &Entity<Yumush>,544 entity: &Entity<Yumush>,
371 popover: &Entity<PopoverState>,545 popover: &Entity<PopoverState>,
@@ -409,7 +583,7 @@ fn menu_row(
409 color: Hsla,583 color: Hsla,
410 palette: Palette,584 palette: Palette,
411 on_click: impl Fn(&mut Window, &mut App) + 'static,585 on_click: impl Fn(&mut Window, &mut App) + 'static,
412-) -> impl IntoElement {586+) -> Stateful<Div> {
413 clickable(id, palette, on_click)587 clickable(id, palette, on_click)
414 .h(px(30.))588 .h(px(30.))
415 .px(px(8.))589 .px(px(8.))
@@ -500,6 +674,28 @@ impl Yumush {
500 .detach();674 .detach();
501 }675 }
502 676
677+ pub(super) fn set_presence(
678+ &mut self,
679+ presence: Presence,
680+ window: &mut Window,
681+ cx: &mut Context<Self>,
682+ ) {
683+ if let Some(me) = &self.user {
684+ self.chat.presences.insert(me.id.clone(), presence);
685+ }
686+ self.chat.card_menu = CardMenu::Main;
687+ cx.notify();
688+
689+ let network = self.network.clone();
690+
691+ cx.spawn_in(window, async move |this, cx| {
692+ if let Err(error) = network.update_presence(presence).await {
693+ super::notify_error(&this, cx, error);
694+ }
695+ })
696+ .detach();
697+ }
698+
503 pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context<Self>) {699 pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context<Self>) {
504 self.chat.pending_user_delete = Some(user_id.to_string());700 self.chat.pending_user_delete = Some(user_id.to_string());
505 cx.notify();701 cx.notify();
crates/client/src/gui/settings_page.rsmodified+16 -1
@@ -6,7 +6,7 @@ use gpui_kit::{
6 AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement,6 AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement,
7 ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window,7 ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window,
8 assets::IconName,8 assets::IconName,
9- component::{Icon, input::InputState},9+ component::{Icon, input::InputState, switch::Switch},
10 div,10 div,
11 prelude::FluentBuilder as _,11 prelude::FluentBuilder as _,
12 px, transparent_black,12 px, transparent_black,
@@ -118,6 +118,21 @@ impl Yumush {
118 Yumush::set_font_size,118 Yumush::set_font_size,
119 ),119 ),
120 ),120 ),
121+ row(
122+ "Close to tray",
123+ Switch::new("close_to_tray_switch")
124+ .checked(self.settings.close_to_tray)
125+ .on_change({
126+ let entity = entity.clone();
127+ move |checked, _, cx| {
128+ let checked = *checked;
129+ entity.update(cx, |yumush, cx| {
130+ yumush.settings.close_to_tray = checked;
131+ yumush.commit_settings(cx);
132+ })
133+ }
134+ }),
135+ ),
121 ],136 ],
122 )137 )
123 .into_any_element(),138 .into_any_element(),
crates/client/src/gui/sidebar.rsmodified+400 -83
@@ -1,17 +1,18 @@
1 use super::text;1 use super::text;
2 use common::{2 use common::{
3- model::{CommunityKind, Invitation, Role, User},3+ model::{CommunityKind, Invitation, Role, Unread, User},
4 permission,4 permission,
5 validate::validate_community_name,5 validate::validate_community_name,
6 };6 };
7 use gpui_kit::{7 use gpui_kit::{
8- Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement,8+ Anchor, AnimationExt, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement,
9- ParentElement, StatefulInteractiveElement, Styled, Window,9+ IntoElement, MouseButton, ParentElement, StatefulInteractiveElement, Styled, Window,
10 assets::IconName,10 assets::IconName,
11 component::{11 component::{
12 Icon,12 Icon,
13 input::{Input, InputState},13 input::{Input, InputState},
14 menu::{ContextMenuExt, PopupMenu, PopupMenuItem},14 menu::{ContextMenuExt, PopupMenu, PopupMenuItem},
15+ popover::Popover,
15 },16 },
16 div,17 div,
17 prelude::FluentBuilder as _,18 prelude::FluentBuilder as _,
@@ -19,15 +20,19 @@ use gpui_kit::{
19 };20 };
20 21
21 use super::{22 use super::{
22- Palette, Tooltip as _, Yumush, avatar,23+ Palette, Tooltip as _, Trigger, Yumush, avatar,
23 chat::{View, create_community},24 chat::{View, create_community},
24 clickable, community_icon, community_name, entity_action, hoverable, hoverable_with,25 clickable, community_icon, community_name, entity_action, hoverable, hoverable_with,
25- input_dialog,26+ input_dialog, motion, pop_in, presence_avatar,
26 profile::profile_popover,27 profile::profile_popover,
27 settings_page::{segment, segment_track},28 settings_page::{segment, segment_track},
28 social::Relation,29 social::Relation,
30+ voice_stats,
29 };31 };
30 32
33+const SIDEBAR_WIDTH: f32 = 232.;
34+const SIDEBAR_COLLAPSED_WIDTH: f32 = 48.;
35+
31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]36 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
32 pub enum SidebarTab {37 pub enum SidebarTab {
33 Messages,38 Messages,
@@ -41,6 +46,52 @@ impl Yumush {
41 query: &str,46 query: &str,
42 palette: Palette,47 palette: Palette,
43 ) -> impl IntoElement {48 ) -> impl IntoElement {
49+ let collapsed = self.chat.sidebar_collapsed;
50+ let (from, to, id) = match collapsed {
51+ true => (SIDEBAR_WIDTH, SIDEBAR_COLLAPSED_WIDTH, "sidebar_collapsing"),
52+ false => (SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_WIDTH, "sidebar_expanding"),
53+ };
54+ let content = match collapsed {
55+ true => self.collapsed_sidebar(entity, palette).into_any_element(),
56+ false => self.expanded_sidebar(entity, query, palette),
57+ };
58+
59+ div()
60+ .h_full()
61+ .flex_shrink_0()
62+ .overflow_hidden()
63+ .child(content)
64+ .with_animation(id, motion(), move |sidebar, delta| {
65+ sidebar.w(px(from + (to - from) * delta))
66+ })
67+ }
68+
69+ fn collapsed_sidebar(&self, entity: &Entity<Self>, palette: Palette) -> Div {
70+ div()
71+ .h_full()
72+ .w(px(SIDEBAR_COLLAPSED_WIDTH))
73+ .flex()
74+ .flex_col()
75+ .items_center()
76+ .justify_between()
77+ .py(px(12.))
78+ .child(self.collapse_button(entity, palette))
79+ .child(
80+ div()
81+ .flex()
82+ .flex_col()
83+ .items_center()
84+ .gap(px(10.))
85+ .children(self.voice_dot(entity, palette))
86+ .children(
87+ self.user
88+ .as_ref()
89+ .map(|user| self.account_trigger(entity, user, false, palette)),
90+ ),
91+ )
92+ }
93+
94+ fn expanded_sidebar(&self, entity: &Entity<Self>, query: &str, palette: Palette) -> AnyElement {
44 let (top, list) = match self.chat.tab {95 let (top, list) = match self.chat.tab {
45 SidebarTab::Messages => (96 SidebarTab::Messages => (
46 Some(input_box(&self.chat.search_input, palette)),97 Some(input_box(&self.chat.search_input, palette)),
@@ -55,8 +106,7 @@ impl Yumush {
55 106
56 div()107 div()
57 .h_full()108 .h_full()
58- .w(px(232.))109+ .w(px(SIDEBAR_WIDTH))
59- .flex_shrink_0()
60 .flex()110 .flex()
61 .flex_col()111 .flex_col()
62 .py(px(12.))112 .py(px(12.))
@@ -66,7 +116,9 @@ impl Yumush {
66 div()116 div()
67 .flex()117 .flex()
68 .items_center()118 .items_center()
69- .child(self.tab_bar(entity, palette)),119+ .gap(px(6.))
120+ .child(self.tab_bar(entity, palette))
121+ .child(self.collapse_button(entity, palette)),
70 )122 )
71 .children(top)123 .children(top)
72 .child(124 .child(
@@ -77,21 +129,186 @@ impl Yumush {
77 .overflow_y_scroll()129 .overflow_y_scroll()
78 .child(list),130 .child(list),
79 )131 )
132+ .children(self.voice_panel(entity, palette))
80 .children(self.account_row(entity, palette))133 .children(self.account_row(entity, palette))
134+ .into_any_element()
135+ }
136+
137+ fn voice_panel(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
138+ let community = self.chat.voice_room()?;
139+ let direct = matches!(community.kind, CommunityKind::Direct { .. });
140+ let go_id = community.id.clone();
141+ let tone = voice_stats::quality(&self.chat.voice_samples)
142+ .map_or(palette.ok, |quality| quality.color(palette));
143+ let stats_entity = entity.clone();
144+
145+ let panel = div()
146+ .flex()
147+ .items_center()
148+ .gap(px(4.))
149+ .p(px(6.))
150+ .rounded(px(8.))
151+ .border_1()
152+ .border_color(palette.ok.opacity(0.35))
153+ .bg(palette.ok.opacity(0.08))
154+ .child(
155+ clickable(
156+ "voice_panel_go",
157+ palette,
158+ entity_action(entity, move |yumush, window, cx| {
159+ yumush.go_to_community(go_id.clone(), direct, window, cx)
160+ }),
161+ )
162+ .tip("Go to call")
163+ .flex_1()
164+ .min_w_0()
165+ .px(px(4.))
166+ .py(px(2.))
167+ .rounded(px(6.))
168+ .flex()
169+ .items_center()
170+ .gap(px(8.))
171+ .child(
172+ Icon::new(IconName::AudioLines)
173+ .w(px(16.))
174+ .h(px(16.))
175+ .text_color(tone),
176+ )
177+ .child(
178+ div()
179+ .flex_1()
180+ .min_w_0()
181+ .flex()
182+ .flex_col()
183+ .child(
184+ div()
185+ .text_size(text(12.))
186+ .font_weight(FontWeight::SEMIBOLD)
187+ .text_color(palette.ok)
188+ .child("Voice connected"),
189+ )
190+ .child(
191+ div()
192+ .truncate()
193+ .text_size(text(11.))
194+ .text_color(palette.muted)
195+ .child(community_name(community).to_string()),
196+ ),
197+ ),
198+ )
199+ .child(icon_button(
200+ "voice_panel_leave".to_string(),
201+ palette,
202+ IconName::PhoneOff,
203+ "Leave call",
204+ entity_action(entity, |yumush, _, cx| {
205+ yumush.end_voice(cx);
206+ cx.notify();
207+ }),
208+ ));
209+
210+ Some(
211+ Popover::new("voice_stats")
212+ .anchor(Anchor::BottomLeft)
213+ .mouse_button(MouseButton::Right)
214+ .appearance(false)
215+ .trigger(Trigger::new(panel))
216+ .content(move |_, _, cx| {
217+ let samples = &stats_entity.read(cx).chat.voice_samples;
218+ pop_in(
219+ "voice_stats_card",
220+ voice_stats::stats_card(samples, palette),
221+ Anchor::BottomLeft,
222+ )
223+ }),
224+ )
225+ }
226+
227+ fn voice_dot(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
228+ let community = self.chat.voice_room()?;
229+ let direct = matches!(community.kind, CommunityKind::Direct { .. });
230+ let go_id = community.id.clone();
231+
232+ Some(
233+ clickable(
234+ "voice_panel_go_collapsed",
235+ palette,
236+ entity_action(entity, move |yumush, window, cx| {
237+ yumush.go_to_community(go_id.clone(), direct, window, cx)
238+ }),
239+ )
240+ .tip("Go to call")
241+ .size(px(28.))
242+ .flex()
243+ .items_center()
244+ .justify_center()
245+ .rounded(px(6.))
246+ .border_1()
247+ .border_color(palette.ok.opacity(0.35))
248+ .bg(palette.ok.opacity(0.08))
249+ .child(
250+ Icon::new(IconName::AudioLines)
251+ .w(px(14.))
252+ .h(px(14.))
253+ .text_color(palette.ok),
254+ ),
255+ )
256+ }
257+
258+ pub(super) fn go_to_community(
259+ &mut self,
260+ community_id: String,
261+ direct: bool,
262+ window: &mut Window,
263+ cx: &mut Context<Self>,
264+ ) {
265+ if self.chat.view == View::Chat && self.chat.is_selected(&community_id) {
266+ return;
267+ }
268+ self.chat.tab = if direct {
269+ SidebarTab::Messages
270+ } else {
271+ SidebarTab::Communities
272+ };
273+ self.show_view(View::Chat, window, cx);
274+ self.select_community(community_id, window, cx);
275+ }
276+
277+ fn collapse_button(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement {
278+ let (icon, tip) = match self.chat.sidebar_collapsed {
279+ true => (IconName::PanelLeftOpen, "Expand"),
280+ false => (IconName::PanelLeftClose, "Collapse"),
281+ };
282+
283+ icon_button(
284+ "sidebar_collapse".to_string(),
285+ palette,
286+ icon,
287+ tip,
288+ entity_action(entity, |yumush, _, cx| {
289+ yumush.chat.sidebar_collapsed = !yumush.chat.sidebar_collapsed;
290+ cx.notify();
291+ }),
292+ )
81 }293 }
82 294
83 fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {295 fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
84- let requests = !self.chat.friends.incoming.is_empty() || !self.chat.invitations.is_empty();296+ let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32;
297+ let direct = self.chat.unread_total(false);
85 let tabs = [298 let tabs = [
86 (299 (
87 SidebarTab::Communities,300 SidebarTab::Communities,
88 "Communities",301 "Communities",
89- self.chat.has_unread(false),302+ self.chat.unread_total(true),
90 ),303 ),
91 (304 (
92 SidebarTab::Messages,305 SidebarTab::Messages,
93 "Messages",306 "Messages",
94- requests || self.chat.has_unread(true),307+ Unread {
308+ messages: direct.messages + requests,
309+ mentions: direct.mentions + requests,
310+ ..direct
311+ },
95 ),312 ),
96 ];313 ];
97 314
@@ -113,7 +330,7 @@ impl Yumush {
113 .gap(px(6.))330 .gap(px(6.))
114 .text_size(text(12.))331 .text_size(text(12.))
115 .child(label)332 .child(label)
116- .children(alert.then(|| dot(palette)));333+ .children(badge(palette, false, Some(&alert)));
117 334
118 match tab {335 match tab {
119 SidebarTab::Communities => item336 SidebarTab::Communities => item
@@ -135,6 +352,7 @@ impl Yumush {
135 .flex()352 .flex()
136 .flex_col()353 .flex_col()
137 .gap(px(14.))354 .gap(px(14.))
355+ .child(self.notes_row(entity, palette))
138 .children(found.map(|user| self.found_row(entity, user, palette)))356 .children(found.map(|user| self.found_row(entity, user, palette)))
139 .children(357 .children(
140 query358 query
@@ -156,6 +374,30 @@ impl Yumush {
156 ))374 ))
157 }375 }
158 376
377+ fn notes_row(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement {
378+ let notes = self.chat.notes();
379+ let active = notes.is_some_and(|notes| self.chat.is_selected(&notes.id));
380+ let unread = notes.and_then(|notes| self.chat.unread.get(&notes.id));
381+ let open = entity.clone();
382+
383+ hoverable_with(
384+ "notes",
385+ entry(
386+ palette,
387+ active,
388+ Icon::new(IconName::Bookmark)
389+ .w(px(20.))
390+ .h(px(20.))
391+ .text_color(palette.accent),
392+ "Notes",
393+ badge(palette, false, unread),
394+ ),
395+ palette.accent.opacity(0.1),
396+ )
397+ .on_click(move |_, window, cx| open.update(cx, |yumush, cx| yumush.open_notes(window, cx)))
398+ .into_any_element()
399+ }
400+
159 fn is_listed(&self, user_id: &str) -> bool {401 fn is_listed(&self, user_id: &str) -> bool {
160 self.chat402 self.chat
161 .friends403 .friends
@@ -180,7 +422,8 @@ impl Yumush {
180 .filter(|community| matches!(community.kind, CommunityKind::Group))422 .filter(|community| matches!(community.kind, CommunityKind::Group))
181 .map(|community| {423 .map(|community| {
182 let active = self.chat.is_selected(&community.id);424 let active = self.chat.is_selected(&community.id);
183- let alert = self.chat.unread.contains(&community.id);425+ let muted = self.chat.muted.contains(&community.id);
426+ let unread = self.chat.unread.get(&community.id);
184 let can_leave = !active || permission::can_leave(self.actor_rank());427 let can_leave = !active || permission::can_leave(self.actor_rank());
185 let community_id = community.id.clone();428 let community_id = community.id.clone();
186 let select = entity.clone();429 let select = entity.clone();
@@ -199,7 +442,7 @@ impl Yumush {
199 &self.chat.avatars,442 &self.chat.avatars,
200 ),443 ),
201 community.name.clone(),444 community.name.clone(),
202- alert.then(|| dot(palette).into_any_element()),445+ badge(palette, muted, unread),
203 ),446 ),
204 themed.accent.opacity(0.1),447 themed.accent.opacity(0.1),
205 )448 )
@@ -208,7 +451,12 @@ impl Yumush {
208 yumush.select_community(community_id.clone(), window, cx)451 yumush.select_community(community_id.clone(), window, cx)
209 })452 })
210 })453 })
211- .context_menu(community_menu(entity, community.id.clone(), can_leave))454+ .context_menu(community_menu(
455+ entity,
456+ community.id.clone(),
457+ can_leave,
458+ muted,
459+ ))
212 .into_any_element()460 .into_any_element()
213 }),461 }),
214 )462 )
@@ -245,7 +493,8 @@ impl Yumush {
245 .filter(|community| matches_query(community_name(community), query))493 .filter(|community| matches_query(community_name(community), query))
246 .map(|community| {494 .map(|community| {
247 let active = self.chat.is_selected(&community.id);495 let active = self.chat.is_selected(&community.id);
248- let alert = self.chat.unread.contains(&community.id);496+ let muted = self.chat.muted.contains(&community.id);
497+ let unread = self.chat.unread.get(&community.id);
249 let community_id = community.id.clone();498 let community_id = community.id.clone();
250 let select = entity.clone();499 let select = entity.clone();
251 500
@@ -255,9 +504,9 @@ impl Yumush {
255 entry(504 entry(
256 themed,505 themed,
257 active,506 active,
258- community_icon(palette, community, px(20.), text(10.), &self.chat.avatars),507+ self.community_badge(community, px(20.), text(10.), palette),
259 community_name(community).to_string(),508 community_name(community).to_string(),
260- alert.then(|| dot(palette).into_any_element()),509+ badge(palette, muted, unread),
261 ),510 ),
262 themed.accent.opacity(0.1),511 themed.accent.opacity(0.1),
263 )512 )
@@ -266,6 +515,7 @@ impl Yumush {
266 yumush.select_community(community_id.clone(), window, cx)515 yumush.select_community(community_id.clone(), window, cx)
267 })516 })
268 })517 })
518+ .context_menu(direct_menu(entity, community.id.clone(), muted))
269 .into_any_element()519 .into_any_element()
270 })520 })
271 .collect()521 .collect()
@@ -288,7 +538,12 @@ impl Yumush {
288 entry(538 entry(
289 palette,539 palette,
290 false,540 false,
291- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),541+ presence_avatar(
542+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
543+ self.presence_of(&user.id),
544+ px(20.),
545+ palette,
546+ ),
292 user.username.clone(),547 user.username.clone(),
293 Vec::new(),548 Vec::new(),
294 ),549 ),
@@ -351,7 +606,12 @@ impl Yumush {
351 entry(606 entry(
352 palette,607 palette,
353 false,608 false,
354- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),609+ presence_avatar(
610+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
611+ self.presence_of(&user.id),
612+ px(20.),
613+ palette,
614+ ),
355 user.username.clone(),615 user.username.clone(),
356 trailing,616 trailing,
357 )617 )
@@ -365,7 +625,12 @@ impl Yumush {
365 entry(625 entry(
366 palette,626 palette,
367 false,627 false,
368- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),628+ presence_avatar(
629+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
630+ self.presence_of(&user.id),
631+ px(20.),
632+ palette,
633+ ),
369 user.username.clone(),634 user.username.clone(),
370 [635 [
371 icon_button(636 icon_button(
@@ -397,7 +662,12 @@ impl Yumush {
397 entry(662 entry(
398 palette,663 palette,
399 false,664 false,
400- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),665+ presence_avatar(
666+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
667+ self.presence_of(&user.id),
668+ px(20.),
669+ palette,
670+ ),
401 user.username.clone(),671 user.username.clone(),
402 [icon_button(672 [icon_button(
403 format!("cancel_friend_{}", user.id),673 format!("cancel_friend_{}", user.id),
@@ -459,68 +729,13 @@ impl Yumush {
459 729
460 fn account_row(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {730 fn account_row(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
461 let user = self.user.as_ref()?;731 let user = self.user.as_ref()?;
462- let status = if self.connected {
463- palette.ok
464- } else {
465- palette.danger
466- };
467-
468 Some(732 Some(
469 div()733 div()
470 .h(px(36.))734 .h(px(36.))
471 .flex()735 .flex()
472 .items_center()736 .items_center()
473 .gap(px(4.))737 .gap(px(4.))
474- .child(738+ .child(self.account_trigger(entity, user, true, palette))
475- profile_popover(
476- "account_profile",
477- Anchor::BottomLeft,
478- user,
479- entity,
480- hoverable(
481- "account_trigger",
482- div()
483- .flex()
484- .items_center()
485- .h(px(36.))
486- .gap(px(8.))
487- .px(px(6.))
488- .rounded(px(6.))
489- .child(
490- div()
491- .relative()
492- .child(avatar(
493- palette,
494- user,
495- px(24.),
496- text(12.),
497- &self.chat.avatars,
498- ))
499- .child(
500- div()
501- .absolute()
502- .right(px(-2.))
503- .bottom(px(-2.))
504- .size(px(10.))
505- .rounded_full()
506- .border_2()
507- .border_color(palette.window)
508- .bg(status),
509- ),
510- )
511- .child(
512- div()
513- .flex_1()
514- .min_w_0()
515- .font_weight(FontWeight::MEDIUM)
516- .child(user.username.clone()),
517- ),
518- palette,
519- ),
520- )
521- .flex_1()
522- .min_w_0(),
523- )
524 .children(self.is_builder().then(|| {739 .children(self.is_builder().then(|| {
525 icon_button(740 icon_button(
526 "builder_button".to_string(),741 "builder_button".to_string(),
@@ -536,6 +751,48 @@ impl Yumush {
536 )751 )
537 }752 }
538 753
754+ fn account_trigger(
755+ &self,
756+ entity: &Entity<Self>,
757+ user: &User,
758+ named: bool,
759+ palette: Palette,
760+ ) -> impl IntoElement {
761+ profile_popover(
762+ "account_profile",
763+ Anchor::BottomLeft,
764+ user,
765+ entity,
766+ hoverable(
767+ "account_trigger",
768+ div()
769+ .flex()
770+ .items_center()
771+ .h(px(36.))
772+ .gap(px(8.))
773+ .px(px(6.))
774+ .rounded(px(6.))
775+ .child(presence_avatar(
776+ avatar(palette, user, px(24.), text(12.), &self.chat.avatars),
777+ self.presence_of(&user.id),
778+ px(24.),
779+ palette,
780+ ))
781+ .when(named, |trigger| {
782+ trigger.child(
783+ div()
784+ .flex_1()
785+ .min_w_0()
786+ .font_weight(FontWeight::MEDIUM)
787+ .child(user.username.clone()),
788+ )
789+ }),
790+ palette,
791+ ),
792+ )
793+ .when(named, |trigger| trigger.flex_1().min_w_0())
794+ }
795+
539 fn set_sidebar_tab(&mut self, tab: SidebarTab, window: &mut Window, cx: &mut Context<Self>) {796 fn set_sidebar_tab(&mut self, tab: SidebarTab, window: &mut Window, cx: &mut Context<Self>) {
540 self.chat.tab = tab;797 self.chat.tab = tab;
541 if tab == SidebarTab::Messages {798 if tab == SidebarTab::Messages {
@@ -557,10 +814,73 @@ impl Yumush {
557 }814 }
558 }815 }
559 816
817+pub(super) fn badge(palette: Palette, muted: bool, unread: Option<&Unread>) -> Option<AnyElement> {
818+ if muted {
819+ return Some(
820+ div()
821+ .text_color(palette.muted)
822+ .child(Icon::new(IconName::BellOff).w(px(12.)).h(px(12.)))
823+ .into_any_element(),
824+ );
825+ }
826+ let unread = unread.filter(|unread| unread.messages > 0)?;
827+ let (fill, ink) = if unread.mentions > 0 {
828+ (palette.accent, palette.on_accent)
829+ } else {
830+ (palette.muted, palette.window)
831+ };
832+ let count = match unread.messages {
833+ 1..=99 => unread.messages.to_string(),
834+ _ => "99+".to_string(),
835+ };
836+ Some(
837+ div()
838+ .h(px(16.))
839+ .min_w(px(16.))
840+ .px(px(4.))
841+ .flex()
842+ .items_center()
843+ .justify_center()
844+ .rounded_full()
845+ .text_size(text(10.))
846+ .bg(fill)
847+ .text_color(ink)
848+ .child(count)
849+ .into_any_element(),
850+ )
851+}
852+
853+fn mute_item(
854+ menu: PopupMenu,
855+ entity: &Entity<Yumush>,
856+ community_id: String,
857+ muted: bool,
858+) -> PopupMenu {
859+ let entity = entity.clone();
860+ let label = if muted { "Unmute" } else { "Mute" };
861+
862+ menu.item(PopupMenuItem::new(label).on_click(move |_, _, cx| {
863+ entity.update(cx, |yumush, cx| {
864+ yumush.toggle_community_mute(community_id.clone(), cx)
865+ })
866+ }))
867+}
868+
869+fn direct_menu(
870+ entity: &Entity<Yumush>,
871+ community_id: String,
872+ muted: bool,
873+) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static {
874+ let entity = entity.clone();
875+
876+ move |menu, _, _| mute_item(menu, &entity, community_id.clone(), muted)
877+}
878+
560 fn community_menu(879 fn community_menu(
561 entity: &Entity<Yumush>,880 entity: &Entity<Yumush>,
562 community_id: String,881 community_id: String,
563 can_leave: bool,882 can_leave: bool,
883+ muted: bool,
564 ) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static {884 ) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static {
565 let entity = entity.clone();885 let entity = entity.clone();
566 886
@@ -585,6 +905,7 @@ fn community_menu(
585 })905 })
586 }),906 }),
587 );907 );
908+ let menu = mute_item(menu, &entity, community_id.clone(), muted);
588 909
589 if !can_leave {910 if !can_leave {
590 return menu;911 return menu;
@@ -631,7 +952,7 @@ fn new_community_menu(
631 }952 }
632 }953 }
633 954
634-fn input_box(input: &Entity<InputState>, palette: Palette) -> Div {955+pub(super) fn input_box(input: &Entity<InputState>, palette: Palette) -> Div {
635 div()956 div()
636 .h(px(30.))957 .h(px(30.))
637 .px(px(10.))958 .px(px(10.))
@@ -691,10 +1012,6 @@ fn entry(
691 .children(trailing)1012 .children(trailing)
692 }1013 }
693 1014
694-fn dot(palette: Palette) -> Div {
695- div().size(px(6.)).rounded_full().bg(palette.alert)
696-}
697-
698 fn icon_button(1015 fn icon_button(
699 id: String,1016 id: String,
700 palette: Palette,1017 palette: Palette,
crates/client/src/gui/snippet.rsmodified+23 -5
@@ -6,7 +6,7 @@ use gpui_kit::{
6 relative,6 relative,
7 };7 };
8 8
9-use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view};9+use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view, poll, profile::user_link};
10 10
11 pub fn snippet_card(11 pub fn snippet_card(
12 message: &Message,12 message: &Message,
@@ -62,7 +62,12 @@ fn snippet_row(
62 div()62 div()
63 .flex()63 .flex()
64 .gap(px(8.))64 .gap(px(8.))
65- .child(avatar(palette, &user, px(20.), text(10.), &chat.avatars))65+ .child(user_link(
66+ format!("snippet_avatar_{}", item.id),
67+ Some(&user),
68+ entity,
69+ avatar(palette, &user, px(20.), text(10.), &chat.avatars),
70+ ))
66 .child(71 .child(
67 div()72 div()
68 .flex_1()73 .flex_1()
@@ -75,12 +80,15 @@ fn snippet_row(
75 .flex()80 .flex()
76 .items_center()81 .items_center()
77 .gap(px(6.))82 .gap(px(6.))
78- .child(83+ .child(user_link(
84+ format!("snippet_name_{}", item.id),
85+ Some(&user),
86+ entity,
79 div()87 div()
80 .font_weight(FontWeight::SEMIBOLD)88 .font_weight(FontWeight::SEMIBOLD)
81 .text_color(palette.tinted(&item.user_id))89 .text_color(palette.tinted(&item.user_id))
82 .child(item.username.clone()),90 .child(item.username.clone()),
83- )91+ ))
84 .child(92 .child(
85 div()93 div()
86 .text_size(text(11.))94 .text_size(text(11.))
@@ -101,6 +109,16 @@ fn snippet_row(
101 &chat.media,109 &chat.media,
102 entity,110 entity,
103 palette,111 palette,
104- )),112+ ))
113+ .children(item.poll.as_ref().map(|poll| {
114+ poll::poll_card(
115+ poll,
116+ poll::PollMode::Snapshot(&item.id),
117+ None,
118+ chat,
119+ entity,
120+ palette,
121+ )
122+ })),
105 )123 )
106 }124 }
crates/client/src/gui/social.rsmodified+24 -9
@@ -111,7 +111,7 @@ impl Yumush {
111 .iter()111 .iter()
112 .filter_map(|community| match &community.kind {112 .filter_map(|community| match &community.kind {
113 CommunityKind::Direct { peer } => Some(peer),113 CommunityKind::Direct { peer } => Some(peer),
114- CommunityKind::Group => None,114+ CommunityKind::Group | CommunityKind::Notes => None,
115 }),115 }),
116 );116 );
117 let avatar_ids: Vec<String> = users117 let avatar_ids: Vec<String> = users
@@ -132,18 +132,22 @@ impl Yumush {
132 let network = self.network.clone();132 let network = self.network.clone();
133 133
134 cx.spawn_in(window, async move |this, cx| {134 cx.spawn_in(window, async move |this, cx| {
135- let (friends, invitations) =135+ let (friends, invitations, presences) = match (
136- match (network.friends().await, network.invitations().await) {136+ network.friends().await,
137- (Ok(friends), Ok(invitations)) => (friends, invitations),137+ network.invitations().await,
138- (Err(error), _) | (_, Err(error)) => {138+ network.read_presences().await,
139- notify_error(&this, cx, error);139+ ) {
140- return;140+ (Ok(friends), Ok(invitations), Ok(presences)) => (friends, invitations, presences),
141- }141+ (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
142- };142+ notify_error(&this, cx, error);
143+ return;
144+ }
145+ };
143 146
144 let _ = this.update(cx, |yumush, cx| {147 let _ = this.update(cx, |yumush, cx| {
145 yumush.chat.friends = friends;148 yumush.chat.friends = friends;
146 yumush.chat.invitations = invitations;149 yumush.chat.invitations = invitations;
150+ yumush.chat.presences = presences.into_iter().collect();
147 yumush.request_social_avatars(cx);151 yumush.request_social_avatars(cx);
148 cx.notify();152 cx.notify();
149 });153 });
@@ -192,6 +196,17 @@ impl Yumush {
192 }196 }
193 }197 }
194 198
199+ pub(super) fn open_notes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
200+ if let Some(notes) = self.chat.notes() {
201+ let community_id = notes.id.clone();
202+ self.select_community(community_id, window, cx);
203+ return;
204+ }
205+ let network = self.network.clone();
206+
207+ spawn_community(window, cx, async move { network.open_notes().await });
208+ }
209+
195 pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {210 pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {
196 let network = self.network.clone();211 let network = self.network.clone();
197 212
crates/client/src/gui/voice_note.rsadded+287 -0
@@ -0,0 +1,287 @@
1+use std::{
2+ rc::Rc,
3+ sync::{Arc, Mutex},
4+ time::{Duration, Instant},
5+};
6+
7+use common::constant::VOICE_SAMPLE_RATE;
8+use gpui_kit::{
9+ App, Context, Div, Entity, InteractiveElement, IntoElement, MouseButton, ParentElement, Styled,
10+ Task, Window,
11+ assets::IconName,
12+ component::{Icon, WindowExt, notification::Notification},
13+ div, px,
14+};
15+use rtrb::{Consumer, RingBuffer};
16+
17+use super::{
18+ Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, media_view::time_text,
19+ notify_error, primary_button, text,
20+};
21+use crate::{
22+ media::voice_note::{self, BARS},
23+ voice::{
24+ Playback,
25+ audio::{self, Audio},
26+ },
27+};
28+
29+const TICK: Duration = Duration::from_millis(100);
30+const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize;
31+const SLOT_WIDTH: f32 = 5.;
32+const BAR_WIDTH: f32 = 3.;
33+const BAR_MIN: f32 = 2.;
34+const BAR_MAX: f32 = 24.;
35+
36+#[derive(Default)]
37+pub enum VoiceNote {
38+ #[default]
39+ Idle,
40+ Recording {
41+ started: Instant,
42+ _audio: Audio,
43+ consumer: Consumer<f32>,
44+ samples: Vec<f32>,
45+ levels: Vec<f32>,
46+ _tick: Task<()>,
47+ },
48+}
49+
50+pub fn bars(
51+ levels: &[f32],
52+ progress: f32,
53+ palette: Palette,
54+ on_pick: impl Fn(usize, &mut Window, &mut App) + 'static,
55+) -> Div {
56+ let on_pick = Rc::new(on_pick);
57+ let offset = BARS - levels.len().min(BARS);
58+ div()
59+ .flex_1()
60+ .h(px(BAR_MAX))
61+ .flex()
62+ .items_center()
63+ .children((0..BARS).map(|index| {
64+ let level = index
65+ .checked_sub(offset)
66+ .and_then(|slot| levels.get(slot))
67+ .copied()
68+ .unwrap_or(0.);
69+ let color = if (index as f32) < progress * BARS as f32 {
70+ palette.accent
71+ } else {
72+ palette.muted
73+ };
74+ let (down, drag) = (on_pick.clone(), on_pick.clone());
75+ div()
76+ .w(px(SLOT_WIDTH))
77+ .h_full()
78+ .flex()
79+ .items_center()
80+ .justify_center()
81+ .on_mouse_down(MouseButton::Left, move |_, window, cx| {
82+ down(index, window, cx)
83+ })
84+ .on_mouse_move(move |event, window, cx| {
85+ if event.pressed_button == Some(MouseButton::Left) {
86+ drag(index, window, cx);
87+ }
88+ })
89+ .child(
90+ div()
91+ .w(px(BAR_WIDTH))
92+ .h(px((BAR_MAX * level).max(BAR_MIN)))
93+ .rounded(px(BAR_WIDTH / 2.))
94+ .bg(color),
95+ )
96+ }))
97+}
98+
99+pub fn recording_row(
100+ started: Instant,
101+ levels: &[f32],
102+ entity: &Entity<Yumush>,
103+ palette: Palette,
104+) -> impl IntoElement {
105+ let cancel = entity.clone();
106+ let send = entity.clone();
107+
108+ div()
109+ .min_h(px(40.))
110+ .pl(px(4.))
111+ .pr(px(4.))
112+ .py(px(4.))
113+ .flex()
114+ .items_center()
115+ .gap(px(8.))
116+ .rounded(px(8.))
117+ .border_1()
118+ .border_color(palette.border)
119+ .bg(palette.field)
120+ .child(
121+ clickable("cancel_voice_note", palette, move |_, cx| {
122+ cancel.update(cx, |yumush, cx| yumush.cancel_voice_note(cx))
123+ })
124+ .tip("Cancel")
125+ .size(px(28.))
126+ .flex()
127+ .items_center()
128+ .justify_center()
129+ .rounded(px(6.))
130+ .text_color(palette.muted)
131+ .child(Icon::new(IconName::X).w(px(16.)).h(px(16.))),
132+ )
133+ .child(
134+ div()
135+ .flex_1()
136+ .flex()
137+ .items_center()
138+ .gap(px(6.))
139+ .text_size(text(13.))
140+ .text_color(palette.text)
141+ .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.)))
142+ .child(time_text(started.elapsed()))
143+ .child(bars(levels, 1., palette, |_, _, _| {})),
144+ )
145+ .child(
146+ primary_button("send_voice_note", palette, move |window, cx| {
147+ send.update(cx, |yumush, cx| yumush.send_voice_note(window, cx))
148+ })
149+ .tip("Send")
150+ .size(px(28.))
151+ .flex()
152+ .items_center()
153+ .justify_center()
154+ .rounded(px(6.))
155+ .child(Icon::new(IconName::ArrowUp).w(px(14.)).h(px(14.))),
156+ )
157+}
158+
159+pub fn mic_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
160+ let entity = entity.clone();
161+
162+ clickable("voice_note_button", palette, move |window, cx| {
163+ entity.update(cx, |yumush, cx| yumush.start_voice_note(window, cx))
164+ })
165+ .tip("Voice message")
166+ .size(px(28.))
167+ .flex()
168+ .items_center()
169+ .justify_center()
170+ .rounded(px(6.))
171+ .text_color(palette.muted)
172+ .child(Icon::new(IconName::Mic).w(px(16.)).h(px(16.)))
173+}
174+
175+impl Yumush {
176+ fn start_voice_note(&mut self, window: &mut Window, cx: &mut Context<Self>) {
177+ if !matches!(self.chat.voice_state, VoiceState::Off) {
178+ window.push_notification(Notification::error("Leave voice call first"), cx);
179+ return;
180+ }
181+ let (producer, consumer) = RingBuffer::new(RING_SAMPLES);
182+ let capture = Arc::new(Mutex::new(producer));
183+ let (_, silent) = RingBuffer::new(1);
184+ let playback: Playback = Arc::new(Mutex::new(silent));
185+ let audio = audio::start(Some(capture), playback, self.settings.voice.choice.clone());
186+ let tick = cx.spawn(async move |this, cx| {
187+ loop {
188+ cx.background_executor().timer(TICK).await;
189+ if this
190+ .update(cx, |yumush, cx| yumush.tick_voice_note(cx))
191+ .is_err()
192+ {
193+ break;
194+ }
195+ }
196+ });
197+ self.chat.media.voice_note = VoiceNote::Recording {
198+ started: Instant::now(),
199+ _audio: audio,
200+ consumer,
201+ samples: Vec::new(),
202+ levels: Vec::new(),
203+ _tick: tick,
204+ };
205+ cx.notify();
206+ }
207+
208+ fn tick_voice_note(&mut self, cx: &mut Context<Self>) {
209+ if let VoiceNote::Recording {
210+ consumer,
211+ samples,
212+ levels,
213+ ..
214+ } = &mut self.chat.media.voice_note
215+ {
216+ let start = samples.len();
217+ while let Ok(sample) = consumer.pop() {
218+ samples.push(sample);
219+ }
220+ levels.push(voice_note::level(&samples[start..]));
221+ if levels.len() > BARS {
222+ levels.remove(0);
223+ }
224+ }
225+ cx.notify();
226+ }
227+
228+ fn cancel_voice_note(&mut self, cx: &mut Context<Self>) {
229+ self.chat.media.voice_note = VoiceNote::Idle;
230+ cx.notify();
231+ }
232+
233+ fn send_voice_note(&mut self, window: &mut Window, cx: &mut Context<Self>) {
234+ let VoiceNote::Recording {
235+ mut consumer,
236+ mut samples,
237+ ..
238+ } = std::mem::take(&mut self.chat.media.voice_note)
239+ else {
240+ return;
241+ };
242+ while let Ok(sample) = consumer.pop() {
243+ samples.push(sample);
244+ }
245+ let Some(community_id) = self.chat.selected_community_id.clone() else {
246+ return;
247+ };
248+ let network = self.network.clone();
249+ let maximum = self
250+ .server
251+ .as_ref()
252+ .map(|settings| settings.max_attachment_bytes);
253+ cx.notify();
254+
255+ cx.spawn_in(window, async move |this, cx| {
256+ let Some(path) = cx
257+ .background_executor()
258+ .spawn(async move { voice_note::save(&samples) })
259+ .await
260+ else {
261+ return;
262+ };
263+ let _ = this.update(cx, |yumush, cx| {
264+ yumush.chat.media.uploading += 1;
265+ cx.notify();
266+ });
267+ let uploaded = network
268+ .upload_attachment(&community_id, path, maximum)
269+ .await;
270+ let _ = this.update(cx, |yumush, cx| {
271+ yumush.chat.media.uploading -= 1;
272+ cx.notify();
273+ });
274+ let attachment = match uploaded {
275+ Ok(attachment) => attachment,
276+ Err(error) => return notify_error(&this, cx, error),
277+ };
278+ if let Err(error) = network
279+ .create_message(&community_id, "", vec![attachment.id], None)
280+ .await
281+ {
282+ notify_error(&this, cx, error);
283+ }
284+ })
285+ .detach();
286+ }
287+}
crates/client/src/gui/voice_stats.rsadded+209 -0
@@ -0,0 +1,209 @@
1+use std::collections::VecDeque;
2+
3+use gpui_kit::{
4+ Div, FontWeight, Hsla, ParentElement, Styled, div, hsla, prelude::FluentBuilder as _, px,
5+};
6+
7+use super::{Palette, text};
8+use crate::voice::VoiceSample;
9+
10+pub const SAMPLE_HISTORY: usize = 60;
11+const GRAPH_HEIGHT: f32 = 32.;
12+const PING_SCALE: f32 = 150.;
13+const LOSS_SCALE: f32 = 10.;
14+
15+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16+pub enum Quality {
17+ Good,
18+ Fair,
19+ Poor,
20+}
21+
22+impl Quality {
23+ pub fn of(sample: &VoiceSample) -> Self {
24+ let loss = sample.traffic.loss * 100.;
25+ let jitter = sample.traffic.jitter_ms;
26+ if sample.ping_ms < 100. && loss < 2. && jitter < 30. {
27+ Self::Good
28+ } else if sample.ping_ms < 200. && loss < 8. && jitter < 60. {
29+ Self::Fair
30+ } else {
31+ Self::Poor
32+ }
33+ }
34+
35+ fn label(self) -> &'static str {
36+ match self {
37+ Self::Good => "Good",
38+ Self::Fair => "Fair",
39+ Self::Poor => "Poor",
40+ }
41+ }
42+
43+ pub fn color(self, palette: Palette) -> Hsla {
44+ match self {
45+ Self::Good => palette.ok,
46+ Self::Fair => hsla(0.11, 0.85, 0.55, 1.),
47+ Self::Poor => palette.danger,
48+ }
49+ }
50+}
51+
52+pub fn quality(samples: &VecDeque<VoiceSample>) -> Option<Quality> {
53+ samples.back().map(Quality::of)
54+}
55+
56+pub fn stats_card(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div {
57+ let latest = samples.back();
58+ let value = |format: fn(&VoiceSample) -> String| latest.map_or("…".to_string(), format);
59+ let tiles = [
60+ ("Ping", value(|sample| format!("{:.0} ms", sample.ping_ms))),
61+ (
62+ "Jitter",
63+ value(|sample| format!("{:.0} ms", sample.traffic.jitter_ms)),
64+ ),
65+ (
66+ "Loss",
67+ value(|sample| format!("{:.1} %", sample.traffic.loss * 100.)),
68+ ),
69+ (
70+ "Buffer",
71+ value(|sample| format!("{:.0} ms", sample.traffic.buffer_ms)),
72+ ),
73+ (
74+ "Upload",
75+ value(|sample| format!("{:.0} kbps", sample.traffic.up_kbps)),
76+ ),
77+ (
78+ "Download",
79+ value(|sample| format!("{:.0} kbps", sample.traffic.down_kbps)),
80+ ),
81+ ];
82+
83+ div()
84+ .w(px(280.))
85+ .p(px(14.))
86+ .flex()
87+ .flex_col()
88+ .gap(px(12.))
89+ .rounded(px(8.))
90+ .border_1()
91+ .border_color(palette.border)
92+ .bg(palette.panel)
93+ .shadow_lg()
94+ .child(
95+ div()
96+ .flex()
97+ .items_center()
98+ .justify_between()
99+ .child(
100+ div()
101+ .font_weight(FontWeight::SEMIBOLD)
102+ .text_color(palette.text)
103+ .child("Connection"),
104+ )
105+ .children(latest.map(|sample| {
106+ let quality = Quality::of(sample);
107+ let color = quality.color(palette);
108+ div()
109+ .px(px(8.))
110+ .py(px(2.))
111+ .rounded_full()
112+ .bg(color.opacity(0.15))
113+ .text_size(text(11.))
114+ .font_weight(FontWeight::MEDIUM)
115+ .text_color(color)
116+ .child(quality.label())
117+ })),
118+ )
119+ .child(
120+ div()
121+ .flex()
122+ .flex_wrap()
123+ .gap(px(6.))
124+ .children(tiles.map(|(label, value)| tile(label, value, palette))),
125+ )
126+ .child(graph(
127+ "Ping",
128+ samples,
129+ |sample| sample.ping_ms / PING_SCALE,
130+ palette,
131+ ))
132+ .child(graph(
133+ "Loss",
134+ samples,
135+ |sample| sample.traffic.loss * 100. / LOSS_SCALE,
136+ palette,
137+ ))
138+ .children(latest.map(|sample| {
139+ div()
140+ .text_size(text(11.))
141+ .text_color(palette.muted)
142+ .child(format!("Opus · 48 kHz · {} kbps", sample.bitrate_kbps))
143+ }))
144+}
145+
146+fn tile(label: &'static str, value: String, palette: Palette) -> Div {
147+ div()
148+ .w(px(80.))
149+ .px(px(8.))
150+ .py(px(6.))
151+ .flex()
152+ .flex_col()
153+ .rounded(px(6.))
154+ .bg(palette.window)
155+ .child(
156+ div()
157+ .text_size(text(10.))
158+ .text_color(palette.muted)
159+ .child(label),
160+ )
161+ .child(
162+ div()
163+ .text_size(text(12.))
164+ .font_weight(FontWeight::MEDIUM)
165+ .text_color(palette.text)
166+ .child(value),
167+ )
168+}
169+
170+fn graph(
171+ label: &'static str,
172+ samples: &VecDeque<VoiceSample>,
173+ level: fn(&VoiceSample) -> f32,
174+ palette: Palette,
175+) -> Div {
176+ let empty = SAMPLE_HISTORY.saturating_sub(samples.len());
177+ let bars = samples.iter().map(|sample| {
178+ let height = level(sample).clamp(0.04, 1.) * GRAPH_HEIGHT;
179+ div()
180+ .flex_1()
181+ .h(px(height))
182+ .rounded_t(px(1.))
183+ .bg(Quality::of(sample).color(palette))
184+ });
185+
186+ div()
187+ .flex()
188+ .flex_col()
189+ .gap(px(4.))
190+ .child(
191+ div()
192+ .text_size(text(10.))
193+ .text_color(palette.muted)
194+ .child(label),
195+ )
196+ .child(
197+ div()
198+ .h(px(GRAPH_HEIGHT))
199+ .p(px(2.))
200+ .flex()
201+ .items_end()
202+ .gap(px(1.))
203+ .rounded(px(4.))
204+ .bg(palette.window)
205+ .children((0..empty).map(|_| div().flex_1()))
206+ .children(bars)
207+ .when(samples.is_empty(), |this| this.opacity(0.5)),
208+ )
209+}
crates/client/src/lib.rsmodified+2 -0
@@ -5,8 +5,10 @@ pub mod avatar;
5 pub mod embed;5 pub mod embed;
6 pub mod gui;6 pub mod gui;
7 pub mod media;7 pub mod media;
8+pub mod mutes;
8 pub mod network;9 pub mod network;
9 pub mod settings;10 pub mod settings;
11+pub mod tray;
10 pub mod voice;12 pub mod voice;
11 13
12 pub const NAME: &str = "Yumush";14 pub const NAME: &str = "Yumush";
crates/client/src/main.rsmodified+78 -20
@@ -2,10 +2,11 @@ use client::{
2 ClientConfig, NAME,2 ClientConfig, NAME,
3 gui::{self, Yumush},3 gui::{self, Yumush},
4 network, settings,4 network, settings,
5+ tray::{self, TrayAction, TrayState},
5 };6 };
6 use gpui_kit::{7 use gpui_kit::{
7- App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application,8+ App, AppContext, Bounds, Entity, QuitMode, TitlebarOptions, Window, WindowBounds,
8- assets::AllAssets, component::Root, init, px, size,9+ WindowOptions, application, assets::AllAssets, component::Root, init, px, size,
9 };10 };
10 11
11 use tracing::Level;12 use tracing::Level;
@@ -23,36 +24,93 @@ fn main() {
23 24
24 let settings = settings::load();25 let settings = settings::load();
25 let (network_handle, network_event_receiver) = network::start(ClientConfig::default());26 let (network_handle, network_event_receiver) = network::start(ClientConfig::default());
27+ let (mut tray_receiver, tray_handle) = tray::start();
26 28
27 application()29 application()
28 .with_assets(AllAssets)30 .with_assets(AllAssets)
31+ .with_quit_mode(QuitMode::Explicit)
29 .run(move |cx: &mut App| {32 .run(move |cx: &mut App| {
30 init(cx);33 init(cx);
31 settings::apply(settings.theme, settings.font_size, cx);34 settings::apply(settings.theme, settings.font_size, cx);
32 gui::bind_keys(cx);35 gui::bind_keys(cx);
33 36
34- let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx);37+ let Some(view) = open_window(cx, |window, cx| {
35-38+ cx.new(|cx| {
36- let titlebar = TitlebarOptions {39+ Yumush::new(network_handle, network_event_receiver, settings, window, cx)
37- title: Some(NAME.into()),40+ })
38- ..Default::default()41+ }) else {
42+ cx.quit();
43+ return;
39 };44 };
40 45
41- cx.open_window(46+ let mut tray_state = TrayState::default();
42- WindowOptions {47+ cx.observe(&view, move |view, cx| {
43- window_bounds: Some(WindowBounds::Windowed(window_bounds)),48+ let state = view.read(cx).tray_state();
44- titlebar: Some(titlebar),49+ if state != tray_state {
45- ..Default::default()50+ tray_state = state;
46- },51+ tray_handle.set(state);
47- |window, cx| {52+ }
48- let view = cx.new(|cx| {53+ })
49- Yumush::new(network_handle, network_event_receiver, settings, window, cx)54+ .detach();
55+
56+ cx.spawn(async move |cx| {
57+ while let Some(action) = tray_receiver.recv().await {
58+ let view = view.clone();
59+ cx.update(|cx| match action {
60+ TrayAction::Show => show(view, cx),
61+ TrayAction::Quit => cx.quit(),
50 });62 });
51- cx.new(|cx| Root::new(view, window, cx))63+ }
52- },64+ })
53- )65+ .detach();
54- .unwrap();
55 66
56 cx.activate(true);67 cx.activate(true);
57 });68 });
58 }69 }
70+
71+fn show(view: Entity<Yumush>, cx: &mut App) {
72+ match view.read(cx).window() {
73+ Some(handle) => {
74+ let _ = handle.update(cx, |_, window, _| window.activate_window());
75+ }
76+ None => {
77+ open_window(cx, |_, _| view);
78+ }
79+ }
80+}
81+
82+fn open_window(
83+ cx: &mut App,
84+ build: impl FnOnce(&mut Window, &mut App) -> Entity<Yumush>,
85+) -> Option<Entity<Yumush>> {
86+ let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx);
87+ let titlebar = TitlebarOptions {
88+ title: Some(NAME.into()),
89+ ..Default::default()
90+ };
91+ let mut opened = None;
92+
93+ cx.open_window(
94+ WindowOptions {
95+ window_bounds: Some(WindowBounds::Windowed(window_bounds)),
96+ titlebar: Some(titlebar),
97+ ..Default::default()
98+ },
99+ |window, cx| {
100+ let view = build(window, cx);
101+ view.update(cx, |yumush, cx| yumush.attach_window(window, cx));
102+ let closing = view.clone();
103+ window.on_window_should_close(cx, move |_, cx| {
104+ if !closing.update(cx, |yumush, _| yumush.detach_window()) {
105+ cx.quit();
106+ }
107+ true
108+ });
109+ opened = Some(view.clone());
110+ cx.new(|cx| Root::new(view, window, cx))
111+ },
112+ )
113+ .ok()?;
114+
115+ opened
116+}
crates/client/src/media/mod.rsmodified+1 -0
@@ -1,6 +1,7 @@
1 mod convert;1 mod convert;
2 mod decode;2 mod decode;
3 mod resample;3 mod resample;
4+pub mod voice_note;
4 5
5 use std::{6 use std::{
6 fmt,7 fmt,
crates/client/src/media/voice_note.rsadded+113 -0
@@ -0,0 +1,113 @@
1+use std::{
2+ path::{Path, PathBuf},
3+ time::Duration,
4+};
5+
6+use common::{
7+ constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE},
8+ model::{Attachment, AttachmentKind},
9+ time::now_ms,
10+};
11+use ec_core::{Buf, CodecId, CodecParameters, Muxer, Packet, StreamInfo, TimeBase};
12+use ec_ogg::OggMuxer;
13+use ec_opus::{Application, Encoder, ogg::opus_head};
14+use ec_probe::{Reader, decoder::AudioDecoder};
15+
16+use super::resample;
17+
18+pub const BARS: usize = 40;
19+const BITRATE: u32 = 32_000;
20+const MAX_PACKET: usize = 1275;
21+const RANGE_DB: f32 = 60.;
22+
23+pub struct Waveform {
24+ pub duration: Duration,
25+ pub peaks: Vec<f32>,
26+}
27+
28+pub fn level(samples: &[f32]) -> f32 {
29+ if samples.is_empty() {
30+ return 0.;
31+ }
32+ let mean = samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32;
33+ let db = 10. * mean.max(f32::MIN_POSITIVE).log10();
34+ ((db + RANGE_DB) / RANGE_DB).clamp(0., 1.)
35+}
36+
37+fn peaks(mono: &[f32]) -> Vec<f32> {
38+ let size = mono.len().div_ceil(BARS).max(1);
39+ let mut levels: Vec<f32> = mono.chunks(size).map(level).collect();
40+ let max = levels.iter().copied().fold(0., f32::max);
41+ if max > 0. {
42+ levels.iter_mut().for_each(|level| *level /= max);
43+ }
44+ levels.resize(BARS, 0.);
45+ levels
46+}
47+
48+pub fn waveform(path: &Path) -> Option<Waveform> {
49+ let mut reader = Reader::open(path).ok()?;
50+ let (index, params) = reader
51+ .streams()
52+ .iter()
53+ .find(|stream| matches!(stream.params.codec, CodecId::Opus))
54+ .map(|stream| (stream.index, stream.params.clone()))?;
55+ let mut decoder = AudioDecoder::new(&params).ok()?;
56+ let mut interleaved = Vec::new();
57+ let mut scratch = Vec::new();
58+ while let Ok(packet) = reader.next_packet() {
59+ if packet.stream == index && decoder.decode(&packet, &mut scratch).is_ok() {
60+ interleaved.append(&mut scratch);
61+ }
62+ }
63+ let mono = resample::downmix(&interleaved, decoder.channels());
64+ Some(Waveform {
65+ duration: Duration::from_secs_f32(mono.len() as f32 / VOICE_SAMPLE_RATE as f32),
66+ peaks: peaks(&mono),
67+ })
68+}
69+
70+pub fn is_voice_note(attachment: &Attachment) -> bool {
71+ attachment.kind == AttachmentKind::Audio
72+ && attachment.name.starts_with("voice-")
73+ && attachment.name.ends_with(".ogg")
74+}
75+
76+pub fn encode(samples: &[f32]) -> Option<Vec<u8>> {
77+ if samples.is_empty() {
78+ return None;
79+ }
80+ let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, Application::Voip).ok()?;
81+ encoder.set_bitrate(BITRATE);
82+
83+ let timebase = TimeBase::new(1, VOICE_SAMPLE_RATE as i64);
84+ let mut params = CodecParameters::new(CodecId::Opus);
85+ params.extradata = Some(Buf::from_vec(opus_head(1, 0, VOICE_SAMPLE_RATE, 0, None)));
86+ let mut muxer = OggMuxer::new(Vec::new());
87+ muxer
88+ .add_stream(StreamInfo::new(0, timebase, params))
89+ .ok()?;
90+
91+ let frame = VOICE_FRAME_SAMPLES;
92+ let mut packet = vec![0u8; MAX_PACKET];
93+ for (index, chunk) in samples.chunks(frame).enumerate() {
94+ let mut pcm = chunk.to_vec();
95+ pcm.resize(frame, 0.0);
96+ let length = encoder.encode_float(&pcm, frame, &mut packet).ok()?;
97+ let data = Packet::new(0, timebase, packet[..length].to_vec())
98+ .with_pts((index * frame) as i64)
99+ .with_duration(frame as i64);
100+ muxer.write_packet(&data).ok()?;
101+ }
102+ muxer.finish().ok()?;
103+ Some(muxer.into_inner())
104+}
105+
106+pub fn save(samples: &[f32]) -> Option<PathBuf> {
107+ let bytes = encode(samples)?;
108+ let directory = dirs::cache_dir()?.join("yumush").join("media");
109+ std::fs::create_dir_all(&directory).ok()?;
110+ let path = directory.join(format!("voice-{}.ogg", now_ms()));
111+ std::fs::write(&path, bytes).ok()?;
112+ Some(path)
113+}
crates/client/src/mutes.rsadded+57 -0
@@ -0,0 +1,57 @@
1+use std::{
2+ collections::HashSet,
3+ fs,
4+ path::{Path, PathBuf},
5+};
6+
7+use tracing::warn;
8+
9+fn path() -> Option<PathBuf> {
10+ dirs::config_dir().map(|dir| dir.join("yumush").join("mutes"))
11+}
12+
13+fn prefix(account_user_id: &str) -> String {
14+ format!("{account_user_id}\t")
15+}
16+
17+pub fn load(account_user_id: &str) -> HashSet<String> {
18+ let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else {
19+ return HashSet::new();
20+ };
21+ let prefix = prefix(account_user_id);
22+
23+ content
24+ .lines()
25+ .filter_map(|line| line.strip_prefix(&prefix))
26+ .map(String::from)
27+ .collect()
28+}
29+
30+pub fn save(account_user_id: &str, muted: &HashSet<String>) {
31+ let Some(path) = path() else {
32+ return;
33+ };
34+ let prefix = prefix(account_user_id);
35+ let mut content: String = fs::read_to_string(&path)
36+ .unwrap_or_default()
37+ .lines()
38+ .filter(|line| !line.starts_with(&prefix))
39+ .map(|line| format!("{line}\n"))
40+ .collect();
41+ content.extend(
42+ muted
43+ .iter()
44+ .map(|community_id| format!("{prefix}{community_id}\n")),
45+ );
46+
47+ if let Err(error) = write(&path, &content) {
48+ warn!("save mutes failed: {error}");
49+ }
50+}
51+
52+fn write(path: &Path, content: &str) -> std::io::Result<()> {
53+ if let Some(parent) = path.parent() {
54+ fs::create_dir_all(parent)?;
55+ }
56+ fs::write(path, content)
57+}
crates/client/src/network.rsmodified+255 -8
@@ -12,14 +12,14 @@ use common::{
12 error::Error,12 error::Error,
13 event::Event,13 event::Event,
14 model::{14 model::{
15- Account, AdminLogEntry, Attachment, AttachmentInfo, Ban, Community, CommunitySummary,15+ Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community,
16- CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit,16+ CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
17- Overview, Rank, Report, ReportStatus, Role, ServerBan, ServerSettings, SessionInfo, Usage,17+ Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,
18- User, VoiceRoom,18+ ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
19 },19 },
20 network::{20 network::{
21 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,21 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,
22- receive_download_status, receive_event, send_download_request, send_request,22+ receive_download_status, receive_event, send_download_request, send_encoded, send_request,
23 send_stream_kind, send_upload_header,23 send_stream_kind, send_upload_header,
24 },24 },
25 request::{DownloadRequest, Request, UploadHeader},25 request::{DownloadRequest, Request, UploadHeader},
@@ -27,8 +27,8 @@ use common::{
27 validate::{27 validate::{
28 validate_attachment_name, validate_attachment_size, validate_avatar_size,28 validate_attachment_name, validate_attachment_size, validate_avatar_size,
29 validate_community_name, validate_forward, validate_message_body, validate_new_message,29 validate_community_name, validate_forward, validate_message_body, validate_new_message,
30- validate_password, validate_reason, validate_server_settings, validate_status,30+ validate_password, validate_poll, validate_reason, validate_server_settings,
31- validate_username,31+ validate_status, validate_username,
32 },32 },
33 };33 };
34 use quinn::Endpoint;34 use quinn::Endpoint;
@@ -47,7 +47,7 @@ use tracing::{info, warn};
47 use crate::{47 use crate::{
48 ClientConfig,48 ClientConfig,
49 settings::VoiceSettings,49 settings::VoiceSettings,
50- voice::{self, Voice},50+ voice::{self, Voice, VoiceSample},
51 };51 };
52 52
53 fn device_name() -> String {53 fn device_name() -> String {
@@ -96,6 +96,11 @@ enum Command {
96 thumbnail: bool,96 thumbnail: bool,
97 reply: oneshot::Sender<Result<Vec<u8>, Error>>,97 reply: oneshot::Sender<Result<Vec<u8>, Error>>,
98 },98 },
99+ BackupDownload {
100+ name: String,
101+ path: PathBuf,
102+ reply: oneshot::Sender<Result<(), Error>>,
103+ },
99 }104 }
100 105
101 #[derive(Clone)]106 #[derive(Clone)]
@@ -726,6 +731,13 @@ impl NetworkHandle {
726 }731 }
727 }732 }
728 733
734+ pub async fn open_notes(&self) -> Result<Community, Error> {
735+ match self.request(Request::OpenNotes).await? {
736+ Response::Community(community) => Ok(community),
737+ _ => Err(Error::Server),
738+ }
739+ }
740+
729 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Error> {741 pub async fn open_direct(&self, user_id: &str) -> Result<Community, Error> {
730 match self742 match self
731 .request(Request::OpenDirect {743 .request(Request::OpenDirect {
@@ -745,6 +757,17 @@ impl NetworkHandle {
745 }757 }
746 }758 }
747 759
760+ pub async fn read_presences(&self) -> Result<Vec<(String, Presence)>, Error> {
761+ match self.request(Request::ReadPresences).await? {
762+ Response::Presences(presences) => Ok(presences),
763+ _ => Err(Error::Server),
764+ }
765+ }
766+
767+ pub async fn update_presence(&self, presence: Presence) -> Result<(), Error> {
768+ self.done(Request::UpdatePresence { presence }).await
769+ }
770+
748 pub async fn add_friend(&self, user_id: &str) -> Result<(), Error> {771 pub async fn add_friend(&self, user_id: &str) -> Result<(), Error> {
749 self.done(Request::AddFriend {772 self.done(Request::AddFriend {
750 user_id: user_id.to_string(),773 user_id: user_id.to_string(),
@@ -800,6 +823,79 @@ impl NetworkHandle {
800 .await823 .await
801 }824 }
802 825
826+ pub async fn decline_call(&self, community_id: &str) -> Result<(), Error> {
827+ self.done(Request::DeclineCall {
828+ community_id: community_id.to_string(),
829+ })
830+ .await
831+ }
832+
833+ pub async fn react(&self, message_id: &str, emoji: &str) -> Result<(), Error> {
834+ self.done(Request::React {
835+ message_id: message_id.to_string(),
836+ emoji: emoji.to_string(),
837+ })
838+ .await
839+ }
840+
841+ pub async fn pin(&self, message_id: &str, pinned: bool) -> Result<(), Error> {
842+ self.done(Request::Pin {
843+ message_id: message_id.to_string(),
844+ pinned,
845+ })
846+ .await
847+ }
848+
849+ pub async fn pins(&self, community_id: &str) -> Result<Vec<Message>, Error> {
850+ match self
851+ .request(Request::Pins {
852+ community_id: community_id.to_string(),
853+ })
854+ .await?
855+ {
856+ Response::Messages(messages) => Ok(messages),
857+ _ => Err(Error::Server),
858+ }
859+ }
860+
861+ pub async fn create_poll(
862+ &self,
863+ community_id: &str,
864+ question: &str,
865+ options: Vec<String>,
866+ multiple: bool,
867+ ) -> Result<Message, Error> {
868+ validate_poll(question, &options)?;
869+
870+ match self
871+ .request(Request::CreatePoll {
872+ community_id: community_id.to_string(),
873+ question: question.to_string(),
874+ options,
875+ multiple,
876+ })
877+ .await?
878+ {
879+ Response::Message(message) => Ok(message),
880+ _ => Err(Error::Server),
881+ }
882+ }
883+
884+ pub async fn vote(&self, message_id: &str, positions: Vec<u32>) -> Result<(), Error> {
885+ self.done(Request::Vote {
886+ message_id: message_id.to_string(),
887+ positions,
888+ })
889+ .await
890+ }
891+
892+ pub async fn close_poll(&self, message_id: &str) -> Result<(), Error> {
893+ self.done(Request::ClosePoll {
894+ message_id: message_id.to_string(),
895+ })
896+ .await
897+ }
898+
803 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Error> {899 pub async fn report_message(&self, message_id: &str, reason: &str) -> Result<(), Error> {
804 validate_reason(Some(reason))?;900 validate_reason(Some(reason))?;
805 901
@@ -858,6 +954,20 @@ impl NetworkHandle {
858 }954 }
859 }955 }
860 956
957+ pub async fn search_community(
958+ &self,
959+ community_id: String,
960+ text: String,
961+ ) -> Result<Vec<MessageHit>, Error> {
962+ match self
963+ .request(Request::SearchCommunity { community_id, text })
964+ .await?
965+ {
966+ Response::MessageHits(hits) => Ok(hits),
967+ _ => Err(Error::Server),
968+ }
969+ }
970+
861 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Error> {971 pub async fn storage_usage(&self) -> Result<(Vec<Usage>, Vec<CommunityUsage>), Error> {
862 match self.request(Request::StorageUsage).await? {972 match self.request(Request::StorageUsage).await? {
863 Response::StorageUsage { users, communities } => Ok((users, communities)),973 Response::StorageUsage { users, communities } => Ok((users, communities)),
@@ -865,6 +975,27 @@ impl NetworkHandle {
865 }975 }
866 }976 }
867 977
978+ pub async fn create_backup(&self) -> Result<BackupInfo, Error> {
979+ match self.request(Request::CreateBackup).await? {
980+ Response::Backup(backup) => Ok(backup),
981+ _ => Err(Error::Server),
982+ }
983+ }
984+
985+ pub async fn backups(&self) -> Result<Vec<BackupInfo>, Error> {
986+ match self.request(Request::Backups).await? {
987+ Response::Backups(backups) => Ok(backups),
988+ _ => Err(Error::Server),
989+ }
990+ }
991+
992+ pub async fn delete_backup(&self, name: &str) -> Result<(), Error> {
993+ self.done(Request::DeleteBackup {
994+ name: name.to_string(),
995+ })
996+ .await
997+ }
998+
868 pub async fn attachments(999 pub async fn attachments(
869 &self,1000 &self,
870 user_id: Option<String>,1001 user_id: Option<String>,
@@ -943,6 +1074,21 @@ impl NetworkHandle {
943 response.await.map_err(|_| Error::ChannelClosed)?1074 response.await.map_err(|_| Error::ChannelClosed)?
944 }1075 }
945 1076
1077+ pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> {
1078+ let (reply, response) = oneshot::channel();
1079+
1080+ self.command_sender
1081+ .send(Command::BackupDownload {
1082+ name: name.to_string(),
1083+ path,
1084+ reply,
1085+ })
1086+ .await
1087+ .map_err(|_| Error::ChannelClosed)?;
1088+
1089+ response.await.map_err(|_| Error::ChannelClosed)?
1090+ }
1091+
946 pub async fn read_messages(1092 pub async fn read_messages(
947 &self,1093 &self,
948 community_id: &str,1094 community_id: &str,
@@ -960,6 +1106,26 @@ impl NetworkHandle {
960 }1106 }
961 }1107 }
962 1108
1109+ pub async fn unreads(&self) -> Result<Vec<Unread>, Error> {
1110+ match self.request(Request::Unreads).await? {
1111+ Response::Unreads(unreads) => Ok(unreads),
1112+ _ => Err(Error::Server),
1113+ }
1114+ }
1115+
1116+ pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> {
1117+ match self
1118+ .request(Request::MarkRead {
1119+ community_id: community_id.to_string(),
1120+ message_id: message_id.to_string(),
1121+ })
1122+ .await?
1123+ {
1124+ Response::Done => Ok(()),
1125+ _ => Err(Error::Server),
1126+ }
1127+ }
1128+
963 pub async fn update_status(&self, status: &str) -> Result<User, Error> {1129 pub async fn update_status(&self, status: &str) -> Result<User, Error> {
964 validate_status(status)?;1130 validate_status(status)?;
965 1131
@@ -1035,6 +1201,18 @@ impl NetworkHandle {
1035 }1201 }
1036 }1202 }
1037 1203
1204+ pub async fn typing(&self, community_id: &str) -> Result<(), Error> {
1205+ match self
1206+ .request(Request::Typing {
1207+ community_id: community_id.to_string(),
1208+ })
1209+ .await?
1210+ {
1211+ Response::Done => Ok(()),
1212+ _ => Err(Error::Server),
1213+ }
1214+ }
1215+
1038 pub async fn leave_voice(&self) -> Result<(), Error> {1216 pub async fn leave_voice(&self) -> Result<(), Error> {
1039 match self.request(Request::LeaveVoice).await? {1217 match self.request(Request::LeaveVoice).await? {
1040 Response::Done => Ok(()),1218 Response::Done => Ok(()),
@@ -1042,6 +1220,18 @@ impl NetworkHandle {
1042 }1220 }
1043 }1221 }
1044 1222
1223+ pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> {
1224+ match self
1225+ .request(Request::ReadCommunity {
1226+ community_id: community_id.to_string(),
1227+ })
1228+ .await?
1229+ {
1230+ Response::Community(community) => Ok(community),
1231+ _ => Err(Error::Server),
1232+ }
1233+ }
1234+
1045 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Error> {1235 pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Error> {
1046 match self1236 match self
1047 .request(Request::VoiceParticipants {1237 .request(Request::VoiceParticipants {
@@ -1133,6 +1323,14 @@ impl NetworkHandle {
1133 voice::play_chime(&self.voice_settings.lock().unwrap());1323 voice::play_chime(&self.voice_settings.lock().unwrap());
1134 }1324 }
1135 1325
1326+ pub fn play_notification(&self) {
1327+ voice::play_yumush(&self.voice_settings.lock().unwrap());
1328+ }
1329+
1330+ pub fn play_ring(&self) {
1331+ voice::play_ring(&self.voice_settings.lock().unwrap());
1332+ }
1333+
1136 pub fn stop_mic_test(&self) {1334 pub fn stop_mic_test(&self) {
1137 self.mic_test.lock().unwrap().take();1335 self.mic_test.lock().unwrap().take();
1138 }1336 }
@@ -1142,6 +1340,10 @@ impl NetworkHandle {
1142 live.or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db))1340 live.or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db))
1143 }1341 }
1144 1342
1343+ pub fn voice_sample(&self) -> Option<VoiceSample> {
1344+ self.voice.lock().unwrap().as_ref().map(Voice::sample)
1345+ }
1346+
1145 pub fn set_talking(&self, talking: bool) {1347 pub fn set_talking(&self, talking: bool) {
1146 if let Some(voice) = self.voice.lock().unwrap().as_ref() {1348 if let Some(voice) = self.voice.lock().unwrap().as_ref() {
1147 voice.set_talking(talking);1349 voice.set_talking(talking);
@@ -1378,6 +1580,44 @@ async fn upload(
1378 }1580 }
1379 }1581 }
1380 1582
1583+async fn backup_download(
1584+ connection: &quinn::Connection,
1585+ name: &str,
1586+ path: &Path,
1587+) -> Result<(), Error> {
1588+ let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
1589+ send_stream_kind(StreamKind::Backup, &mut send_stream).await?;
1590+ send_encoded(
1591+ &Request::DownloadBackup {
1592+ name: name.to_string(),
1593+ },
1594+ &mut send_stream,
1595+ )
1596+ .await?;
1597+ send_stream.finish()?;
1598+
1599+ match receive_download_status(&mut receive_stream).await? {
1600+ DownloadStatus::Error => {
1601+ Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?)
1602+ }
1603+ DownloadStatus::Ok => {
1604+ let mut length_bytes = [0u8; 8];
1605+ receive_stream.read_exact(&mut length_bytes).await?;
1606+ let length = u64::from_le_bytes(length_bytes);
1607+
1608+ let mut file = tokio::fs::File::create(path).await?;
1609+ let copied = tokio::io::copy(&mut receive_stream, &mut file).await?;
1610+ if copied != length {
1611+ return Err(Error::Network(format!(
1612+ "backup truncated ({copied} < {length})"
1613+ )));
1614+ }
1615+
1616+ Ok(())
1617+ }
1618+ }
1619+}
1620+
1381 async fn download(1621 async fn download(
1382 connection: &quinn::Connection,1622 connection: &quinn::Connection,
1383 attachment_id: &str,1623 attachment_id: &str,
@@ -1544,6 +1784,13 @@ async fn actor(
1544 let _ = reply.send(download(&connection, &attachment_id, thumbnail).await);1784 let _ = reply.send(download(&connection, &attachment_id, thumbnail).await);
1545 });1785 });
1546 }1786 }
1787+ Some(Command::BackupDownload { name, path, reply }) => {
1788+ let connection = connection.clone();
1789+
1790+ tokio::spawn(async move {
1791+ let _ = reply.send(backup_download(&connection, &name, &path).await);
1792+ });
1793+ }
1547 None => break 'session,1794 None => break 'session,
1548 },1795 },
1549 Some((epoch, session_token)) = token_receiver.recv() => {1796 Some((epoch, session_token)) = token_receiver.recv() => {
crates/client/src/settings.rsmodified+3 -0
@@ -124,6 +124,7 @@ pub struct Settings {
124 pub theme: ThemeChoice,124 pub theme: ThemeChoice,
125 pub font_size: FontSize,125 pub font_size: FontSize,
126 pub voice: VoiceSettings,126 pub voice: VoiceSettings,
127+ pub close_to_tray: bool,
127 }128 }
128 129
129 fn path() -> Option<PathBuf> {130 fn path() -> Option<PathBuf> {
@@ -179,6 +180,7 @@ pub fn load() -> Settings {
179 .and_then(|value| FontSize::parse(&value))180 .and_then(|value| FontSize::parse(&value))
180 .unwrap_or(FontSize::Medium),181 .unwrap_or(FontSize::Medium),
181 voice,182 voice,
183+ close_to_tray: text("close_to_tray").is_none_or(|value| value != "false"),
182 }184 }
183 }185 }
184 186
@@ -204,6 +206,7 @@ pub fn save(settings: &Settings) {
204 let content = [206 let content = [
205 line("theme", settings.theme.name()),207 line("theme", settings.theme.name()),
206 line("font_size", settings.font_size.name()),208 line("font_size", settings.font_size.name()),
209+ line("close_to_tray", settings.close_to_tray),
207 line("voice.sensitivity", voice.sensitivity_db),210 line("voice.sensitivity", voice.sensitivity_db),
208 line("voice.input_volume", voice.input_volume),211 line("voice.input_volume", voice.input_volume),
209 line("voice.output_volume", voice.output_volume),212 line("voice.output_volume", voice.output_volume),
crates/client/src/tray.rsadded+205 -0
@@ -0,0 +1,205 @@
1+use tokio::sync::mpsc;
2+
3+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4+pub enum TrayAction {
5+ Show,
6+ Quit,
7+}
8+
9+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10+pub struct TrayState {
11+ pub messages: u32,
12+ pub mentions: u32,
13+}
14+
15+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16+enum Badge {
17+ None,
18+ Unread,
19+ Mention,
20+}
21+
22+impl TrayState {
23+ fn badge(self) -> Badge {
24+ match (self.messages, self.mentions) {
25+ (_, 1..) => Badge::Mention,
26+ (1.., _) => Badge::Unread,
27+ _ => Badge::None,
28+ }
29+ }
30+}
31+
32+#[derive(Clone)]
33+pub struct TrayHandle(mpsc::UnboundedSender<TrayState>);
34+
35+impl TrayHandle {
36+ pub fn set(&self, state: TrayState) {
37+ let _ = self.0.send(state);
38+ }
39+}
40+
41+#[cfg(target_os = "linux")]
42+pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
43+ use ksni::TrayMethods;
44+ use tracing::warn;
45+
46+ let (sender, receiver) = mpsc::unbounded_channel();
47+ let (state_sender, mut state_receiver) = mpsc::unbounded_channel();
48+ let tray = Tray {
49+ sender,
50+ state: TrayState::default(),
51+ };
52+
53+ let _ = std::thread::Builder::new()
54+ .name("tray".to_string())
55+ .spawn(move || {
56+ let runtime = match tokio::runtime::Builder::new_current_thread()
57+ .enable_all()
58+ .build()
59+ {
60+ Ok(runtime) => runtime,
61+ Err(error) => {
62+ warn!("tray runtime: {error}");
63+ return;
64+ }
65+ };
66+ runtime.block_on(async move {
67+ match tray.assume_sni_available(true).spawn().await {
68+ Ok(handle) => {
69+ while let Some(state) = state_receiver.recv().await {
70+ handle.update(|tray| tray.state = state).await;
71+ }
72+ std::future::pending::<()>().await
73+ }
74+ Err(error) => warn!("tray: {error}"),
75+ }
76+ });
77+ });
78+
79+ (receiver, TrayHandle(state_sender))
80+}
81+
82+#[cfg(not(target_os = "linux"))]
83+pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
84+ (
85+ mpsc::unbounded_channel().1,
86+ TrayHandle(mpsc::unbounded_channel().0),
87+ )
88+}
89+
90+#[cfg(target_os = "linux")]
91+struct Tray {
92+ sender: mpsc::UnboundedSender<TrayAction>,
93+ state: TrayState,
94+}
95+
96+#[cfg(target_os = "linux")]
97+impl ksni::Tray for Tray {
98+ fn id(&self) -> String {
99+ crate::NAME.to_string()
100+ }
101+
102+ fn title(&self) -> String {
103+ crate::NAME.to_string()
104+ }
105+
106+ fn icon_pixmap(&self) -> Vec<ksni::Icon> {
107+ vec![icon(self.state.badge())]
108+ }
109+
110+ fn status(&self) -> ksni::Status {
111+ match self.state.badge() {
112+ Badge::Mention => ksni::Status::NeedsAttention,
113+ _ => ksni::Status::Active,
114+ }
115+ }
116+
117+ fn tool_tip(&self) -> ksni::ToolTip {
118+ let description = match self.state.badge() {
119+ Badge::None => String::new(),
120+ _ => format!(
121+ "{} unread · {} mentions",
122+ self.state.messages, self.state.mentions
123+ ),
124+ };
125+ ksni::ToolTip {
126+ title: crate::NAME.to_string(),
127+ description,
128+ ..Default::default()
129+ }
130+ }
131+
132+ fn activate(&mut self, _x: i32, _y: i32) {
133+ let _ = self.sender.send(TrayAction::Show);
134+ }
135+
136+ fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
137+ use ksni::menu::StandardItem;
138+
139+ [("Show", TrayAction::Show), ("Quit", TrayAction::Quit)]
140+ .into_iter()
141+ .map(|(label, action)| {
142+ StandardItem {
143+ label: label.to_string(),
144+ activate: Box::new(move |tray: &mut Self| {
145+ let _ = tray.sender.send(action);
146+ }),
147+ ..Default::default()
148+ }
149+ .into()
150+ })
151+ .collect()
152+ }
153+}
154+
155+#[cfg(target_os = "linux")]
156+const ICON_SIZE: i32 = 32;
157+#[cfg(target_os = "linux")]
158+const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2];
159+#[cfg(target_os = "linux")]
160+const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)];
161+#[cfg(target_os = "linux")]
162+const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0);
163+#[cfg(target_os = "linux")]
164+const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6];
165+#[cfg(target_os = "linux")]
166+const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44];
167+
168+#[cfg(target_os = "linux")]
169+fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 {
170+ let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt();
171+ (radius - distance + 0.5).clamp(0.0, 1.0)
172+}
173+
174+#[cfg(target_os = "linux")]
175+fn icon(badge: Badge) -> ksni::Icon {
176+ let dot = match badge {
177+ Badge::None => None,
178+ Badge::Unread => Some(UNREAD_COLOR),
179+ Badge::Mention => Some(MENTION_COLOR),
180+ };
181+ let data = (0..ICON_SIZE * ICON_SIZE)
182+ .flat_map(|index| {
183+ let x = (index % ICON_SIZE) as f32 + 0.5;
184+ let y = (index / ICON_SIZE) as f32 + 0.5;
185+ let base = ICON_DROPS
186+ .iter()
187+ .map(|drop| coverage(x, y, *drop))
188+ .fold(0.0, f32::max);
189+ let ([red, green, blue], alpha) = match dot {
190+ Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)),
191+ Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => {
192+ (ICON_COLOR, 0.0)
193+ }
194+ _ => (ICON_COLOR, base),
195+ };
196+ [(alpha * 255.0) as u8, red, green, blue]
197+ })
198+ .collect();
199+
200+ ksni::Icon {
201+ width: ICON_SIZE,
202+ height: ICON_SIZE,
203+ data,
204+ }
205+}
crates/client/src/voice/engine.rsmodified+74 -1
@@ -71,6 +71,16 @@ struct Speaker {
71 first_sequence: u32,71 first_sequence: u32,
72 previous_transit: Option<f32>,72 previous_transit: Option<f32>,
73 jitter_ms: f32,73 jitter_ms: f32,
74+ highest: u32,
75+}
76+
77+#[derive(Debug, Clone, Copy, Default)]
78+pub struct Traffic {
79+ pub jitter_ms: f32,
80+ pub buffer_ms: f32,
81+ pub loss: f32,
82+ pub up_kbps: f32,
83+ pub down_kbps: f32,
74 }84 }
75 85
76 impl Speaker {86 impl Speaker {
@@ -87,6 +97,7 @@ impl Speaker {
87 first_sequence: sequence,97 first_sequence: sequence,
88 previous_transit: None,98 previous_transit: None,
89 jitter_ms: 0.0,99 jitter_ms: 0.0,
100+ highest: sequence.wrapping_sub(1),
90 }101 }
91 }102 }
92 103
@@ -161,6 +172,11 @@ pub struct Engine {
161 sending: bool,172 sending: bool,
162 level_db: f32,173 level_db: f32,
163 speakers: HashMap<String, Speaker>,174 speakers: HashMap<String, Speaker>,
175+ sent_bytes: usize,
176+ received_bytes: usize,
177+ expected: u32,
178+ arrived: u32,
179+ counting_since: Instant,
164 }180 }
165 181
166 impl Default for Engine {182 impl Default for Engine {
@@ -187,6 +203,11 @@ impl Engine {
187 sending: false,203 sending: false,
188 level_db: SILENT_DB,204 level_db: SILENT_DB,
189 speakers: HashMap::new(),205 speakers: HashMap::new(),
206+ sent_bytes: 0,
207+ received_bytes: 0,
208+ expected: 0,
209+ arrived: 0,
210+ counting_since: Instant::now(),
190 }211 }
191 }212 }
192 213
@@ -239,7 +260,9 @@ impl Engine {
239 continue;260 continue;
240 };261 };
241 262
242- packets.push(encode_packet(self.sequence, &payload[..length]));263+ let packet = encode_packet(self.sequence, &payload[..length]);
264+ self.sent_bytes += packet.len();
265+ packets.push(packet);
243 self.sequence = self.sequence.wrapping_add(1);266 self.sequence = self.sequence.wrapping_add(1);
244 }267 }
245 268
@@ -251,6 +274,7 @@ impl Engine {
251 return;274 return;
252 };275 };
253 let now = Instant::now();276 let now = Instant::now();
277+ self.received_bytes += datagram.len();
254 278
255 let stale = self279 let stale = self
256 .speakers280 .speakers
@@ -268,6 +292,11 @@ impl Engine {
268 if payload.is_empty() || sequence < speaker.next {292 if payload.is_empty() || sequence < speaker.next {
269 return;293 return;
270 }294 }
295+ if sequence.wrapping_sub(speaker.highest) < u32::MAX / 2 {
296+ self.expected += sequence.wrapping_sub(speaker.highest);
297+ speaker.highest = sequence;
298+ }
299+ self.arrived += 1;
271 300
272 let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0301 let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0
273 - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS;302 - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS;
@@ -312,6 +341,50 @@ impl Engine {
312 .collect()341 .collect()
313 }342 }
314 343
344+ pub fn take_traffic(&mut self) -> Traffic {
345+ let now = Instant::now();
346+ let seconds = now
347+ .duration_since(self.counting_since)
348+ .as_secs_f32()
349+ .max(f32::EPSILON);
350+ let heard = self
351+ .speakers
352+ .values()
353+ .filter(|speaker| now.duration_since(speaker.last_heard) <= RESTART_AFTER);
354+ let (jitter_ms, buffer_ms) = heard.fold((0.0f32, 0.0f32), |(jitter, buffer), speaker| {
355+ (
356+ jitter.max(speaker.jitter_ms),
357+ buffer.max(speaker.target() as f32 * FRAME_MS),
358+ )
359+ });
360+ let loss = if self.expected == 0 {
361+ 0.0
362+ } else {
363+ 1.0 - (self.arrived as f32 / self.expected as f32).min(1.0)
364+ };
365+ let traffic = Traffic {
366+ jitter_ms,
367+ buffer_ms,
368+ loss,
369+ up_kbps: self.sent_bytes as f32 * 8.0 / 1000.0 / seconds,
370+ down_kbps: self.received_bytes as f32 * 8.0 / 1000.0 / seconds,
371+ };
372+
373+ self.sent_bytes = 0;
374+ self.received_bytes = 0;
375+ self.expected = 0;
376+ self.arrived = 0;
377+ self.counting_since = now;
378+ traffic
379+ }
380+
381+ pub fn bitrate_kbps(&self) -> u32 {
382+ match self.profile {
383+ Profile::Voice => VOICE_BITRATE as u32 / 1000,
384+ Profile::Music => MUSIC_BITRATE as u32 / 1000,
385+ }
386+ }
387+
315 pub fn forget(&mut self, user_id: &str) {388 pub fn forget(&mut self, user_id: &str) {
316 self.speakers.remove(user_id);389 self.speakers.remove(user_id);
317 }390 }
crates/client/src/voice/mod.rsmodified+157 -6
@@ -21,7 +21,7 @@ pub mod engine;
21 21
22 use crate::settings::{Activation, VoiceSettings};22 use crate::settings::{Activation, VoiceSettings};
23 use audio::{Audio, Choice};23 use audio::{Audio, Choice};
24-use engine::{Engine, SILENT_DB};24+use engine::{Engine, SILENT_DB, Traffic};
25 25
26 const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2;26 const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2;
27 const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2;27 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)];
32 pub type Capture = Arc<Mutex<Producer<f32>>>;32 pub type Capture = Arc<Mutex<Producer<f32>>>;
33 pub type Playback = Arc<Mutex<Consumer<f32>>>;33 pub type Playback = Arc<Mutex<Consumer<f32>>>;
34 34
35+#[derive(Debug, Clone, Copy, Default)]
36+pub struct VoiceSample {
37+ pub ping_ms: f32,
38+ pub traffic: Traffic,
39+ pub bitrate_kbps: u32,
40+}
41+
35 pub struct Voice {42 pub struct Voice {
36 engine: Arc<Mutex<Engine>>,43 engine: Arc<Mutex<Engine>>,
44+ connection: Option<Connection>,
37 stop: Arc<AtomicBool>,45 stop: Arc<AtomicBool>,
38 worker: Option<JoinHandle<()>>,46 worker: Option<JoinHandle<()>>,
39 capture: Capture,47 capture: Capture,
@@ -55,6 +63,7 @@ pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice
55 playback.clone(),63 playback.clone(),
56 settings.choice.clone(),64 settings.choice.clone(),
57 );65 );
66+ let link = connection.clone();
58 let worker = {67 let worker = {
59 let engine = engine.clone();68 let engine = engine.clone();
60 let stop = stop.clone();69 let stop = stop.clone();
@@ -75,6 +84,7 @@ pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice
75 84
76 let mut voice = Voice {85 let mut voice = Voice {
77 engine,86 engine,
87+ connection: link,
78 stop,88 stop,
79 worker,89 worker,
80 capture,90 capture,
@@ -88,25 +98,150 @@ pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice
88 98
89 pub fn play_chime(settings: &VoiceSettings) {99 pub fn play_chime(settings: &VoiceSettings) {
90 let rate = VOICE_SAMPLE_RATE as f32;100 let rate = VOICE_SAMPLE_RATE as f32;
91- let gain = 0.3 * settings.output_volume / 100.0;
92 let mut samples = Vec::new();101 let mut samples = Vec::new();
93 for (frequency, seconds) in CHIME {102 for (frequency, seconds) in CHIME {
94 let length = (rate * seconds) as usize;103 let length = (rate * seconds) as usize;
95 samples.extend((0..length).map(|index| {104 samples.extend((0..length).map(|index| {
96 let time = index as f32 / rate;105 let time = index as f32 / rate;
97 let fade = (1.0 - index as f32 / length as f32).powi(2);106 let fade = (1.0 - index as f32 / length as f32).powi(2);
98- (std::f32::consts::TAU * frequency * time).sin() * fade * gain107+ (std::f32::consts::TAU * frequency * time).sin() * fade
99 }));108 }));
100 }109 }
110+ play(samples, 0.3, settings);
111+}
112+
113+pub fn play_yumush(settings: &VoiceSettings) {
114+ play(plops(&YUMUSH, YUMUSH_SECONDS), 0.35, settings);
115+}
116+
117+pub fn play_ring(settings: &VoiceSettings) {
118+ play(plops(&RING, RING_SECONDS), 0.35, settings);
119+}
120+
121+fn plops(plops: &[Plop], seconds: f32) -> Vec<f32> {
122+ let rate = VOICE_SAMPLE_RATE as f32;
123+ let mut dry = vec![0.0; (rate * seconds) as usize];
124+ for plop in plops {
125+ plop.add(&mut dry, rate);
126+ }
127+ reverb(dry, rate)
128+}
129+
130+const YUMUSH_SECONDS: f32 = 0.9;
131+const RING_SECONDS: f32 = 1.3;
132+const DETUNE: [f32; 2] = [0.998, 1.002];
133+const PITCH_SETTLE: f32 = 0.04;
134+const ATTACK: f32 = 0.004;
135+const COMB_SECONDS: [f32; 4] = [0.0297, 0.0371, 0.0411, 0.0437];
136+const COMB_FEEDBACK: f32 = 0.72;
137+const COMB_DAMPING: f32 = 0.35;
138+const REVERB_WET: f32 = 0.25;
139+
140+struct Plop {
141+ start: f32,
142+ from: f32,
143+ rise: f32,
144+ decay: f32,
145+ gain: f32,
146+}
147+
148+const YUMUSH: [Plop; 2] = [
149+ Plop {
150+ start: 0.0,
151+ from: 620.0,
152+ rise: 0.6,
153+ decay: 0.07,
154+ gain: 1.0,
155+ },
156+ Plop {
157+ start: 0.13,
158+ from: 400.0,
159+ rise: 0.45,
160+ decay: 0.14,
161+ gain: 0.9,
162+ },
163+];
164+
165+const RING: [Plop; 4] = [
166+ Plop {
167+ start: 0.0,
168+ from: 400.0,
169+ rise: 0.45,
170+ decay: 0.1,
171+ gain: 0.9,
172+ },
173+ Plop {
174+ start: 0.14,
175+ from: 500.0,
176+ rise: 0.45,
177+ decay: 0.1,
178+ gain: 0.9,
179+ },
180+ Plop {
181+ start: 0.28,
182+ from: 620.0,
183+ rise: 0.6,
184+ decay: 0.12,
185+ gain: 1.0,
186+ },
187+ Plop {
188+ start: 0.5,
189+ from: 620.0,
190+ rise: 0.6,
191+ decay: 0.2,
192+ gain: 0.8,
193+ },
194+];
195+
196+impl Plop {
197+ fn add(&self, out: &mut [f32], rate: f32) {
198+ let start = (self.start * rate) as usize;
199+ for detune in DETUNE {
200+ let mut phase = 0.0;
201+ for (index, sample) in out.iter_mut().enumerate().skip(start) {
202+ let time = (index - start) as f32 / rate;
203+ let frequency =
204+ self.from * detune * (1.0 + self.rise * (1.0 - (-time / PITCH_SETTLE).exp()));
205+ phase += std::f32::consts::TAU * frequency / rate;
206+ let envelope = (time / ATTACK).min(1.0) * (-time / self.decay).exp();
207+ *sample += phase.sin() * envelope * self.gain / DETUNE.len() as f32;
208+ }
209+ }
210+ }
211+}
212+
213+fn reverb(dry: Vec<f32>, rate: f32) -> Vec<f32> {
214+ let mut wet = vec![0.0; dry.len()];
215+ for seconds in COMB_SECONDS {
216+ let mut buffer = vec![0.0; (rate * seconds) as usize];
217+ let mut filtered = 0.0;
218+ for (index, (input, output)) in dry.iter().zip(wet.iter_mut()).enumerate() {
219+ let slot = index % buffer.len();
220+ let delayed = buffer[slot];
221+ filtered = delayed * (1.0 - COMB_DAMPING) + filtered * COMB_DAMPING;
222+ buffer[slot] = input + filtered * COMB_FEEDBACK;
223+ *output += delayed / COMB_SECONDS.len() as f32;
224+ }
225+ }
226+
227+ dry.iter()
228+ .zip(wet)
229+ .map(|(dry, wet)| dry + wet * REVERB_WET)
230+ .collect()
231+}
232+
233+fn play(samples: Vec<f32>, gain: f32, settings: &VoiceSettings) {
234+ let rate = VOICE_SAMPLE_RATE as f32;
235+ let gain = gain * settings.output_volume / 100.0;
101 let duration = Duration::from_secs_f32(samples.len() as f32 / rate + 0.3);236 let duration = Duration::from_secs_f32(samples.len() as f32 / rate + 0.3);
102- let (mut producer, consumer) = RingBuffer::new(samples.len());237+ let (mut producer, consumer) = RingBuffer::new(samples.len().max(1));
103 for sample in samples {238 for sample in samples {
104- let _ = producer.push(sample);239+ let _ = producer.push(sample * gain);
105 }240 }
106 let choice = settings.choice.clone();241 let choice = settings.choice.clone();
107 242
108 let _ = std::thread::Builder::new()243 let _ = std::thread::Builder::new()
109- .name("chime".to_string())244+ .name("sound".to_string())
110 .spawn(move || {245 .spawn(move || {
111 let _audio = audio::start(None, Arc::new(Mutex::new(consumer)), choice);246 let _audio = audio::start(None, Arc::new(Mutex::new(consumer)), choice);
112 std::thread::sleep(duration);247 std::thread::sleep(duration);
@@ -197,6 +332,22 @@ impl Voice {
197 .map_or(SILENT_DB, |engine| engine.level_db())332 .map_or(SILENT_DB, |engine| engine.level_db())
198 }333 }
199 334
335+ pub fn sample(&self) -> VoiceSample {
336+ let ping_ms = self
337+ .connection
338+ .as_ref()
339+ .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0);
340+ let Ok(mut engine) = self.engine.lock() else {
341+ return VoiceSample::default();
342+ };
343+
344+ VoiceSample {
345+ ping_ms,
346+ traffic: engine.take_traffic(),
347+ bitrate_kbps: engine.bitrate_kbps(),
348+ }
349+ }
350+
200 pub fn set_muted(&self, muted: bool) {351 pub fn set_muted(&self, muted: bool) {
201 if let Ok(mut engine) = self.engine.lock() {352 if let Ok(mut engine) = self.engine.lock() {
202 engine.set_muted(muted);353 engine.set_muted(muted);
crates/common/src/constant.rsmodified+5 -0
@@ -7,6 +7,11 @@ pub const MINIMUM_MESSAGE_LENGTH: usize = 1;
7 pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16;7 pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16;
8 pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3;8 pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3;
9 pub const MESSAGE_PAGE_LIMIT: usize = 50;9 pub const MESSAGE_PAGE_LIMIT: usize = 50;
10+pub const REACTIONS: [&str; 8] = ["👍", "❤️", "😂", "😮", "😢", "🔥", "🎉", "👀"];
11+pub const MINIMUM_POLL_OPTIONS: usize = 2;
12+pub const MAXIMUM_POLL_OPTIONS: usize = 10;
13+pub const MAXIMUM_POLL_QUESTION_LENGTH: usize = 128;
14+pub const MAXIMUM_POLL_OPTION_LENGTH: usize = 64;
10 pub const LOG_PAGE_LIMIT: u32 = 500;15 pub const LOG_PAGE_LIMIT: u32 = 500;
11 pub const AVATAR_SIZE: u32 = 128;16 pub const AVATAR_SIZE: u32 = 128;
12 pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024;17 pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024;
crates/common/src/error.rsmodified+4 -2
@@ -160,6 +160,8 @@ pub enum Error {
160 AttachmentLimit(InvalidInput),160 AttachmentLimit(InvalidInput),
161 #[error("device: {0}")]161 #[error("device: {0}")]
162 Device(InvalidInput),162 Device(InvalidInput),
163+ #[error("backup name: {0}")]
164+ BackupName(InvalidInput),
163 #[error("banned")]165 #[error("banned")]
164 Banned,166 Banned,
165 #[error("maintenance")]167 #[error("maintenance")]
@@ -172,8 +174,8 @@ pub enum Error {
172 Announcement(InvalidInput),174 Announcement(InvalidInput),
173 #[error("limit reached")]175 #[error("limit reached")]
174 LimitReached,176 LimitReached,
175- #[error("too many requests")]177+ #[error("too many requests, retry in {retry_after_seconds}s")]
176- RateLimited,178+ RateLimited { retry_after_seconds: u64 },
177 }179 }
178 180
179 from_display! { Error {181 from_display! { Error {
crates/common/src/event.rsmodified+26 -1
@@ -1,6 +1,6 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::model::{Community, Friends, Invitation, Member, Message, Rank, User};3+use crate::model::{Community, Friends, Invitation, Member, Message, Presence, Rank, User};
4 4
5 #[derive(Debug, Clone, Encode, Decode)]5 #[derive(Debug, Clone, Encode, Decode)]
6 pub enum Event {6 pub enum Event {
@@ -37,6 +37,10 @@ pub enum Event {
37 user_id: String,37 user_id: String,
38 },38 },
39 UserUpdated(User),39 UserUpdated(User),
40+ PresenceChanged {
41+ user_id: String,
42+ presence: Presence,
43+ },
40 VoiceJoined {44 VoiceJoined {
41 community_id: String,45 community_id: String,
42 user_id: String,46 user_id: String,
@@ -53,4 +57,25 @@ pub enum Event {
53 Announcement {57 Announcement {
54 text: String,58 text: String,
55 },59 },
60+ Typing {
61+ community_id: String,
62+ user_id: String,
63+ },
64+}
65+
66+impl Event {
67+ pub fn community_id(&self) -> Option<&str> {
68+ match self {
69+ Self::MessageCreated(message)
70+ | Self::MessageUpdated(message)
71+ | Self::MessageDeleted(message) => Some(&message.community_id),
72+ Self::CommunityUpdated(community) => Some(&community.id),
73+ Self::MemberJoined { community_id, .. }
74+ | Self::MemberLeft { community_id, .. }
75+ | Self::RankChanged { community_id, .. }
76+ | Self::VoiceJoined { community_id, .. }
77+ | Self::VoiceLeft { community_id, .. } => Some(community_id),
78+ _ => None,
79+ }
80+ }
56 }81 }
crates/common/src/model.rsmodified+138 -5
@@ -33,6 +33,39 @@ impl Role {
33 }33 }
34 }34 }
35 35
36+#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
37+pub enum Presence {
38+ Online,
39+ Busy,
40+ Offline,
41+}
42+
43+impl Presence {
44+ pub const ALL: [Self; 3] = [Presence::Online, Presence::Busy, Presence::Offline];
45+
46+ pub fn as_str(self) -> &'static str {
47+ match self {
48+ Presence::Online => "online",
49+ Presence::Busy => "busy",
50+ Presence::Offline => "offline",
51+ }
52+ }
53+
54+ pub fn label(self) -> &'static str {
55+ match self {
56+ Presence::Online => "Online",
57+ Presence::Busy => "Busy",
58+ Presence::Offline => "Offline",
59+ }
60+ }
61+
62+ pub fn parse(text: &str) -> Option<Self> {
63+ Self::ALL
64+ .into_iter()
65+ .find(|presence| presence.as_str() == text)
66+ }
67+}
68+
36 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]69 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
37 pub enum Rank {70 pub enum Rank {
38 Member,71 Member,
@@ -111,6 +144,7 @@ pub struct Member {
111 pub enum CommunityKind {144 pub enum CommunityKind {
112 Group,145 Group,
113 Direct { peer: User },146 Direct { peer: User },
147+ Notes,
114 }148 }
115 149
116 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]150 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
@@ -122,6 +156,19 @@ pub struct Community {
122 pub voice_enabled: bool,156 pub voice_enabled: bool,
123 }157 }
124 158
159+#[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)]
160+pub struct Unread {
161+ pub community_id: String,
162+ pub messages: u32,
163+ pub mentions: u32,
164+ pub last_read: Option<String>,
165+}
166+
167+pub fn mentions(body: &str, username: &str) -> bool {
168+ body.to_lowercase()
169+ .contains(&format!("@{}", username.to_lowercase()))
170+}
171+
125 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]172 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
126 pub struct VoiceRoom {173 pub struct VoiceRoom {
127 pub community_id: String,174 pub community_id: String,
@@ -198,6 +245,9 @@ pub enum AdminAction {
198 GhostDisabled,245 GhostDisabled,
199 GhostVisit,246 GhostVisit,
200 GhostVoice { seconds: u64 },247 GhostVoice { seconds: u64 },
248+ BackupCreated { name: String },
249+ BackupDeleted { name: String },
250+ BackupDownloaded { name: String },
201 }251 }
202 252
203 #[derive(Debug, Clone, Copy, PartialEq, Eq)]253 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -230,10 +280,13 @@ pub enum AdminActionKind {
230 GhostDisabled,280 GhostDisabled,
231 GhostVisit,281 GhostVisit,
232 GhostVoice,282 GhostVoice,
283+ BackupCreated,
284+ BackupDeleted,
285+ BackupDownloaded,
233 }286 }
234 287
235 impl AdminActionKind {288 impl AdminActionKind {
236- pub const ALL: [Self; 28] = [289+ pub const ALL: [Self; 31] = [
237 AdminActionKind::RoleChanged,290 AdminActionKind::RoleChanged,
238 AdminActionKind::UserDeleted,291 AdminActionKind::UserDeleted,
239 AdminActionKind::UserSuspended,292 AdminActionKind::UserSuspended,
@@ -262,6 +315,9 @@ impl AdminActionKind {
262 AdminActionKind::GhostDisabled,315 AdminActionKind::GhostDisabled,
263 AdminActionKind::GhostVisit,316 AdminActionKind::GhostVisit,
264 AdminActionKind::GhostVoice,317 AdminActionKind::GhostVoice,
318+ AdminActionKind::BackupCreated,
319+ AdminActionKind::BackupDeleted,
320+ AdminActionKind::BackupDownloaded,
265 ];321 ];
266 322
267 pub const fn as_str(self) -> &'static str {323 pub const fn as_str(self) -> &'static str {
@@ -294,6 +350,9 @@ impl AdminActionKind {
294 AdminActionKind::GhostDisabled => "ghost_disabled",350 AdminActionKind::GhostDisabled => "ghost_disabled",
295 AdminActionKind::GhostVisit => "ghost_visit",351 AdminActionKind::GhostVisit => "ghost_visit",
296 AdminActionKind::GhostVoice => "ghost_voice",352 AdminActionKind::GhostVoice => "ghost_voice",
353+ AdminActionKind::BackupCreated => "backup_created",
354+ AdminActionKind::BackupDeleted => "backup_deleted",
355+ AdminActionKind::BackupDownloaded => "backup_downloaded",
297 }356 }
298 }357 }
299 358
@@ -333,21 +392,24 @@ impl AdminAction {
333 AdminAction::GhostDisabled => AdminActionKind::GhostDisabled,392 AdminAction::GhostDisabled => AdminActionKind::GhostDisabled,
334 AdminAction::GhostVisit => AdminActionKind::GhostVisit,393 AdminAction::GhostVisit => AdminActionKind::GhostVisit,
335 AdminAction::GhostVoice { .. } => AdminActionKind::GhostVoice,394 AdminAction::GhostVoice { .. } => AdminActionKind::GhostVoice,
395+ AdminAction::BackupCreated { .. } => AdminActionKind::BackupCreated,
396+ AdminAction::BackupDeleted { .. } => AdminActionKind::BackupDeleted,
397+ AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded,
336 }398 }
337 }399 }
338 }400 }
339 401
340-const fn action_names() -> [&'static str; 28] {402+const fn action_names() -> [&'static str; 31] {
341- let mut names = [""; 28];403+ let mut names = [""; 31];
342 let mut index = 0;404 let mut index = 0;
343- while index < 28 {405+ while index < 31 {
344 names[index] = AdminActionKind::ALL[index].as_str();406 names[index] = AdminActionKind::ALL[index].as_str();
345 index += 1;407 index += 1;
346 }408 }
347 names409 names
348 }410 }
349 411
350-pub const ACTION_NAMES: [&str; 28] = action_names();412+pub const ACTION_NAMES: [&str; 31] = action_names();
351 413
352 pub fn action_name(action: &AdminAction) -> &'static str {414 pub fn action_name(action: &AdminAction) -> &'static str {
353 action.kind().as_str()415 action.kind().as_str()
@@ -364,6 +426,9 @@ pub fn action_detail(action: &AdminAction) -> Option<String> {
364 AdminAction::VoiceMuted { muted } => Some(muted.to_string()),426 AdminAction::VoiceMuted { muted } => Some(muted.to_string()),
365 AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()),427 AdminAction::CommunityVoiceSet { enabled } => Some(enabled.to_string()),
366 AdminAction::GhostVoice { seconds } => Some(seconds.to_string()),428 AdminAction::GhostVoice { seconds } => Some(seconds.to_string()),
429+ AdminAction::BackupCreated { name }
430+ | AdminAction::BackupDeleted { name }
431+ | AdminAction::BackupDownloaded { name } => Some(name.clone()),
367 _ => None,432 _ => None,
368 }433 }
369 }434 }
@@ -472,6 +537,13 @@ pub struct AttachmentInfo {
472 pub community: String,537 pub community: String,
473 }538 }
474 539
540+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
541+pub struct BackupInfo {
542+ pub name: String,
543+ pub size_bytes: u64,
544+ pub created_ms: u64,
545+}
546+
475 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]547 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
476 pub struct Usage {548 pub struct Usage {
477 pub user: User,549 pub user: User,
@@ -611,6 +683,7 @@ pub struct SnippetMessage {
611 pub avatar_id: Option<String>,683 pub avatar_id: Option<String>,
612 pub body: String,684 pub body: String,
613 pub attachments: Vec<Attachment>,685 pub attachments: Vec<Attachment>,
686+ pub poll: Option<Poll>,
614 }687 }
615 688
616 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]689 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
@@ -619,6 +692,26 @@ pub struct Snippet {
619 pub messages: Vec<SnippetMessage>,692 pub messages: Vec<SnippetMessage>,
620 }693 }
621 694
695+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
696+pub struct Reaction {
697+ pub emoji: String,
698+ pub user_ids: Vec<String>,
699+}
700+
701+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
702+pub struct PollOption {
703+ pub text: String,
704+ pub voter_ids: Vec<String>,
705+}
706+
707+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
708+pub struct Poll {
709+ pub question: String,
710+ pub options: Vec<PollOption>,
711+ pub multiple: bool,
712+ pub closed: bool,
713+}
714+
622 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]715 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
623 pub struct Message {716 pub struct Message {
624 pub id: String,717 pub id: String,
@@ -626,9 +719,49 @@ pub struct Message {
626 pub community_id: String,719 pub community_id: String,
627 pub body: String,720 pub body: String,
628 pub attachments: Vec<Attachment>,721 pub attachments: Vec<Attachment>,
722+ pub reactions: Vec<Reaction>,
629 pub reply: Option<Quote>,723 pub reply: Option<Quote>,
630 pub snippet: Option<Snippet>,724 pub snippet: Option<Snippet>,
725+ pub poll: Option<Poll>,
631 pub edited: bool,726 pub edited: bool,
727+ pub pinned: bool,
728+ pub call: Option<CallLog>,
729+}
730+
731+#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
732+pub enum CallLog {
733+ Started,
734+ Declined,
735+ Missed,
736+ Ended { seconds: u64 },
737+}
738+
739+impl CallLog {
740+ pub fn as_str(self) -> &'static str {
741+ match self {
742+ CallLog::Started => "started",
743+ CallLog::Declined => "declined",
744+ CallLog::Missed => "missed",
745+ CallLog::Ended { .. } => "ended",
746+ }
747+ }
748+
749+ pub fn parse(text: &str, seconds: u64) -> Option<Self> {
750+ match text {
751+ "started" => Some(CallLog::Started),
752+ "declined" => Some(CallLog::Declined),
753+ "missed" => Some(CallLog::Missed),
754+ "ended" => Some(CallLog::Ended { seconds }),
755+ _ => None,
756+ }
757+ }
758+
759+ pub fn seconds(self) -> u64 {
760+ match self {
761+ CallLog::Ended { seconds } => seconds,
762+ CallLog::Started | CallLog::Declined | CallLog::Missed => 0,
763+ }
764+ }
632 }765 }
633 766
634 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]767 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
crates/common/src/network.rsmodified+2 -0
@@ -29,6 +29,7 @@ pub enum StreamKind {
29 Request = 0,29 Request = 0,
30 Upload = 1,30 Upload = 1,
31 Download = 2,31 Download = 2,
32+ Backup = 3,
32 }33 }
33 34
34 impl StreamKind {35 impl StreamKind {
@@ -37,6 +38,7 @@ impl StreamKind {
37 0 => Some(StreamKind::Request),38 0 => Some(StreamKind::Request),
38 1 => Some(StreamKind::Upload),39 1 => Some(StreamKind::Upload),
39 2 => Some(StreamKind::Download),40 2 => Some(StreamKind::Download),
41+ 3 => Some(StreamKind::Backup),
40 _ => None,42 _ => None,
41 }43 }
42 }44 }
crates/common/src/permission.rsmodified+8 -0
@@ -35,6 +35,14 @@ pub fn can_edit_message(is_author: bool) -> bool {
35 is_author35 is_author
36 }36 }
37 37
38+pub fn can_pin(actor: Option<Rank>, direct: bool) -> bool {
39+ actor >= Some(Rank::Moderator) || (direct && actor.is_some())
40+}
41+
42+pub fn can_close_poll(actor: Option<Rank>, is_author: bool) -> bool {
43+ is_author || actor >= Some(Rank::Moderator)
44+}
45+
38 pub fn can_delete_message(actor: Option<Rank>, author: Option<Rank>, is_author: bool) -> bool {46 pub fn can_delete_message(actor: Option<Rank>, author: Option<Rank>, is_author: bool) -> bool {
39 is_author || (actor >= Some(Rank::Moderator) && actor > author)47 is_author || (actor >= Some(Rank::Moderator) && actor > author)
40 }48 }
crates/common/src/request.rsmodified+53 -1
@@ -1,6 +1,6 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::model::{Rank, ReportStatus, Role, ServerSettings};3+use crate::model::{Presence, Rank, ReportStatus, Role, ServerSettings};
4 4
5 #[derive(Debug, Clone, Encode, Decode)]5 #[derive(Debug, Clone, Encode, Decode)]
6 pub struct UploadHeader {6 pub struct UploadHeader {
@@ -39,6 +39,10 @@ pub enum Request {
39 UpdateStatus {39 UpdateStatus {
40 status: String,40 status: String,
41 },41 },
42+ UpdatePresence {
43+ presence: Presence,
44+ },
45+ ReadPresences,
42 UpdateAvatar {46 UpdateAvatar {
43 image: Vec<u8>,47 image: Vec<u8>,
44 },48 },
@@ -113,14 +117,49 @@ pub enum Request {
113 DeleteMessage {117 DeleteMessage {
114 message_id: String,118 message_id: String,
115 },119 },
120+ CreatePoll {
121+ community_id: String,
122+ question: String,
123+ options: Vec<String>,
124+ multiple: bool,
125+ },
126+ Vote {
127+ message_id: String,
128+ positions: Vec<u32>,
129+ },
130+ ClosePoll {
131+ message_id: String,
132+ },
133+ React {
134+ message_id: String,
135+ emoji: String,
136+ },
137+ Pin {
138+ message_id: String,
139+ pinned: bool,
140+ },
141+ Pins {
142+ community_id: String,
143+ },
116 ReadMessages {144 ReadMessages {
117 community_id: String,145 community_id: String,
118 before: Option<String>,146 before: Option<String>,
119 },147 },
148+ Unreads,
149+ MarkRead {
150+ community_id: String,
151+ message_id: String,
152+ },
153+ Typing {
154+ community_id: String,
155+ },
120 JoinVoice {156 JoinVoice {
121 community_id: String,157 community_id: String,
122 },158 },
123 LeaveVoice,159 LeaveVoice,
160+ DeclineCall {
161+ community_id: String,
162+ },
124 VoiceParticipants {163 VoiceParticipants {
125 community_id: String,164 community_id: String,
126 },165 },
@@ -130,6 +169,7 @@ pub enum Request {
130 OpenDirect {169 OpenDirect {
131 user_id: String,170 user_id: String,
132 },171 },
172+ OpenNotes,
133 Friends,173 Friends,
134 AddFriend {174 AddFriend {
135 user_id: String,175 user_id: String,
@@ -252,6 +292,10 @@ pub enum Request {
252 after_ms: Option<u64>,292 after_ms: Option<u64>,
253 before_ms: Option<u64>,293 before_ms: Option<u64>,
254 },294 },
295+ SearchCommunity {
296+ community_id: String,
297+ text: String,
298+ },
255 PurgeUser {299 PurgeUser {
256 user_id: String,300 user_id: String,
257 },301 },
@@ -281,4 +325,12 @@ pub enum Request {
281 SetGhost {325 SetGhost {
282 enabled: bool,326 enabled: bool,
283 },327 },
328+ CreateBackup,
329+ Backups,
330+ DeleteBackup {
331+ name: String,
332+ },
333+ DownloadBackup {
334+ name: String,
335+ },
284 }336 }
crates/common/src/response.rsmodified+12 -4
@@ -3,15 +3,19 @@ use bitcode::{Decode, Encode};
3 use crate::{3 use crate::{
4 error::Error,4 error::Error,
5 model::{5 model::{
6- Account, AdminLogEntry, Attachment, AttachmentInfo, Ban, Community, CommunitySummary,6+ Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community,
7- CommunityUsage, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit,7+ CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
8- DayStat, Overview, Report, ServerBan, ServerSettings, SessionInfo, Usage, User, VoiceRoom,8+ Member, Message, MessageHit, Overview, Presence, Report, ServerBan, ServerSettings,
9+ SessionInfo, Unread, Usage, User, VoiceRoom,
9 },10 },
10 };11 };
11 12
12 #[derive(Debug, Clone, Encode, Decode)]13 #[derive(Debug, Clone, Encode, Decode)]
13 pub enum Response {14 pub enum Response {
14- Session { user: User, token: String },15+ Session {
16+ user: User,
17+ token: String,
18+ },
15 User(User),19 User(User),
16 Avatar(Vec<u8>),20 Avatar(Vec<u8>),
17 Community(Community),21 Community(Community),
@@ -20,6 +24,7 @@ pub enum Response {
20 Bans(Vec<Ban>),24 Bans(Vec<Ban>),
21 Message(Message),25 Message(Message),
22 Messages(Vec<Message>),26 Messages(Vec<Message>),
27+ Unreads(Vec<Unread>),
23 Attachment(Attachment),28 Attachment(Attachment),
24 Voice(Vec<String>),29 Voice(Vec<String>),
25 Friends(Friends),30 Friends(Friends),
@@ -45,4 +50,7 @@ pub enum Response {
45 communities: Vec<CommunityUsage>,50 communities: Vec<CommunityUsage>,
46 },51 },
47 DailyStats(Vec<DayStat>),52 DailyStats(Vec<DayStat>),
53+ Backup(BackupInfo),
54+ Backups(Vec<BackupInfo>),
55+ Presences(Vec<(String, Presence)>),
48 }56 }
crates/common/src/validate.rsmodified+62 -8
@@ -1,14 +1,18 @@
1+use std::collections::BTreeSet;
2+
1 use crate::{3 use crate::{
2 constant::{4 constant::{
3- MAXIMUM_ANNOUNCEMENT_LENGTH, MAXIMUM_ATTACHMENT_LIMIT_BYTES, MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_AVATAR_BYTES,5+ MAXIMUM_ANNOUNCEMENT_LENGTH, MAXIMUM_ATTACHMENT_LIMIT_BYTES,
4- MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_DEVICE_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES,6+ MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_AVATAR_BYTES, MAXIMUM_COMMUNITY_NAME_LENGTH,
5- MAXIMUM_MESSAGE_LENGTH, MAXIMUM_PASSWORD_LENGTH, MAXIMUM_REASON_LENGTH,7+ MAXIMUM_DEVICE_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH,
6- MAXIMUM_STATUS_LENGTH, MAXIMUM_USERNAME_LENGTH, MINIMUM_ATTACHMENT_LIMIT_BYTES,8+ MAXIMUM_PASSWORD_LENGTH, MAXIMUM_POLL_OPTION_LENGTH, MAXIMUM_POLL_OPTIONS,
7- MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH,9+ MAXIMUM_POLL_QUESTION_LENGTH, MAXIMUM_REASON_LENGTH, MAXIMUM_STATUS_LENGTH,
8- MINIMUM_USERNAME_LENGTH,10+ MAXIMUM_USERNAME_LENGTH, MINIMUM_ATTACHMENT_LIMIT_BYTES, MINIMUM_COMMUNITY_NAME_LENGTH,
11+ MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS,
12+ MINIMUM_USERNAME_LENGTH, REACTIONS,
9 },13 },
10 error::{Error, InvalidInput},14 error::{Error, InvalidInput},
11- model::ServerSettings,15+ model::{Poll, ServerSettings},
12 };16 };
13 17
14 fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {18 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
78 check(body, 0, maximum, false).map_err(Error::Message)82 check(body, 0, maximum, false).map_err(Error::Message)
79 }83 }
80 84
85+pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> {
86+ check_length(question.chars().count(), 1, MAXIMUM_POLL_QUESTION_LENGTH)
87+ .map_err(Error::Message)?;
88+ check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)
89+ .map_err(Error::Message)?;
90+ for option in options {
91+ check_length(option.chars().count(), 1, MAXIMUM_POLL_OPTION_LENGTH)
92+ .map_err(Error::Message)?;
93+ }
94+
95+ Ok(())
96+}
97+
98+pub fn validate_vote(poll: &Poll, positions: &[u32]) -> Result<(), Error> {
99+ let unique: BTreeSet<&u32> = positions.iter().collect();
100+ let in_range = positions
101+ .iter()
102+ .all(|position| (*position as usize) < poll.options.len());
103+ let allowed = poll.multiple || positions.len() <= 1;
104+ if poll.closed || !in_range || unique.len() != positions.len() || !allowed {
105+ return Err(Error::Forbidden);
106+ }
107+
108+ Ok(())
109+}
110+
111+pub fn validate_reaction(emoji: &str) -> Result<(), Error> {
112+ if REACTIONS.contains(&emoji) {
113+ return Ok(());
114+ }
115+
116+ Err(Error::Message(InvalidInput::ForbiddenCharacter))
117+}
118+
81 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {119 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {
82 check_length(name.chars().count(), 1, MAXIMUM_ATTACHMENT_NAME_LENGTH)120 check_length(name.chars().count(), 1, MAXIMUM_ATTACHMENT_NAME_LENGTH)
83 .map_err(Error::AttachmentName)?;121 .map_err(Error::AttachmentName)?;
@@ -89,6 +127,19 @@ pub fn validate_attachment_name(name: &str) -> Result<(), Error> {
89 Ok(())127 Ok(())
90 }128 }
91 129
130+pub fn validate_backup_name(name: &str) -> Result<(), Error> {
131+ if name.is_empty()
132+ || name.contains("..")
133+ || !name.chars().all(|character| {
134+ character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
135+ })
136+ {
137+ return Err(Error::BackupName(InvalidInput::ForbiddenCharacter));
138+ }
139+
140+ Ok(())
141+}
142+
92 fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> {143 fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> {
93 match actual {144 match actual {
94 0 => Err(InvalidInput::Empty),145 0 => Err(InvalidInput::Empty),
@@ -142,7 +193,10 @@ pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error>
142 validate_community_name(&settings.name)?;193 validate_community_name(&settings.name)?;
143 validate_attachment_limit(settings.max_attachment_bytes)?;194 validate_attachment_limit(settings.max_attachment_bytes)?;
144 check_quota(settings.user_quota_bytes, settings.max_attachment_bytes)?;195 check_quota(settings.user_quota_bytes, settings.max_attachment_bytes)?;
145- check_quota(settings.community_quota_bytes, settings.max_attachment_bytes)?;196+ check_quota(
197+ settings.community_quota_bytes,
198+ settings.max_attachment_bytes,
199+ )?;
146 validate_announcement(&settings.announcement)?;200 validate_announcement(&settings.announcement)?;
147 check_length(201 check_length(
148 settings.max_message_length as usize,202 settings.max_message_length as usize,
crates/server/src/admin_log.rsmodified+3 -0
@@ -54,6 +54,9 @@ fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {
54 AdminActionKind::GhostVoice => AdminAction::GhostVoice {54 AdminActionKind::GhostVoice => AdminAction::GhostVoice {
55 seconds: detail?.parse().ok()?,55 seconds: detail?.parse().ok()?,
56 },56 },
57+ AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? },
58+ AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? },
59+ AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? },
57 })60 })
58 }61 }
59 62
crates/server/src/attachment.rsmodified+10 -2
@@ -478,7 +478,14 @@ pub async fn store<R: AsyncRead + Unpin>(
478 validate_attachment_name(&header.name)?;478 validate_attachment_name(&header.name)?;
479 let settings = server_settings::read(&conn).await?;479 let settings = server_settings::read(&conn).await?;
480 validate_attachment_size(header.size, settings.max_attachment_bytes)?;480 validate_attachment_size(header.size, settings.max_attachment_bytes)?;
481- ensure_quota(&user.id, &header.community_id, header.size, &settings, &conn).await?;481+ ensure_quota(
482+ &user.id,
483+ &header.community_id,
484+ header.size,
485+ &settings,
486+ &conn,
487+ )
488+ .await?;
482 489
483 let id = new_id();490 let id = new_id();
484 let part = directory.join(format!("{id}.part"));491 let part = directory.join(format!("{id}.part"));
@@ -579,7 +586,7 @@ async fn locate(
579 Ok((path, length))586 Ok((path, length))
580 }587 }
581 588
582-async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> {589+pub async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> {
583 let mut file = File::open(path).await?;590 let mut file = File::open(path).await?;
584 let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];591 let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
585 loop {592 loop {
@@ -730,6 +737,7 @@ mod tests {
730 &Services::default(),737 &Services::default(),
731 None,738 None,
732 &test::directory(),739 &test::directory(),
740+ &test::directory(),
733 )741 )
734 .await;742 .await;
735 743
crates/server/src/backup.rsadded+150 -0
@@ -0,0 +1,150 @@
1+use std::path::{Path, PathBuf};
2+
3+use common::{
4+ error::Error as CommonError,
5+ model::{AdminAction, BackupInfo, User},
6+ network::{
7+ DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_request, send_download_status,
8+ send_encoded,
9+ },
10+ permission,
11+ request::Request,
12+ time,
13+ validate::validate_backup_name,
14+};
15+use quinn::{RecvStream, SendStream};
16+use turso::Connection;
17+
18+use crate::{
19+ admin_log, attachment,
20+ database::{self, DB},
21+ error::Error,
22+ request::ensure,
23+ user,
24+};
25+
26+const PREFIX: &str = "yumush-";
27+const EXTENSION: &str = ".db";
28+
29+pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
30+ let directory = Path::new(database_path)
31+ .parent()
32+ .unwrap_or_else(|| Path::new(""))
33+ .join("backups");
34+ std::fs::create_dir_all(&directory)?;
35+
36+ Ok(directory)
37+}
38+
39+fn created_secs(name: &str) -> Option<u64> {
40+ name.strip_prefix(PREFIX)?
41+ .strip_suffix(EXTENSION)?
42+ .parse()
43+ .ok()
44+}
45+
46+fn info(directory: &Path, name: &str) -> Result<BackupInfo, Error> {
47+ let created_secs = created_secs(name).ok_or(CommonError::NotFound)?;
48+ let size_bytes = std::fs::metadata(directory.join(name))?.len();
49+
50+ Ok(BackupInfo {
51+ name: name.to_string(),
52+ size_bytes,
53+ created_ms: created_secs * 1000,
54+ })
55+}
56+
57+fn path_of(directory: &Path, name: &str) -> Result<PathBuf, Error> {
58+ validate_backup_name(name)?;
59+ created_secs(name).ok_or(CommonError::NotFound)?;
60+
61+ Ok(directory.join(name))
62+}
63+
64+pub async fn create(conn: &Connection, directory: &Path) -> Result<BackupInfo, Error> {
65+ let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000);
66+ let path = directory.join(&name);
67+ let statement = format!(
68+ "VACUUM INTO '{}'",
69+ path.to_string_lossy().replace('\'', "''")
70+ );
71+ conn.execute(&statement, ()).await?;
72+
73+ info(directory, &name)
74+}
75+
76+pub fn list(directory: &Path) -> Result<Vec<BackupInfo>, Error> {
77+ let mut backups = Vec::new();
78+ for entry in std::fs::read_dir(directory)? {
79+ let name = entry?.file_name().to_string_lossy().into_owned();
80+ if created_secs(&name).is_some() {
81+ backups.push(info(directory, &name)?);
82+ }
83+ }
84+ backups.sort_by(|left, right| right.created_ms.cmp(&left.created_ms));
85+
86+ Ok(backups)
87+}
88+
89+pub fn delete(name: &str, directory: &Path) -> Result<(), Error> {
90+ std::fs::remove_file(path_of(directory, name)?)?;
91+
92+ Ok(())
93+}
94+
95+async fn locate(
96+ user: Option<&User>,
97+ request: Request,
98+ db: &DB,
99+ directory: &Path,
100+) -> Result<(PathBuf, u64), Error> {
101+ let user = user.ok_or(CommonError::Unauthenticated)?;
102+ let Request::DownloadBackup { name } = request else {
103+ return Err(CommonError::Forbidden.into());
104+ };
105+ let conn = database::connect(db).await?;
106+ let me = user::read(&user.id, &conn).await?;
107+ ensure(permission::is_builder(me.role))?;
108+
109+ let path = path_of(directory, &name)?;
110+ let length = tokio::fs::metadata(&path)
111+ .await
112+ .map_err(|_| CommonError::NotFound)?
113+ .len();
114+ admin_log::record(
115+ Some(&me.id),
116+ None,
117+ None,
118+ &AdminAction::BackupDownloaded { name },
119+ &conn,
120+ )
121+ .await?;
122+
123+ Ok((path, length))
124+}
125+
126+pub async fn download(
127+ user: Option<&User>,
128+ receive_stream: RecvStream,
129+ mut send_stream: SendStream,
130+ db: &DB,
131+ directory: &Path,
132+) -> Result<(), Error> {
133+ let request = receive_request(receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?;
134+
135+ match locate(user, request, db, directory).await {
136+ Ok((path, length)) => {
137+ send_download_status(DownloadStatus::Ok, &mut send_stream).await?;
138+ send_stream.write_all(&length.to_le_bytes()).await?;
139+ attachment::stream_file(&path, &mut send_stream).await?;
140+ }
141+ Err(error) => {
142+ let error: CommonError = error.into();
143+ send_download_status(DownloadStatus::Error, &mut send_stream).await?;
144+ send_encoded(&error, &mut send_stream).await?;
145+ }
146+ }
147+ send_stream.finish()?;
148+
149+ Ok(())
150+}
crates/server/src/community.rsmodified+69 -8
@@ -11,15 +11,17 @@ use crate::{database::new_id, error::Error, user};
11 pub enum Kind {11 pub enum Kind {
12 Group,12 Group,
13 Direct,13 Direct,
14+ Notes,
14 }15 }
15 16
16 impl Kind {17 impl Kind {
17- const ALL: [Self; 2] = [Kind::Group, Kind::Direct];18+ const ALL: [Self; 3] = [Kind::Group, Kind::Direct, Kind::Notes];
18 19
19 pub fn as_str(self) -> &'static str {20 pub fn as_str(self) -> &'static str {
20 match self {21 match self {
21 Kind::Group => "group",22 Kind::Group => "group",
22 Kind::Direct => "direct",23 Kind::Direct => "direct",
24+ Kind::Notes => "notes",
23 }25 }
24 }26 }
25 27
@@ -56,13 +58,39 @@ async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result<
56 user::from_row(&row)58 user::from_row(&row)
57 }59 }
58 60
61+async fn outsider_name(
62+ community_id: &str,
63+ viewer_id: &str,
64+ conn: &Connection,
65+) -> Result<Option<String>, Error> {
66+ let mut rows = conn
67+ .query(
68+ "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",
69+ (community_id, viewer_id),
70+ )
71+ .await?;
72+ let Some(row) = rows.next().await? else {
73+ return Ok(None);
74+ };
75+ let first: String = row.get(0)?;
76+ let second: String = row.get(1)?;
77+
78+ Ok(Some(format!("{first} & {second}")))
79+}
80+
59 async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community, Error> {81 async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community, Error> {
60- let (id, name, kind, avatar_id, voice_enabled) = raw;82+ let (id, mut name, kind, avatar_id, voice_enabled) = raw;
61 let kind = match kind {83 let kind = match kind {
62 Kind::Group => CommunityKind::Group,84 Kind::Group => CommunityKind::Group,
63- Kind::Direct => CommunityKind::Direct {85+ Kind::Direct => {
64- peer: peer(&id, viewer_id, conn).await?,86+ if let Some(outsider) = outsider_name(&id, viewer_id, conn).await? {
65- },87+ name = outsider;
88+ }
89+ CommunityKind::Direct {
90+ peer: peer(&id, viewer_id, conn).await?,
91+ }
92+ }
93+ Kind::Notes => CommunityKind::Notes,
66 };94 };
67 95
68 Ok(Community {96 Ok(Community {
@@ -104,6 +132,17 @@ pub async fn create_direct(conn: &Connection) -> Result<String, Error> {
104 Ok(id)132 Ok(id)
105 }133 }
106 134
135+pub async fn create_notes(conn: &Connection) -> Result<String, Error> {
136+ let id = new_id();
137+ conn.execute(
138+ "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)",
139+ (id.as_str(), Kind::Notes.as_str()),
140+ )
141+ .await?;
142+
143+ Ok(id)
144+}
145+
107 pub async fn read(146 pub async fn read(
108 community_id: &str,147 community_id: &str,
109 viewer_id: &str,148 viewer_id: &str,
@@ -236,7 +275,7 @@ pub async fn delete(
236 Ok(deleted)275 Ok(deleted)
237 }276 }
238 277
239-async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, Error> {278+pub async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, Error> {
240 let mut rows = conn279 let mut rows = conn
241 .query("SELECT kind FROM community WHERE id = ?1", (community_id,))280 .query("SELECT kind FROM community WHERE id = ?1", (community_id,))
242 .await?;281 .await?;
@@ -250,6 +289,13 @@ pub async fn is_direct(community_id: &str, conn: &Connection) -> Result<bool, Er
250 Ok(kind(community_id, conn).await? == Kind::Direct)289 Ok(kind(community_id, conn).await? == Kind::Direct)
251 }290 }
252 291
292+pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result<bool, Error> {
293+ Ok(matches!(
294+ kind(community_id, conn).await?,
295+ Kind::Direct | Kind::Notes
296+ ))
297+}
298+
253 pub async fn set_voice_enabled(299 pub async fn set_voice_enabled(
254 community_id: &str,300 community_id: &str,
255 enabled: bool,301 enabled: bool,
@@ -280,13 +326,28 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool
280 pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> {326 pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> {
281 let mut rows = conn327 let mut rows = conn
282 .query(328 .query(
283- "SELECT CASE WHEN kind = ?2 THEN 'DM' ELSE name END FROM community WHERE id = ?1",329+ "SELECT kind = ?2, name FROM community WHERE id = ?1",
284 (community_id, Kind::Direct.as_str()),330 (community_id, Kind::Direct.as_str()),
285 )331 )
286 .await?;332 .await?;
287 let row = rows.next().await?.ok_or(CommonError::NotFound)?;333 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
334+ let direct: i64 = row.get(0)?;
335+ if direct == 0 {
336+ return Ok(row.get(1)?);
337+ }
338+
339+ let mut rows = conn
340+ .query(
341+ "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",
342+ (community_id,),
343+ )
344+ .await?;
345+ let mut usernames = Vec::new();
346+ while let Some(row) = rows.next().await? {
347+ usernames.push(row.get::<String>(0)?);
348+ }
288 349
289- Ok(row.get(0)?)350+ Ok(format!("DM · {}", usernames.join(" & ")))
290 }351 }
291 352
292 #[cfg(test)]353 #[cfg(test)]
crates/server/src/database.rsmodified+49 -0
@@ -240,6 +240,55 @@ const MIGRATIONS: &[&str] = &[
240 "240 "
241 ALTER TABLE user ADD COLUMN ghost INTEGER NOT NULL DEFAULT 0;241 ALTER TABLE user ADD COLUMN ghost INTEGER NOT NULL DEFAULT 0;
242 ",242 ",
243+ "
244+ ALTER TABLE user ADD COLUMN presence TEXT NOT NULL DEFAULT 'online';
245+",
246+ "
247+ ALTER TABLE message ADD COLUMN call TEXT;
248+ ALTER TABLE message ADD COLUMN call_seconds INTEGER NOT NULL DEFAULT 0;
249+",
250+ "
251+ CREATE TABLE reaction (
252+ message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE,
253+ user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
254+ emoji TEXT NOT NULL,
255+ PRIMARY KEY (message_id, user_id, emoji)
256+ );
257+",
258+ "
259+ ALTER TABLE message ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;
260+",
261+ "
262+ ALTER TABLE user_community ADD COLUMN last_read TEXT;
263+ UPDATE user_community SET last_read = (SELECT MAX(id) FROM message WHERE message.community_id = user_community.community_id);
264+",
265+ "
266+ CREATE TABLE notes (
267+ user_id TEXT PRIMARY KEY REFERENCES user (id) ON DELETE CASCADE,
268+ community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE
269+ );
270+",
271+ "
272+ CREATE TABLE poll (
273+ message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE,
274+ question TEXT NOT NULL,
275+ multiple INTEGER NOT NULL,
276+ closed INTEGER NOT NULL DEFAULT 0
277+ );
278+ CREATE TABLE poll_option (
279+ message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE,
280+ position INTEGER NOT NULL,
281+ text TEXT NOT NULL,
282+ PRIMARY KEY (message_id, position)
283+ );
284+ CREATE TABLE poll_vote (
285+ message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE,
286+ position INTEGER NOT NULL,
287+ user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
288+ PRIMARY KEY (message_id, position, user_id)
289+ );
290+",
291+ "ALTER TABLE snippet_message ADD COLUMN poll BLOB;",
243 ];292 ];
244 293
245 pub async fn open(path: &str) -> Result<DB, Error> {294 pub async fn open(path: &str) -> Result<DB, Error> {
crates/server/src/lib.rsmodified+13 -3
@@ -1,17 +1,19 @@
1+pub mod admin_log;
1 pub mod attachment;2 pub mod attachment;
2 pub mod authentication;3 pub mod authentication;
4+pub mod backup;
3 pub mod certificate;5 pub mod certificate;
4 pub mod community;6 pub mod community;
5-pub mod admin_log;
6 pub mod database;7 pub mod database;
7 pub mod direct;8 pub mod direct;
8 pub mod error;9 pub mod error;
9 pub mod friend;10 pub mod friend;
10-pub mod invite;
11 pub mod invitation;11 pub mod invitation;
12+pub mod invite;
12 pub mod log;13 pub mod log;
13 pub mod message;14 pub mod message;
14 pub mod network;15 pub mod network;
16+pub mod notes;
15 pub mod overview;17 pub mod overview;
16 pub mod rate_limit;18 pub mod rate_limit;
17 pub mod report;19 pub mod report;
@@ -70,10 +72,18 @@ pub async fn showtime() -> Result<(), Error> {
70 let database = database::open(&config.database_path).await?;72 let database = database::open(&config.database_path).await?;
71 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;73 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;
72 let attachments = attachment::directory(&config.database_path)?;74 let attachments = attachment::directory(&config.database_path)?;
75+ let backups = backup::directory(&config.database_path)?;
73 tokio::spawn(attachment::collect(database.clone(), attachments.clone()));76 tokio::spawn(attachment::collect(database.clone(), attachments.clone()));
74 tokio::spawn(retention::collect(database.clone(), attachments.clone()));77 tokio::spawn(retention::collect(database.clone(), attachments.clone()));
75 78
76- network::serve(&config.server_address, certificate, database, attachments).await79+ network::serve(
80+ &config.server_address,
81+ certificate,
82+ database,
83+ attachments,
84+ backups,
85+ )
86+ .await
77 }87 }
78 88
79 pub async fn set_role(username: &str, role: Role) -> Result<(), Error> {89 pub async fn set_role(username: &str, role: Role) -> Result<(), Error> {
crates/server/src/message.rsmodified+294 -15
@@ -1,11 +1,14 @@
1-use std::path::Path;1+use std::{collections::HashMap, path::Path};
2 2
3 use common::{3 use common::{
4 constant::{4 constant::{
5 MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT,5 MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT,
6 },6 },
7 error::{Error as CommonError, InvalidInput},7 error::{Error as CommonError, InvalidInput},
8- model::{Message, MessageHit, Quote, Snippet, SnippetMessage, User},8+ model::{
9+ CallLog, Message, MessageHit, Poll, PollOption, Quote, Reaction, Snippet, SnippetMessage,
10+ User,
11+ },
9 time,12 time,
10 validate::{validate_message_body, validate_new_message},13 validate::{validate_message_body, validate_new_message},
11 };14 };
@@ -15,10 +18,15 @@ use crate::{attachment, community, database::new_id, error::Error, user};
15 18
16 const SEARCH_LIMIT: usize = 200;19 const SEARCH_LIMIT: usize = 200;
17 20
18-const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL) FROM message m LEFT JOIN message r ON r.id = m.reply_to";21+const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL), m.call, m.call_seconds, m.pinned FROM message m LEFT JOIN message r ON r.id = m.reply_to";
19 22
20 fn from_row(row: &Row) -> Result<Message, Error> {23 fn from_row(row: &Row) -> Result<Message, Error> {
21 let edited: i64 = row.get(4)?;24 let edited: i64 = row.get(4)?;
25+ let call_seconds: i64 = row.get(10)?;
26+ let pinned: i64 = row.get(11)?;
27+ let call = row
28+ .get::<Option<String>>(9)?
29+ .and_then(|text| CallLog::parse(&text, call_seconds as u64));
22 let reply = match row.get::<Option<String>>(5)? {30 let reply = match row.get::<Option<String>>(5)? {
23 Some(message_id) => {31 Some(message_id) => {
24 let body: String = row.get(7)?;32 let body: String = row.get(7)?;
@@ -39,12 +47,136 @@ fn from_row(row: &Row) -> Result<Message, Error> {
39 community_id: row.get(2)?,47 community_id: row.get(2)?,
40 body: row.get(3)?,48 body: row.get(3)?,
41 attachments: Vec::new(),49 attachments: Vec::new(),
50+ reactions: Vec::new(),
42 reply,51 reply,
43 snippet: None,52 snippet: None,
53+ poll: None,
44 edited: edited != 0,54 edited: edited != 0,
55+ pinned: pinned != 0,
56+ call,
45 })57 })
46 }58 }
47 59
60+fn placeholders(count: usize) -> String {
61+ (1..=count)
62+ .map(|index| format!("?{index}"))
63+ .collect::<Vec<_>>()
64+ .join(", ")
65+}
66+
67+async fn reactions_of(
68+ message_ids: &[String],
69+ conn: &Connection,
70+) -> Result<HashMap<String, Vec<Reaction>>, Error> {
71+ let mut reactions: HashMap<String, Vec<Reaction>> = HashMap::new();
72+ if message_ids.is_empty() {
73+ return Ok(reactions);
74+ }
75+
76+ let placeholders = placeholders(message_ids.len());
77+ let mut rows = conn
78+ .query(
79+ &format!(
80+ "SELECT message_id, emoji, user_id FROM reaction WHERE message_id IN ({placeholders}) ORDER BY message_id, emoji, user_id"
81+ ),
82+ message_ids.to_vec(),
83+ )
84+ .await?;
85+
86+ while let Some(row) = rows.next().await? {
87+ let message_id: String = row.get(0)?;
88+ let emoji: String = row.get(1)?;
89+ let user_id: String = row.get(2)?;
90+ let entries = reactions.entry(message_id).or_default();
91+ match entries
92+ .last_mut()
93+ .filter(|reaction| reaction.emoji == emoji)
94+ {
95+ Some(reaction) => reaction.user_ids.push(user_id),
96+ None => entries.push(Reaction {
97+ emoji,
98+ user_ids: vec![user_id],
99+ }),
100+ }
101+ }
102+
103+ Ok(reactions)
104+}
105+
106+async fn polls_of(
107+ message_ids: &[String],
108+ conn: &Connection,
109+) -> Result<HashMap<String, Poll>, Error> {
110+ let mut polls: HashMap<String, Poll> = HashMap::new();
111+ if message_ids.is_empty() {
112+ return Ok(polls);
113+ }
114+
115+ let placeholders = placeholders(message_ids.len());
116+ let mut rows = conn
117+ .query(
118+ &format!(
119+ "SELECT message_id, question, multiple, closed FROM poll WHERE message_id IN ({placeholders})"
120+ ),
121+ message_ids.to_vec(),
122+ )
123+ .await?;
124+ while let Some(row) = rows.next().await? {
125+ let multiple: i64 = row.get(2)?;
126+ let closed: i64 = row.get(3)?;
127+ polls.insert(
128+ row.get(0)?,
129+ Poll {
130+ question: row.get(1)?,
131+ options: Vec::new(),
132+ multiple: multiple != 0,
133+ closed: closed != 0,
134+ },
135+ );
136+ }
137+ drop(rows);
138+
139+ let mut rows = conn
140+ .query(
141+ &format!(
142+ "SELECT message_id, text FROM poll_option WHERE message_id IN ({placeholders}) ORDER BY message_id, position"
143+ ),
144+ message_ids.to_vec(),
145+ )
146+ .await?;
147+ while let Some(row) = rows.next().await? {
148+ let message_id: String = row.get(0)?;
149+ if let Some(poll) = polls.get_mut(&message_id) {
150+ poll.options.push(PollOption {
151+ text: row.get(1)?,
152+ voter_ids: Vec::new(),
153+ });
154+ }
155+ }
156+ drop(rows);
157+
158+ let mut rows = conn
159+ .query(
160+ &format!(
161+ "SELECT message_id, position, user_id FROM poll_vote WHERE message_id IN ({placeholders}) ORDER BY message_id, position, user_id"
162+ ),
163+ message_ids.to_vec(),
164+ )
165+ .await?;
166+ while let Some(row) = rows.next().await? {
167+ let message_id: String = row.get(0)?;
168+ let position: i64 = row.get(1)?;
169+ let option = polls
170+ .get_mut(&message_id)
171+ .and_then(|poll| poll.options.get_mut(position as usize));
172+ if let Some(option) = option {
173+ option.voter_ids.push(row.get(2)?);
174+ }
175+ }
176+
177+ Ok(polls)
178+}
179+
48 async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippet>, Error> {180 async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippet>, Error> {
49 let mut rows = conn181 let mut rows = conn
50 .query(182 .query(
@@ -60,7 +192,7 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippe
60 192
61 let mut rows = conn193 let mut rows = conn
62 .query(194 .query(
63- "SELECT position, original_id, user_id, username, avatar_id, body FROM snippet_message WHERE message_id = ?1 ORDER BY position",195+ "SELECT position, original_id, user_id, username, avatar_id, body, poll FROM snippet_message WHERE message_id = ?1 ORDER BY position",
64 (message_id,),196 (message_id,),
65 )197 )
66 .await?;198 .await?;
@@ -76,6 +208,9 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippe
76 avatar_id: row.get(4)?,208 avatar_id: row.get(4)?,
77 body: row.get(5)?,209 body: row.get(5)?,
78 attachments: Vec::new(),210 attachments: Vec::new(),
211+ poll: row
212+ .get::<Option<Vec<u8>>>(6)?
213+ .and_then(|bytes| bitcode::decode(&bytes).ok()),
79 },214 },
80 ));215 ));
81 }216 }
@@ -90,11 +225,21 @@ async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippe
90 Ok(Some(Snippet { origin, messages }))225 Ok(Some(Snippet { origin, messages }))
91 }226 }
92 227
93-async fn hydrate(mut message: Message, conn: &Connection) -> Result<Message, Error> {228+async fn hydrate(messages: Vec<Message>, conn: &Connection) -> Result<Vec<Message>, Error> {
94- message.attachments = attachment::of_message(&message.id, None, conn).await?;229+ let ids: Vec<String> = messages.iter().map(|message| message.id.clone()).collect();
95- message.snippet = snippet_of(&message.id, conn).await?;230+ let mut reactions = reactions_of(&ids, conn).await?;
231+ let mut polls = polls_of(&ids, conn).await?;
232+
233+ let mut hydrated = Vec::new();
234+ for mut message in messages {
235+ message.reactions = reactions.remove(&message.id).unwrap_or_default();
236+ message.poll = polls.remove(&message.id);
237+ message.attachments = attachment::of_message(&message.id, None, conn).await?;
238+ message.snippet = snippet_of(&message.id, conn).await?;
239+ hydrated.push(message);
240+ }
96 241
97- Ok(message)242+ Ok(hydrated)
98 }243 }
99 244
100 async fn insert(245 async fn insert(
@@ -114,7 +259,7 @@ async fn insert(
114 Ok(message_id)259 Ok(message_id)
115 }260 }
116 261
117-async fn ensure_in_community(262+pub async fn ensure_in_community(
118 message_id: &str,263 message_id: &str,
119 community_id: &str,264 community_id: &str,
120 conn: &Connection,265 conn: &Connection,
@@ -132,6 +277,28 @@ async fn ensure_in_community(
132 Ok(())277 Ok(())
133 }278 }
134 279
280+pub async fn create_call_log(
281+ community_id: &str,
282+ user_id: &str,
283+ call: CallLog,
284+ conn: &Connection,
285+) -> Result<Message, Error> {
286+ let message_id = new_id();
287+ conn.execute(
288+ "INSERT INTO message (id, user_id, community_id, body, call, call_seconds) VALUES (?1, ?2, ?3, '', ?4, ?5)",
289+ (
290+ message_id.as_str(),
291+ user_id,
292+ community_id,
293+ call.as_str(),
294+ call.seconds() as i64,
295+ ),
296+ )
297+ .await?;
298+
299+ read(&message_id, conn).await
300+}
301+
135 pub async fn create(302 pub async fn create(
136 user_id: &str,303 user_id: &str,
137 community_id: &str,304 community_id: &str,
@@ -159,7 +326,10 @@ pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, Error>
159 let message = from_row(&row)?;326 let message = from_row(&row)?;
160 drop(rows);327 drop(rows);
161 328
162- hydrate(message, conn).await329+ hydrate(vec![message], conn)
330+ .await?
331+ .pop()
332+ .ok_or(CommonError::NotFound.into())
163 }333 }
164 334
165 pub async fn read_page(335 pub async fn read_page(
@@ -183,12 +353,118 @@ pub async fn read_page(
183 drop(rows);353 drop(rows);
184 messages.reverse();354 messages.reverse();
185 355
186- let mut page = Vec::new();356+ hydrate(messages, conn).await
187- for message in messages {357+}
188- page.push(hydrate(message, conn).await?);358+
359+pub async fn create_poll(
360+ user_id: &str,
361+ community_id: &str,
362+ question: &str,
363+ options: &[String],
364+ multiple: bool,
365+ conn: &Connection,
366+) -> Result<Message, Error> {
367+ let message_id = insert(user_id, community_id, "", None, conn).await?;
368+ conn.execute(
369+ "INSERT INTO poll (message_id, question, multiple) VALUES (?1, ?2, ?3)",
370+ (message_id.as_str(), question, multiple as i64),
371+ )
372+ .await?;
373+ for (position, text) in options.iter().enumerate() {
374+ conn.execute(
375+ "INSERT INTO poll_option (message_id, position, text) VALUES (?1, ?2, ?3)",
376+ (message_id.as_str(), position as i64, text.as_str()),
377+ )
378+ .await?;
379+ }
380+
381+ read(&message_id, conn).await
382+}
383+
384+pub async fn vote(
385+ message_id: &str,
386+ user_id: &str,
387+ positions: &[u32],
388+ conn: &Connection,
389+) -> Result<Message, Error> {
390+ conn.execute(
391+ "DELETE FROM poll_vote WHERE message_id = ?1 AND user_id = ?2",
392+ (message_id, user_id),
393+ )
394+ .await?;
395+ for position in positions {
396+ conn.execute(
397+ "INSERT INTO poll_vote (message_id, position, user_id) VALUES (?1, ?2, ?3)",
398+ (message_id, *position as i64, user_id),
399+ )
400+ .await?;
401+ }
402+
403+ read(message_id, conn).await
404+}
405+
406+pub async fn close_poll(message_id: &str, conn: &Connection) -> Result<Message, Error> {
407+ let updated = conn
408+ .execute(
409+ "UPDATE poll SET closed = 1 WHERE message_id = ?1",
410+ (message_id,),
411+ )
412+ .await?;
413+ if updated == 0 {
414+ return Err(CommonError::NotFound.into());
189 }415 }
190 416
191- Ok(page)417+ read(message_id, conn).await
418+}
419+
420+pub async fn react(
421+ message_id: &str,
422+ user_id: &str,
423+ emoji: &str,
424+ conn: &Connection,
425+) -> Result<Message, Error> {
426+ let removed = conn
427+ .execute(
428+ "DELETE FROM reaction WHERE message_id = ?1 AND user_id = ?2 AND emoji = ?3",
429+ (message_id, user_id, emoji),
430+ )
431+ .await?;
432+ if removed == 0 {
433+ conn.execute(
434+ "INSERT INTO reaction (message_id, user_id, emoji) VALUES (?1, ?2, ?3)",
435+ (message_id, user_id, emoji),
436+ )
437+ .await?;
438+ }
439+
440+ read(message_id, conn).await
441+}
442+
443+pub async fn pin(message_id: &str, pinned: bool, conn: &Connection) -> Result<Message, Error> {
444+ conn.execute(
445+ "UPDATE message SET pinned = ?2 WHERE id = ?1",
446+ (message_id, pinned as i64),
447+ )
448+ .await?;
449+
450+ read(message_id, conn).await
451+}
452+
453+pub async fn pinned(community_id: &str, conn: &Connection) -> Result<Vec<Message>, Error> {
454+ let mut rows = conn
455+ .query(
456+ &format!("{SELECT} WHERE m.community_id = ?1 AND m.pinned = 1 ORDER BY m.id DESC"),
457+ (community_id,),
458+ )
459+ .await?;
460+
461+ let mut messages = Vec::new();
462+ while let Some(row) = rows.next().await? {
463+ messages.push(from_row(&row)?);
464+ }
465+ drop(rows);
466+
467+ hydrate(messages, conn).await
192 }468 }
193 469
194 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {470 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {
@@ -303,6 +579,7 @@ async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, Er
303 avatar_id: author.avatar_id,579 avatar_id: author.avatar_id,
304 body: source.body.clone(),580 body: source.body.clone(),
305 attachments: source.attachments.clone(),581 attachments: source.attachments.clone(),
582+ poll: source.poll.clone(),
306 })583 })
307 }584 }
308 585
@@ -323,8 +600,9 @@ async fn write_snippet(
323 600
324 for (position, entry) in entries.iter().enumerate() {601 for (position, entry) in entries.iter().enumerate() {
325 let position = position as i64;602 let position = position as i64;
603+ let poll = entry.poll.as_ref().map(bitcode::encode);
326 conn.execute(604 conn.execute(
327- "INSERT INTO snippet_message (message_id, position, original_id, user_id, username, avatar_id, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",605+ "INSERT INTO snippet_message (message_id, position, original_id, user_id, username, avatar_id, body, poll) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
328 (606 (
329 message_id,607 message_id,
330 position,608 position,
@@ -333,6 +611,7 @@ async fn write_snippet(
333 entry.username.as_str(),611 entry.username.as_str(),
334 entry.avatar_id.as_deref(),612 entry.avatar_id.as_deref(),
335 entry.body.as_str(),613 entry.body.as_str(),
614+ poll,
336 ),615 ),
337 )616 )
338 .await?;617 .await?;
crates/server/src/network.rsmodified+87 -14
@@ -18,7 +18,7 @@ use tokio::{sync::mpsc, task::JoinHandle};
18 use tracing::{info, warn};18 use tracing::{info, warn};
19 19
20 use crate::{20 use crate::{
21- attachment, authentication,21+ attachment, authentication, backup,
22 database::{self, DB},22 database::{self, DB},
23 error::Error,23 error::Error,
24 rate_limit::RateLimit,24 rate_limit::RateLimit,
@@ -35,21 +35,47 @@ type Signed = (String, String, Connection);
35 #[derive(Clone, Default)]35 #[derive(Clone, Default)]
36 pub struct Presence(Arc<Mutex<HashMap<usize, Signed>>>);36 pub struct Presence(Arc<Mutex<HashMap<usize, Signed>>>);
37 37
38+#[derive(Default)]
39+struct VisitBook {
40+ seen: HashMap<usize, HashSet<String>>,
41+ watching: HashMap<usize, String>,
42+}
43+
38 #[derive(Clone, Default)]44 #[derive(Clone, Default)]
39-pub struct Visits(Arc<Mutex<HashMap<usize, HashSet<String>>>>);45+pub struct Visits(Arc<Mutex<VisitBook>>);
40 46
41 impl Visits {47 impl Visits {
42 pub fn first(&self, connection_id: usize, community_id: &str) -> bool {48 pub fn first(&self, connection_id: usize, community_id: &str) -> bool {
43 self.049 self.0
44 .lock()50 .lock()
45 .unwrap()51 .unwrap()
52+ .seen
46 .entry(connection_id)53 .entry(connection_id)
47 .or_default()54 .or_default()
48 .insert(community_id.to_string())55 .insert(community_id.to_string())
49 }56 }
50 57
58+ pub fn watch(&self, connection_id: usize, community_id: Option<&str>) {
59+ let watching = &mut self.0.lock().unwrap().watching;
60+ match community_id {
61+ Some(community_id) => watching.insert(connection_id, community_id.to_string()),
62+ None => watching.remove(&connection_id),
63+ };
64+ }
65+
66+ fn watches(&self, connection_id: usize, community_id: &str) -> bool {
67+ self.0
68+ .lock()
69+ .unwrap()
70+ .watching
71+ .get(&connection_id)
72+ .is_some_and(|watched| watched == community_id)
73+ }
74+
51 pub fn forget(&self, connection_id: usize) {75 pub fn forget(&self, connection_id: usize) {
52- self.0.lock().unwrap().remove(&connection_id);76+ let mut book = self.0.lock().unwrap();
77+ book.seen.remove(&connection_id);
78+ book.watching.remove(&connection_id);
53 }79 }
54 }80 }
55 81
@@ -170,6 +196,7 @@ struct Shared {
170 db: DB,196 db: DB,
171 services: Services,197 services: Services,
172 directory: PathBuf,198 directory: PathBuf,
199+ backups: PathBuf,
173 }200 }
174 201
175 pub async fn serve(202 pub async fn serve(
@@ -177,17 +204,20 @@ pub async fn serve(
177 server_config: quinn::ServerConfig,204 server_config: quinn::ServerConfig,
178 db: DB,205 db: DB,
179 directory: PathBuf,206 directory: PathBuf,
207+ backups: PathBuf,
180 ) -> Result<(), Error> {208 ) -> Result<(), Error> {
181 let endpoint = Endpoint::server(server_config, server_address.parse()?)?;209 let endpoint = Endpoint::server(server_config, server_address.parse()?)?;
182 info!("listening on {server_address}");210 info!("listening on {server_address}");
183 211
184 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH);212 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH);
185- tokio::spawn(the_actor(event_receiver));213+ let services = Services::default();
214+ tokio::spawn(the_actor(event_receiver, services.visits.clone()));
186 let shared = Shared {215 let shared = Shared {
187 event_sender,216 event_sender,
188 db,217 db,
189- services: Services::default(),218+ services,
190 directory,219 directory,
220+ backups,
191 };221 };
192 222
193 while let Some(incoming) = endpoint.accept().await {223 while let Some(incoming) = endpoint.accept().await {
@@ -244,9 +274,11 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro
244 if let Some((user_id, token)) = signed_in(&state) {274 if let Some((user_id, token)) = signed_in(&state) {
245 let conn = database::connect(&shared.db).await?;275 let conn = database::connect(&shared.db).await?;
246 authentication::seen(&user_id, &token, &conn).await?;276 authentication::seen(&user_id, &token, &conn).await?;
247- let broadcasts =277+ let mut broadcasts =
248 request::leave_connection_voice(&shared.services.voice, Some(&connection), &conn)278 request::leave_connection_voice(&shared.services.voice, Some(&connection), &conn)
249 .await?;279 .await?;
280+ broadcasts
281+ .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?);
250 for broadcast in broadcasts {282 for broadcast in broadcasts {
251 let _ = shared283 let _ = shared
252 .event_sender284 .event_sender
@@ -298,6 +330,17 @@ async fn route(
298 )330 )
299 .await331 .await
300 }332 }
333+ StreamKind::Backup => {
334+ let user = signed_user(&state);
335+ backup::download(
336+ user.as_ref(),
337+ receive_stream,
338+ send_stream,
339+ &shared.db,
340+ &shared.backups,
341+ )
342+ .await
343+ }
301 }344 }
302 }345 }
303 346
@@ -317,29 +360,37 @@ async fn answer(
317 &shared.services,360 &shared.services,
318 Some(&connection),361 Some(&connection),
319 &shared.directory,362 &shared.directory,
363+ &shared.backups,
320 )364 )
321 .await;365 .await;
322 let after = signed_in(&state);366 let after = signed_in(&state);
323 367
324 if before != after {368 if before != after {
325 let connection_id = connection.stable_id();369 let connection_id = connection.stable_id();
326- let event = match after {370+ let (event, presence_user_id) = match after {
327 Some((user_id, token)) => {371 Some((user_id, token)) => {
328 shared372 shared
329 .services373 .services
330 .presence374 .presence
331 .sign_in(&connection, &user_id, &token);375 .sign_in(&connection, &user_id, &token);
332- Event::SignedIn {376+ (
333- connection_id,377+ Event::SignedIn {
334- user_id,378+ connection_id,
335- }379+ user_id: user_id.clone(),
380+ },
381+ Some(user_id),
382+ )
336 }383 }
337 None => {384 None => {
338 shared.services.presence.sign_out(connection_id);385 shared.services.presence.sign_out(connection_id);
339- Event::SignedOut { connection_id }386+ let user_id = before.map(|(user_id, _)| user_id);
387+ (Event::SignedOut { connection_id }, user_id)
340 }388 }
341 };389 };
342 let _ = shared.event_sender.send(event).await;390 let _ = shared.event_sender.send(event).await;
391+ if let Some(user_id) = presence_user_id {
392+ broadcast_presence(&shared, &user_id).await;
393+ }
343 }394 }
344 395
345 for broadcast in broadcasts {396 for broadcast in broadcasts {
@@ -354,6 +405,24 @@ async fn answer(
354 Ok(())405 Ok(())
355 }406 }
356 407
408+async fn broadcast_presence(shared: &Shared, user_id: &str) {
409+ let broadcasts = match database::connect(&shared.db).await {
410+ Ok(conn) => request::presence_changed(&shared.services.presence, user_id, &conn).await,
411+ Err(error) => Err(error),
412+ };
413+ match broadcasts {
414+ Ok(broadcasts) => {
415+ for broadcast in broadcasts {
416+ let _ = shared
417+ .event_sender
418+ .send(Event::Broadcast(Box::new(broadcast)))
419+ .await;
420+ }
421+ }
422+ Err(error) => warn!("presence: {error}"),
423+ }
424+}
425+
357 fn signed_user(state: &Mutex<State>) -> Option<User> {426 fn signed_user(state: &Mutex<State>) -> Option<User> {
358 match &*state.lock().unwrap() {427 match &*state.lock().unwrap() {
359 State::Anonymous => None,428 State::Anonymous => None,
@@ -384,7 +453,7 @@ async fn write_session(mut event_receiver: mpsc::Receiver<Arc<Push>>, mut send_s
384 }453 }
385 }454 }
386 455
387-async fn the_actor(mut event_receiver: mpsc::Receiver<Event>) {456+async fn the_actor(mut event_receiver: mpsc::Receiver<Event>, visits: Visits) {
388 let mut sessions: Vec<Session> = Vec::new();457 let mut sessions: Vec<Session> = Vec::new();
389 458
390 while let Some(event) = event_receiver.recv().await {459 while let Some(event) = event_receiver.recv().await {
@@ -429,13 +498,17 @@ async fn the_actor(mut event_receiver: mpsc::Receiver<Event>) {
429 }498 }
430 }499 }
431 Event::Broadcast(broadcast) => {500 Event::Broadcast(broadcast) => {
501+ let community_id = broadcast.event.community_id().map(str::to_string);
432 let event = Arc::new(broadcast.event);502 let event = Arc::new(broadcast.event);
433 503
434 sessions.retain(|session| {504 sessions.retain(|session| {
435 let Some(user_id) = &session.user_id else {505 let Some(user_id) = &session.user_id else {
436 return true;506 return true;
437 };507 };
438- if !broadcast.user_ids.contains(user_id) {508+ let watching = community_id.as_deref().is_some_and(|community_id| {
509+ visits.watches(session.connection_id, community_id)
510+ });
511+ if !broadcast.user_ids.contains(user_id) && !watching {
439 return true;512 return true;
440 }513 }
441 514
crates/server/src/notes.rsadded+36 -0
@@ -0,0 +1,36 @@
1+use common::model::{Community, Rank};
2+use turso::Connection;
3+
4+use crate::{community, error::Error, user_community};
5+
6+async fn find(user_id: &str, conn: &Connection) -> Result<Option<String>, Error> {
7+ let mut rows = conn
8+ .query(
9+ "SELECT community_id FROM notes WHERE user_id = ?1",
10+ (user_id,),
11+ )
12+ .await?;
13+
14+ Ok(rows.next().await?.map(|row| row.get(0)).transpose()?)
15+}
16+
17+pub async fn open(me: &str, conn: &mut Connection) -> Result<Community, Error> {
18+ let tx = conn.transaction().await?;
19+ let community_id = match find(me, &tx).await? {
20+ Some(community_id) => community_id,
21+ None => {
22+ let community_id = community::create_notes(&tx).await?;
23+ user_community::join(me, &community_id, Rank::Owner, &tx).await?;
24+ tx.execute(
25+ "INSERT INTO notes (user_id, community_id) VALUES (?1, ?2)",
26+ (me, community_id.as_str()),
27+ )
28+ .await?;
29+ community_id
30+ }
31+ };
32+ let community = community::read(&community_id, me, &tx).await?;
33+ tx.commit().await?;
34+
35+ Ok(community)
36+}
crates/server/src/rate_limit.rsmodified+11 -5
@@ -3,7 +3,10 @@ use std::{
3 sync::{Arc, Mutex},3 sync::{Arc, Mutex},
4 };4 };
5 5
6-use common::time::{MINUTE_MILLIS, now_ms};6+use common::{
7+ error::Error,
8+ time::{MINUTE_MILLIS, now_ms},
9+};
7 10
8 const PRUNE_LENGTH: usize = 4096;11 const PRUNE_LENGTH: usize = 4096;
9 12
@@ -11,9 +14,9 @@ const PRUNE_LENGTH: usize = 4096;
11 pub struct RateLimit(Arc<Mutex<HashMap<String, (u64, u32)>>>);14 pub struct RateLimit(Arc<Mutex<HashMap<String, (u64, u32)>>>);
12 15
13 impl RateLimit {16 impl RateLimit {
14- pub fn allow(&self, key: &str, limit: u32) -> bool {17+ pub fn allow(&self, key: &str, limit: u32) -> Result<(), Error> {
15 if limit == 0 {18 if limit == 0 {
16- return true;19+ return Ok(());
17 }20 }
18 21
19 let now = now_ms();22 let now = now_ms();
@@ -27,10 +30,13 @@ impl RateLimit {
27 *window = (now, 0);30 *window = (now, 0);
28 }31 }
29 if window.1 >= limit {32 if window.1 >= limit {
30- return false;33+ let wait = MINUTE_MILLIS - now.saturating_sub(window.0);
34+ return Err(Error::RateLimited {
35+ retry_after_seconds: wait.div_ceil(1000),
36+ });
31 }37 }
32 window.1 += 1;38 window.1 += 1;
33 39
34- true40+ Ok(())
35 }41 }
36 }42 }
crates/server/src/request.rsmodified+436 -44
@@ -8,8 +8,8 @@ use common::{
8 error::Error as CommonError,8 error::Error as CommonError,
9 event::Event,9 event::Event,
10 model::{10 model::{
11- AdminAction, CommunityKind, CommunitySummary, LogAction, Member, Rank, ReportStatus,11+ AdminAction, CallLog, CommunityKind, CommunitySummary, LogAction, Member, Presence, Rank,
12- ServerBanKind, ServerSettings, User, VoiceRoom,12+ ReportStatus, ServerBanKind, ServerSettings, User, VoiceRoom,
13 },13 },
14 permission,14 permission,
15 request::Request,15 request::Request,
@@ -17,21 +17,22 @@ use common::{
17 time::{self, MINUTE_MILLIS},17 time::{self, MINUTE_MILLIS},
18 validate::{18 validate::{
19 validate_avatar_size, validate_forward, validate_message_body, validate_new_message,19 validate_avatar_size, validate_forward, validate_message_body, validate_new_message,
20- validate_reason, validate_server_settings,20+ validate_poll, validate_reaction, validate_reason, validate_server_settings, validate_vote,
21 },21 },
22 };22 };
23 use turso::Connection;23 use turso::Connection;
24 24
25 use crate::{25 use crate::{
26- admin_log, attachment, authentication, community,26+ admin_log, attachment, authentication, backup, community,
27 database::{self, DB},27 database::{self, DB},
28 direct,28 direct,
29 error::Error,29 error::Error,
30 friend, invitation, invite, log, message,30 friend, invitation, invite, log, message,
31- network::{Services, State},31+ network::{self, Services, State},
32- overview, rate_limit::RateLimit, report, server_ban, server_settings, stats, user,32+ notes, overview,
33- user_community,33+ rate_limit::RateLimit,
34- voice::{Left, Voice},34+ report, server_ban, server_settings, stats, user, user_community,
35+ voice::{CallEnd, GhostChange, Left, Voice},
35 };36 };
36 37
37 pub struct Broadcast {38 pub struct Broadcast {
@@ -48,8 +49,9 @@ pub async fn handle(
48 services: &Services,49 services: &Services,
49 connection: Option<&quinn::Connection>,50 connection: Option<&quinn::Connection>,
50 directory: &Path,51 directory: &Path,
52+ backups: &Path,
51 ) -> Outcome {53 ) -> Outcome {
52- match dispatch(request, state, db, services, connection, directory).await {54+ match dispatch(request, state, db, services, connection, directory, backups).await {
53 Ok(outcome) => outcome,55 Ok(outcome) => outcome,
54 Err(error) => (Response::Error(error.into()), Vec::new()),56 Err(error) => (Response::Error(error.into()), Vec::new()),
55 }57 }
@@ -62,6 +64,7 @@ async fn dispatch(
62 services: &Services,64 services: &Services,
63 connection: Option<&quinn::Connection>,65 connection: Option<&quinn::Connection>,
64 directory: &Path,66 directory: &Path,
67+ backups: &Path,
65 ) -> Result<Outcome, Error> {68 ) -> Result<Outcome, Error> {
66 let Services {69 let Services {
67 voice,70 voice,
@@ -347,7 +350,10 @@ async fn dispatch(
347 &conn,350 &conn,
348 )351 )
349 .await?;352 .await?;
350- let broadcasts = user_updated(&user, &conn).await?;353+ let mut broadcasts = user_updated(&user, &conn).await?;
354+ if permission::is_builder(role) {
355+ broadcasts.extend(voice_unmuted(voice, &user_id, &conn).await?);
356+ }
351 (Response::User(user), broadcasts)357 (Response::User(user), broadcasts)
352 }358 }
353 Request::UpdateStatus { status } => {359 Request::UpdateStatus { status } => {
@@ -363,6 +369,23 @@ async fn dispatch(
363 let broadcasts = user_updated(&user, &conn).await?;369 let broadcasts = user_updated(&user, &conn).await?;
364 (Response::User(user), broadcasts)370 (Response::User(user), broadcasts)
365 }371 }
372+ Request::UpdatePresence { presence: chosen } => {
373+ let (me, _) = authenticated(state, &conn).await?;
374+ user::update_presence(&me.id, chosen, &conn).await?;
375+ let broadcasts = presence_changed(presence, &me.id, &conn).await?;
376+ (Response::Done, broadcasts)
377+ }
378+ Request::ReadPresences => {
379+ let (me, _) = authenticated(state, &conn).await?;
380+ let mut presences = Vec::new();
381+ for user_id in related_user_ids(&me.id, &conn).await? {
382+ let effective = effective_presence(presence, &user_id, &conn).await?;
383+ if effective != Presence::Offline || user_id == me.id {
384+ presences.push((user_id, effective));
385+ }
386+ }
387+ (Response::Presences(presences), Vec::new())
388+ }
366 Request::UpdateAvatar { image } => {389 Request::UpdateAvatar { image } => {
367 let (me, token) = authenticated(state, &conn).await?;390 let (me, token) = authenticated(state, &conn).await?;
368 validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?;391 validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?;
@@ -445,7 +468,7 @@ async fn dispatch(
445 Request::CreateCommunity { name } => {468 Request::CreateCommunity { name } => {
446 let (me, _) = authenticated(state, &conn).await?;469 let (me, _) = authenticated(state, &conn).await?;
447 let limit = server_settings::read(&conn).await?.max_communities_per_user;470 let limit = server_settings::read(&conn).await?.max_communities_per_user;
448- let owned = user_community::owned(&me.id, &conn).await?.len();471+ let owned = user_community::owned_groups(&me.id, &conn).await?;
449 ensure_or(472 ensure_or(
450 limit == 0 || owned < limit as usize,473 limit == 0 || owned < limit as usize,
451 CommonError::LimitReached,474 CommonError::LimitReached,
@@ -459,6 +482,9 @@ async fn dispatch(
459 }482 }
460 Request::ReadCommunity { community_id } => {483 Request::ReadCommunity { community_id } => {
461 let (me, _) = authenticated(state, &conn).await?;484 let (me, _) = authenticated(state, &conn).await?;
485+ ensure(permission::can_read(
486+ actor_rank(&me, &community_id, &conn).await?,
487+ ))?;
462 (488 (
463 Response::Community(community::read(&community_id, &me.id, &conn).await?),489 Response::Community(community::read(&community_id, &me.id, &conn).await?),
464 Vec::new(),490 Vec::new(),
@@ -466,7 +492,7 @@ async fn dispatch(
466 }492 }
467 Request::UpdateCommunity { community_id, name } => {493 Request::UpdateCommunity { community_id, name } => {
468 let (me, _) = authenticated(state, &conn).await?;494 let (me, _) = authenticated(state, &conn).await?;
469- ensure(!community::is_direct(&community_id, &conn).await?)?;495+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
470 ensure(permission::can_rename_community(496 ensure(permission::can_rename_community(
471 actor_rank(&me, &community_id, &conn).await?,497 actor_rank(&me, &community_id, &conn).await?,
472 ))?;498 ))?;
@@ -484,7 +510,7 @@ async fn dispatch(
484 image,510 image,
485 } => {511 } => {
486 let (me, _) = authenticated(state, &conn).await?;512 let (me, _) = authenticated(state, &conn).await?;
487- ensure(!community::is_direct(&community_id, &conn).await?)?;513+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
488 ensure(permission::can_rename_community(514 ensure(permission::can_rename_community(
489 actor_rank(&me, &community_id, &conn).await?,515 actor_rank(&me, &community_id, &conn).await?,
490 ))?;516 ))?;
@@ -505,7 +531,7 @@ async fn dispatch(
505 }531 }
506 Request::DeleteCommunity { community_id } => {532 Request::DeleteCommunity { community_id } => {
507 let (me, _) = authenticated(state, &conn).await?;533 let (me, _) = authenticated(state, &conn).await?;
508- ensure(!community::is_direct(&community_id, &conn).await?)?;534+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
509 ensure(permission::can_delete_community(535 ensure(permission::can_delete_community(
510 actor_rank(&me, &community_id, &conn).await?,536 actor_rank(&me, &community_id, &conn).await?,
511 ))?;537 ))?;
@@ -534,7 +560,7 @@ async fn dispatch(
534 }560 }
535 Request::LeaveCommunity { community_id } => {561 Request::LeaveCommunity { community_id } => {
536 let (me, _) = authenticated(state, &conn).await?;562 let (me, _) = authenticated(state, &conn).await?;
537- ensure(!community::is_direct(&community_id, &conn).await?)?;563+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
538 ensure(permission::can_leave(564 ensure(permission::can_leave(
539 actor_rank(&me, &community_id, &conn).await?,565 actor_rank(&me, &community_id, &conn).await?,
540 ))?;566 ))?;
@@ -644,7 +670,7 @@ async fn dispatch(
644 rank,670 rank,
645 } => {671 } => {
646 let (me, _) = authenticated(state, &conn).await?;672 let (me, _) = authenticated(state, &conn).await?;
647- ensure(!community::is_direct(&community_id, &conn).await?)?;673+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
648 let target = user::read(&user_id, &conn).await?;674 let target = user::read(&user_id, &conn).await?;
649 ensure(permission::can_set_rank(675 ensure(permission::can_set_rank(
650 actor_rank(&me, &community_id, &conn).await?,676 actor_rank(&me, &community_id, &conn).await?,
@@ -699,7 +725,10 @@ async fn dispatch(
699 tx.commit().await?;725 tx.commit().await?;
700 let members = user_community::members(&community_id, &conn).await?;726 let members = user_community::members(&community_id, &conn).await?;
701 let event = Event::MessageCreated(created.clone());727 let event = Event::MessageCreated(created.clone());
702- (Response::Message(created), broadcast(event, &members))728+ (
729+ Response::Message(created),
730+ broadcast_with(event, &members, &me.id),
731+ )
703 }732 }
704 Request::ForwardMessages {733 Request::ForwardMessages {
705 message_ids,734 message_ids,
@@ -728,7 +757,7 @@ async fn dispatch(
728 let mut broadcasts = Vec::new();757 let mut broadcasts = Vec::new();
729 for message in &created {758 for message in &created {
730 let event = Event::MessageCreated(message.clone());759 let event = Event::MessageCreated(message.clone());
731- broadcasts.extend(broadcast(event, &members));760+ broadcasts.extend(broadcast_with(event, &members, &me.id));
732 }761 }
733 (Response::Messages(created), broadcasts)762 (Response::Messages(created), broadcasts)
734 }763 }
@@ -743,7 +772,120 @@ async fn dispatch(
743 let updated = message::update(&message_id, &body, &conn).await?;772 let updated = message::update(&message_id, &body, &conn).await?;
744 let members = user_community::members(&updated.community_id, &conn).await?;773 let members = user_community::members(&updated.community_id, &conn).await?;
745 let event = Event::MessageUpdated(updated.clone());774 let event = Event::MessageUpdated(updated.clone());
746- (Response::Message(updated), broadcast(event, &members))775+ (
776+ Response::Message(updated),
777+ broadcast_with(event, &members, &me.id),
778+ )
779+ }
780+ Request::CreatePoll {
781+ community_id,
782+ question,
783+ options,
784+ multiple,
785+ } => {
786+ let (me, _) = authenticated(state, &conn).await?;
787+ let settings = server_settings::read(&conn).await?;
788+ limit_messages(&me, rate_limit, &settings)?;
789+ validate_poll(&question, &options)?;
790+ ensure(permission::can_post(
791+ actor_rank(&me, &community_id, &conn).await?,
792+ ))?;
793+ let tx = conn.transaction().await?;
794+ let created =
795+ message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx)
796+ .await?;
797+ stats::mark_active(&me.id, &tx).await?;
798+ tx.commit().await?;
799+ let members = user_community::members(&community_id, &conn).await?;
800+ let event = Event::MessageCreated(created.clone());
801+ (
802+ Response::Message(created),
803+ broadcast_with(event, &members, &me.id),
804+ )
805+ }
806+ Request::Vote {
807+ message_id,
808+ positions,
809+ } => {
810+ let (me, _) = authenticated(state, &conn).await?;
811+ let existing = message::read(&message_id, &conn).await?;
812+ ensure(permission::can_read(
813+ actor_rank(&me, &existing.community_id, &conn).await?,
814+ ))?;
815+ let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?;
816+ validate_vote(poll, &positions)?;
817+ let updated = message::vote(&message_id, &me.id, &positions, &conn).await?;
818+ let members = user_community::members(&updated.community_id, &conn).await?;
819+ let event = Event::MessageUpdated(updated);
820+ (Response::Done, broadcast_with(event, &members, &me.id))
821+ }
822+ Request::ClosePoll { message_id } => {
823+ let (me, _) = authenticated(state, &conn).await?;
824+ let existing = message::read(&message_id, &conn).await?;
825+ ensure(permission::can_close_poll(
826+ actor_rank(&me, &existing.community_id, &conn).await?,
827+ existing.user_id == me.id,
828+ ))?;
829+ let updated = message::close_poll(&message_id, &conn).await?;
830+ let members = user_community::members(&updated.community_id, &conn).await?;
831+ let event = Event::MessageUpdated(updated);
832+ (Response::Done, broadcast_with(event, &members, &me.id))
833+ }
834+ Request::React { message_id, emoji } => {
835+ let (me, _) = authenticated(state, &conn).await?;
836+ validate_reaction(&emoji)?;
837+ let existing = message::read(&message_id, &conn).await?;
838+ ensure(permission::can_read(
839+ actor_rank(&me, &existing.community_id, &conn).await?,
840+ ))?;
841+ let updated = message::react(&message_id, &me.id, &emoji, &conn).await?;
842+ let members = user_community::members(&updated.community_id, &conn).await?;
843+ let event = Event::MessageUpdated(updated);
844+ (Response::Done, broadcast_with(event, &members, &me.id))
845+ }
846+ Request::Pin { message_id, pinned } => {
847+ let (me, _) = authenticated(state, &conn).await?;
848+ let existing = message::read(&message_id, &conn).await?;
849+ let direct = community::is_direct(&existing.community_id, &conn).await?;
850+ ensure(permission::can_pin(
851+ actor_rank(&me, &existing.community_id, &conn).await?,
852+ direct,
853+ ))?;
854+ let updated = message::pin(&message_id, pinned, &conn).await?;
855+ let members = user_community::members(&updated.community_id, &conn).await?;
856+ let event = Event::MessageUpdated(updated);
857+ (Response::Done, broadcast_with(event, &members, &me.id))
858+ }
859+ Request::Unreads => {
860+ let (me, _) = authenticated(state, &conn).await?;
861+ (
862+ Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?),
863+ Vec::new(),
864+ )
865+ }
866+ Request::MarkRead {
867+ community_id,
868+ message_id,
869+ } => {
870+ let (me, _) = authenticated(state, &conn).await?;
871+ ensure(
872+ user_community::rank(&me.id, &community_id, &conn)
873+ .await?
874+ .is_some(),
875+ )?;
876+ message::ensure_in_community(&message_id, &community_id, &conn).await?;
877+ user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?;
878+ (Response::Done, Vec::new())
879+ }
880+ Request::Pins { community_id } => {
881+ let (me, _) = authenticated(state, &conn).await?;
882+ ensure(permission::can_read(
883+ actor_rank(&me, &community_id, &conn).await?,
884+ ))?;
885+ (
886+ Response::Messages(message::pinned(&community_id, &conn).await?),
887+ Vec::new(),
888+ )
747 }889 }
748 Request::DeleteMessage { message_id } => {890 Request::DeleteMessage { message_id } => {
749 let (me, _) = authenticated(state, &conn).await?;891 let (me, _) = authenticated(state, &conn).await?;
@@ -778,7 +920,10 @@ async fn dispatch(
778 }920 }
779 let members = user_community::members(&deleted.community_id, &conn).await?;921 let members = user_community::members(&deleted.community_id, &conn).await?;
780 let event = Event::MessageDeleted(deleted.clone());922 let event = Event::MessageDeleted(deleted.clone());
781- (Response::Message(deleted), broadcast(event, &members))923+ (
924+ Response::Message(deleted),
925+ broadcast_with(event, &members, &me.id),
926+ )
782 }927 }
783 Request::ReadMessages {928 Request::ReadMessages {
784 community_id,929 community_id,
@@ -788,11 +933,20 @@ async fn dispatch(
788 ensure(permission::can_read(933 ensure(permission::can_read(
789 actor_rank(&me, &community_id, &conn).await?,934 actor_rank(&me, &community_id, &conn).await?,
790 ))?;935 ))?;
936+ let outsider = user_community::rank(&me.id, &community_id, &conn)
937+ .await?
938+ .is_none();
939+ if before.is_none()
940+ && let Some(connection) = connection
941+ {
942+ visits.watch(
943+ connection.stable_id(),
944+ outsider.then_some(community_id.as_str()),
945+ );
946+ }
791 let visit = before.is_none()947 let visit = before.is_none()
792 && permission::is_builder(me.role)948 && permission::is_builder(me.role)
793- && user_community::rank(&me.id, &community_id, &conn)949+ && outsider
794- .await?
795- .is_none()
796 && user::is_ghost(&me.id, &conn).await?;950 && user::is_ghost(&me.id, &conn).await?;
797 if visit951 if visit
798 && connection952 && connection
@@ -816,18 +970,34 @@ async fn dispatch(
816 ensure(permission::can_join_voice(970 ensure(permission::can_join_voice(
817 actor_rank(&me, &community_id, &conn).await?,971 actor_rank(&me, &community_id, &conn).await?,
818 ))?;972 ))?;
819- ensure(community::voice_enabled(&community_id, &conn).await?)?;973+ ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?;
974+ ensure(
975+ permission::is_builder(me.role)
976+ || community::voice_enabled(&community_id, &conn).await?,
977+ )?;
820 let Some(connection) = connection else {978 let Some(connection) = connection else {
821 return Err(CommonError::Server.into());979 return Err(CommonError::Server.into());
822 };980 };
823 let members = user_community::members(&community_id, &conn).await?;981 let members = user_community::members(&community_id, &conn).await?;
824 let muted = user::voice_muted(&me.id, &conn).await?;982 let muted = user::voice_muted(&me.id, &conn).await?;
825- let ghost = user::is_ghost(&me.id, &conn).await?;983+ let outsider = user_community::rank(&me.id, &community_id, &conn)
984+ .await?
985+ .is_none();
986+ let ghost = outsider || user::is_ghost(&me.id, &conn).await?;
987+ let starts_call = !ghost
988+ && community::is_direct(&community_id, &conn).await?
989+ && voice.participants(&community_id).is_empty();
826 let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost);990 let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost);
827 let mut broadcasts = match joined {991 let mut broadcasts = match joined {
828 Some(previous) => voice_left(previous, &conn).await?,992 Some(previous) => voice_left(previous, &conn).await?,
829 None => Vec::new(),993 None => Vec::new(),
830 };994 };
995+ if starts_call {
996+ let created =
997+ message::create_call_log(&community_id, &me.id, CallLog::Started, &conn)
998+ .await?;
999+ broadcasts.extend(broadcast(Event::MessageCreated(created), &members));
1000+ }
831 if !ghost {1001 if !ghost {
832 let event = Event::VoiceJoined {1002 let event = Event::VoiceJoined {
833 community_id: community_id.clone(),1003 community_id: community_id.clone(),
@@ -847,6 +1017,27 @@ async fn dispatch(
847 broadcasts,1017 broadcasts,
848 )1018 )
849 }1019 }
1020+ Request::Typing { community_id } => {
1021+ let (me, _) = authenticated(state, &conn).await?;
1022+ ensure(permission::can_read(
1023+ actor_rank(&me, &community_id, &conn).await?,
1024+ ))?;
1025+ let broadcasts = if user::is_ghost(&me.id, &conn).await? {
1026+ Vec::new()
1027+ } else {
1028+ let members: Vec<Member> = user_community::members(&community_id, &conn)
1029+ .await?
1030+ .into_iter()
1031+ .filter(|member| member.user.id != me.id)
1032+ .collect();
1033+ let event = Event::Typing {
1034+ community_id,
1035+ user_id: me.id.clone(),
1036+ };
1037+ broadcast(event, &members)
1038+ };
1039+ (Response::Done, broadcasts)
1040+ }
850 Request::LeaveVoice => {1041 Request::LeaveVoice => {
851 authenticated(state, &conn).await?;1042 authenticated(state, &conn).await?;
852 (1043 (
@@ -854,6 +1045,23 @@ async fn dispatch(
854 leave_connection_voice(voice, connection, &conn).await?,1045 leave_connection_voice(voice, connection, &conn).await?,
855 )1046 )
856 }1047 }
1048+ Request::DeclineCall { community_id } => {
1049+ let (me, _) = authenticated(state, &conn).await?;
1050+ ensure(community::is_direct(&community_id, &conn).await?)?;
1051+ ensure(permission::can_read(
1052+ actor_rank(&me, &community_id, &conn).await?,
1053+ ))?;
1054+ let participants = voice.participants(&community_id);
1055+ ensure(!participants.is_empty() && !participants.contains(&me.id))?;
1056+ voice.decline(&community_id);
1057+ let created =
1058+ message::create_call_log(&community_id, &me.id, CallLog::Declined, &conn).await?;
1059+ let members = user_community::members(&community_id, &conn).await?;
1060+ (
1061+ Response::Done,
1062+ broadcast(Event::MessageCreated(created), &members),
1063+ )
1064+ }
857 Request::VoiceParticipants { community_id } => {1065 Request::VoiceParticipants { community_id } => {
858 let (me, _) = authenticated(state, &conn).await?;1066 let (me, _) = authenticated(state, &conn).await?;
859 ensure(permission::can_read(1067 ensure(permission::can_read(
@@ -886,6 +1094,13 @@ async fn dispatch(
886 };1094 };
887 (Response::Community(community), broadcasts)1095 (Response::Community(community), broadcasts)
888 }1096 }
1097+ Request::OpenNotes => {
1098+ let (me, _) = authenticated(state, &conn).await?;
1099+ (
1100+ Response::Community(notes::open(&me.id, &mut conn).await?),
1101+ Vec::new(),
1102+ )
1103+ }
889 Request::Friends => {1104 Request::Friends => {
890 let (me, _) = authenticated(state, &conn).await?;1105 let (me, _) = authenticated(state, &conn).await?;
891 (1106 (
@@ -916,7 +1131,7 @@ async fn dispatch(
916 user_id,1131 user_id,
917 } => {1132 } => {
918 let (me, _) = authenticated(state, &conn).await?;1133 let (me, _) = authenticated(state, &conn).await?;
919- ensure(!community::is_direct(&community_id, &conn).await?)?;1134+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
920 ensure(permission::can_read(1135 ensure(permission::can_read(
921 actor_rank(&me, &community_id, &conn).await?,1136 actor_rank(&me, &community_id, &conn).await?,
922 ))?;1137 ))?;
@@ -1014,7 +1229,7 @@ async fn dispatch(
1014 user_id,1229 user_id,
1015 } => {1230 } => {
1016 let (me, _) = authenticated(state, &conn).await?;1231 let (me, _) = authenticated(state, &conn).await?;
1017- ensure(!community::is_direct(&community_id, &conn).await?)?;1232+ ensure(!community::is_fixed(&community_id, &conn).await?)?;
1018 ensure(permission::can_transfer_ownership(1233 ensure(permission::can_transfer_ownership(
1019 actor_rank(&me, &community_id, &conn).await?,1234 actor_rank(&me, &community_id, &conn).await?,
1020 ))?;1235 ))?;
@@ -1234,6 +1449,15 @@ async fn dispatch(
1234 .await?;1449 .await?;
1235 (Response::MessageHits(hits), Vec::new())1450 (Response::MessageHits(hits), Vec::new())
1236 }1451 }
1452+ Request::SearchCommunity { community_id, text } => {
1453+ let (me, _) = authenticated(state, &conn).await?;
1454+ ensure(permission::can_read(
1455+ actor_rank(&me, &community_id, &conn).await?,
1456+ ))?;
1457+ let hits =
1458+ message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?;
1459+ (Response::MessageHits(hits), Vec::new())
1460+ }
1237 Request::PurgeUser { user_id } => {1461 Request::PurgeUser { user_id } => {
1238 let (me, _) = authenticated(state, &conn).await?;1462 let (me, _) = authenticated(state, &conn).await?;
1239 managed(&me, &user_id, &conn).await?;1463 managed(&me, &user_id, &conn).await?;
@@ -1312,6 +1536,32 @@ async fn dispatch(
1312 let (users, communities) = attachment::usage(&conn).await?;1536 let (users, communities) = attachment::usage(&conn).await?;
1313 (Response::StorageUsage { users, communities }, Vec::new())1537 (Response::StorageUsage { users, communities }, Vec::new())
1314 }1538 }
1539+ Request::CreateBackup => {
1540+ let (me, _) = authenticated(state, &conn).await?;
1541+ ensure(permission::is_builder(me.role))?;
1542+ let backup = backup::create(&conn, backups).await?;
1543+ let action = AdminAction::BackupCreated {
1544+ name: backup.name.clone(),
1545+ };
1546+ admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1547+ (Response::Backup(backup), Vec::new())
1548+ }
1549+ Request::Backups => {
1550+ let (me, _) = authenticated(state, &conn).await?;
1551+ ensure(permission::is_builder(me.role))?;
1552+ (Response::Backups(backup::list(backups)?), Vec::new())
1553+ }
1554+ Request::DeleteBackup { name } => {
1555+ let (me, _) = authenticated(state, &conn).await?;
1556+ ensure(permission::is_builder(me.role))?;
1557+ backup::delete(&name, backups)?;
1558+ let action = AdminAction::BackupDeleted { name };
1559+ admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1560+ (Response::Done, Vec::new())
1561+ }
1562+ Request::DownloadBackup { .. } => {
1563+ return Err(CommonError::Server.into());
1564+ }
1315 Request::VoiceRooms => {1565 Request::VoiceRooms => {
1316 let (me, _) = authenticated(state, &conn).await?;1566 let (me, _) = authenticated(state, &conn).await?;
1317 ensure(permission::is_builder(me.role))?;1567 ensure(permission::is_builder(me.role))?;
@@ -1390,7 +1640,7 @@ async fn dispatch(
1390 tx.commit().await?;1640 tx.commit().await?;
1391 let mut broadcasts = Vec::new();1641 let mut broadcasts = Vec::new();
1392 if !enabled {1642 if !enabled {
1393- broadcasts.extend(voice_closed(voice, &community_id, &conn).await?);1643+ broadcasts.extend(voice_silenced(voice, &community_id, &conn).await?);
1394 }1644 }
1395 let event = Event::CommunityUpdated(updated.clone());1645 let event = Event::CommunityUpdated(updated.clone());
1396 broadcasts.extend(broadcast(event, &members));1646 broadcasts.extend(broadcast(event, &members));
@@ -1408,9 +1658,23 @@ async fn dispatch(
1408 };1658 };
1409 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;1659 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1410 let mut broadcasts = Vec::new();1660 let mut broadcasts = Vec::new();
1411- if let Some((community_id, seconds)) = voice.set_ghost(&me.id, enabled) {1661+ let outsider = match voice.room_of(&me.id) {
1662+ Some(community_id) => user_community::rank(&me.id, &community_id, &conn)
1663+ .await?
1664+ .is_none(),
1665+ None => false,
1666+ };
1667+ if !outsider
1668+ && let Some(GhostChange {
1669+ community_id,
1670+ ghost_seconds: seconds,
1671+ call,
1672+ }) = voice.set_ghost(&me.id, enabled)
1673+ {
1412 let members = user_community::members(&community_id, &conn).await?;1674 let members = user_community::members(&community_id, &conn).await?;
1413 if enabled {1675 if enabled {
1676+ broadcasts
1677+ .extend(call_ended(&community_id, &me.id, call, &members, &conn).await?);
1414 broadcasts.push(Broadcast {1678 broadcasts.push(Broadcast {
1415 event: Event::VoiceLeft {1679 event: Event::VoiceLeft {
1416 community_id,1680 community_id,
@@ -1513,10 +1777,7 @@ async fn limit_logins(
1513 ) -> Result<(), Error> {1777 ) -> Result<(), Error> {
1514 let limit = server_settings::read(conn).await?.logins_per_minute;1778 let limit = server_settings::read(conn).await?.logins_per_minute;
1515 1779
1516- ensure_or(1780+ Ok(rate_limit.allow(&address(connection), limit)?)
1517- rate_limit.allow(&address(connection), limit),
1518- CommonError::RateLimited,
1519- )
1520 }1781 }
1521 1782
1522 fn limit_messages(1783 fn limit_messages(
@@ -1528,10 +1789,7 @@ fn limit_messages(
1528 return Ok(());1789 return Ok(());
1529 }1790 }
1530 1791
1531- ensure_or(1792+ Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?)
1532- rate_limit.allow(&me.id, settings.messages_per_minute),
1533- CommonError::RateLimited,
1534- )
1535 }1793 }
1536 1794
1537 fn ensure_untaken(taken: bool) -> Result<(), Error> {1795 fn ensure_untaken(taken: bool) -> Result<(), Error> {
@@ -1579,7 +1837,7 @@ async fn remove_member(
1579 banned,1837 banned,
1580 } = removal;1838 } = removal;
1581 validate_reason(reason.as_deref())?;1839 validate_reason(reason.as_deref())?;
1582- ensure(!community::is_direct(&community_id, conn).await?)?;1840+ ensure(!community::is_fixed(&community_id, conn).await?)?;
1583 let target = user::read(&user_id, conn).await?;1841 let target = user::read(&user_id, conn).await?;
1584 ensure(permission::can_moderate(1842 ensure(permission::can_moderate(
1585 actor_rank(me, &community_id, conn).await?,1843 actor_rank(me, &community_id, conn).await?,
@@ -1620,20 +1878,52 @@ async fn remove_member(
1620 Ok((Response::Done, broadcasts))1878 Ok((Response::Done, broadcasts))
1621 }1879 }
1622 1880
1623-async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {1881+async fn related_user_ids(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
1624- let mut user_ids = BTreeSet::from([user.id.clone()]);1882+ let mut user_ids = BTreeSet::from([user_id.to_string()]);
1625- for community in community::communities_of(&user.id, conn).await? {1883+ for community in community::communities_of(user_id, conn).await? {
1626 for member in user_community::members(&community.id, conn).await? {1884 for member in user_community::members(&community.id, conn).await? {
1627 user_ids.insert(member.user.id);1885 user_ids.insert(member.user.id);
1628 }1886 }
1629 }1887 }
1630- for friend in friend::state(&user.id, conn).await?.friends {1888+ for friend in friend::state(user_id, conn).await?.friends {
1631 user_ids.insert(friend.id);1889 user_ids.insert(friend.id);
1632 }1890 }
1633 1891
1892+ Ok(user_ids.into_iter().collect())
1893+}
1894+
1895+async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
1634 Ok(vec![Broadcast {1896 Ok(vec![Broadcast {
1635 event: Event::UserUpdated(user.clone()),1897 event: Event::UserUpdated(user.clone()),
1636- user_ids: user_ids.into_iter().collect(),1898+ user_ids: related_user_ids(&user.id, conn).await?,
1899+ }])
1900+}
1901+
1902+async fn effective_presence(
1903+ presence: &network::Presence,
1904+ user_id: &str,
1905+ conn: &Connection,
1906+) -> Result<Presence, Error> {
1907+ if !presence.user_ids().iter().any(|id| id == user_id) {
1908+ return Ok(Presence::Offline);
1909+ }
1910+
1911+ user::presence(user_id, conn).await
1912+}
1913+
1914+pub async fn presence_changed(
1915+ presence: &network::Presence,
1916+ user_id: &str,
1917+ conn: &Connection,
1918+) -> Result<Vec<Broadcast>, Error> {
1919+ let presence = effective_presence(presence, user_id, conn).await?;
1920+
1921+ Ok(vec![Broadcast {
1922+ event: Event::PresenceChanged {
1923+ user_id: user_id.to_string(),
1924+ presence,
1925+ },
1926+ user_ids: related_user_ids(user_id, conn).await?,
1637 }])1927 }])
1638 }1928 }
1639 1929
@@ -1690,6 +1980,51 @@ async fn voice_leave(
1690 }1980 }
1691 }1981 }
1692 1982
1983+async fn voice_unmuted(
1984+ voice: &Voice,
1985+ user_id: &str,
1986+ conn: &Connection,
1987+) -> Result<Vec<Broadcast>, Error> {
1988+ let Some(community_id) = voice.set_muted(user_id, false) else {
1989+ return Ok(Vec::new());
1990+ };
1991+ let mut user_ids = vec![user_id.to_string()];
1992+ if !user::is_ghost(user_id, conn).await? {
1993+ user_ids.extend(
1994+ user_community::members(&community_id, conn)
1995+ .await?
1996+ .into_iter()
1997+ .map(|member| member.user.id),
1998+ );
1999+ }
2000+
2001+ Ok(vec![Broadcast {
2002+ event: Event::VoiceMuted {
2003+ user_id: user_id.to_string(),
2004+ muted: false,
2005+ },
2006+ user_ids,
2007+ }])
2008+}
2009+
2010+async fn voice_silenced(
2011+ voice: &Voice,
2012+ community_id: &str,
2013+ conn: &Connection,
2014+) -> Result<Vec<Broadcast>, Error> {
2015+ let mut broadcasts = Vec::new();
2016+ for user_id in voice.room_users(community_id) {
2017+ if permission::is_builder(user::read(&user_id, conn).await?.role) {
2018+ continue;
2019+ }
2020+ if let Some(left) = voice.leave_room(community_id, &user_id) {
2021+ broadcasts.extend(voice_left(left, conn).await?);
2022+ }
2023+ }
2024+
2025+ Ok(broadcasts)
2026+}
2027+
1693 async fn voice_closed(2028 async fn voice_closed(
1694 voice: &Voice,2029 voice: &Voice,
1695 community_id: &str,2030 community_id: &str,
@@ -1703,15 +2038,45 @@ async fn voice_closed(
1703 Ok(broadcasts)2038 Ok(broadcasts)
1704 }2039 }
1705 2040
2041+fn call_log_of(end: CallEnd) -> Option<CallLog> {
2042+ match end {
2043+ CallEnd::Answered { seconds } => Some(CallLog::Ended { seconds }),
2044+ CallEnd::Unanswered => Some(CallLog::Missed),
2045+ CallEnd::Declined => None,
2046+ }
2047+}
2048+
2049+async fn call_ended(
2050+ community_id: &str,
2051+ user_id: &str,
2052+ call: Option<CallEnd>,
2053+ members: &[Member],
2054+ conn: &Connection,
2055+) -> Result<Vec<Broadcast>, Error> {
2056+ let direct = match call {
2057+ Some(_) => community::is_direct(community_id, conn).await?,
2058+ None => false,
2059+ };
2060+ let Some(call) = call.filter(|_| direct).and_then(call_log_of) else {
2061+ return Ok(Vec::new());
2062+ };
2063+ let created = message::create_call_log(community_id, user_id, call, conn).await?;
2064+
2065+ Ok(broadcast(Event::MessageCreated(created), members))
2066+}
2067+
1706 async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Error> {2068 async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
1707 let Some(seconds) = left.ghost_seconds else {2069 let Some(seconds) = left.ghost_seconds else {
1708 let members = user_community::members(&left.community_id, conn).await?;2070 let members = user_community::members(&left.community_id, conn).await?;
2071+ let mut broadcasts =
2072+ call_ended(&left.community_id, &left.user_id, left.call, &members, conn).await?;
1709 let event = Event::VoiceLeft {2073 let event = Event::VoiceLeft {
1710 community_id: left.community_id,2074 community_id: left.community_id,
1711 user_id: left.user_id,2075 user_id: left.user_id,
1712 };2076 };
2077+ broadcasts.extend(broadcast(event, &members));
1713 2078
1714- return Ok(broadcast(event, &members));2079+ return Ok(broadcasts);
1715 };2080 };
1716 let community = community::label(&left.community_id, conn).await?;2081 let community = community::label(&left.community_id, conn).await?;
1717 admin_log::record(2082 admin_log::record(
@@ -1788,6 +2153,16 @@ pub fn ensure(allowed: bool) -> Result<(), Error> {
1788 Ok(())2153 Ok(())
1789 }2154 }
1790 2155
2156+fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Vec<Broadcast> {
2157+ let mut broadcasts = broadcast(event, members);
2158+ for broadcast in &mut broadcasts {
2159+ if !broadcast.user_ids.iter().any(|id| id == user_id) {
2160+ broadcast.user_ids.push(user_id.to_string());
2161+ }
2162+ }
2163+ broadcasts
2164+}
2165+
1791 fn broadcast(event: Event, members: &[Member]) -> Vec<Broadcast> {2166 fn broadcast(event: Event, members: &[Member]) -> Vec<Broadcast> {
1792 vec![Broadcast {2167 vec![Broadcast {
1793 event,2168 event,
@@ -1825,6 +2200,7 @@ mod tests {
1825 &Services::default(),2200 &Services::default(),
1826 None,2201 None,
1827 &test::directory(),2202 &test::directory(),
2203+ &test::directory(),
1828 )2204 )
1829 .await;2205 .await;
1830 2206
@@ -1848,6 +2224,7 @@ mod tests {
1848 &services,2224 &services,
1849 None,2225 None,
1850 &test::directory(),2226 &test::directory(),
2227+ &test::directory(),
1851 )2228 )
1852 .await2229 .await
1853 else {2230 else {
@@ -1863,6 +2240,7 @@ mod tests {
1863 &services,2240 &services,
1864 None,2241 None,
1865 &test::directory(),2242 &test::directory(),
2243+ &test::directory(),
1866 )2244 )
1867 .await;2245 .await;
1868 handle(2246 handle(
@@ -1874,6 +2252,7 @@ mod tests {
1874 &services,2252 &services,
1875 None,2253 None,
1876 &test::directory(),2254 &test::directory(),
2255+ &test::directory(),
1877 )2256 )
1878 .await;2257 .await;
1879 }2258 }
@@ -1893,6 +2272,7 @@ mod tests {
1893 &services,2272 &services,
1894 None,2273 None,
1895 &test::directory(),2274 &test::directory(),
2275+ &test::directory(),
1896 )2276 )
1897 .await2277 .await
1898 else {2278 else {
@@ -1910,6 +2290,7 @@ mod tests {
1910 &services,2290 &services,
1911 None,2291 None,
1912 &test::directory(),2292 &test::directory(),
2293+ &test::directory(),
1913 )2294 )
1914 .await;2295 .await;
1915 2296
@@ -1931,6 +2312,7 @@ mod tests {
1931 &services,2312 &services,
1932 None,2313 None,
1933 &test::directory(),2314 &test::directory(),
2315+ &test::directory(),
1934 )2316 )
1935 .await2317 .await
1936 else {2318 else {
@@ -1945,6 +2327,7 @@ mod tests {
1945 &services,2327 &services,
1946 None,2328 None,
1947 &test::directory(),2329 &test::directory(),
2330+ &test::directory(),
1948 )2331 )
1949 .await2332 .await
1950 else {2333 else {
@@ -1959,6 +2342,7 @@ mod tests {
1959 &services,2342 &services,
1960 None,2343 None,
1961 &test::directory(),2344 &test::directory(),
2345+ &test::directory(),
1962 )2346 )
1963 .await;2347 .await;
1964 handle(2348 handle(
@@ -1970,6 +2354,7 @@ mod tests {
1970 &services,2354 &services,
1971 None,2355 None,
1972 &test::directory(),2356 &test::directory(),
2357+ &test::directory(),
1973 )2358 )
1974 .await;2359 .await;
1975 2360
@@ -1980,6 +2365,7 @@ mod tests {
1980 &services,2365 &services,
1981 None,2366 None,
1982 &test::directory(),2367 &test::directory(),
2368+ &test::directory(),
1983 )2369 )
1984 .await2370 .await
1985 else {2371 else {
@@ -1992,6 +2378,7 @@ mod tests {
1992 &services,2378 &services,
1993 None,2379 None,
1994 &test::directory(),2380 &test::directory(),
2381+ &test::directory(),
1995 )2382 )
1996 .await2383 .await
1997 else {2384 else {
@@ -2017,6 +2404,7 @@ mod tests {
2017 &services,2404 &services,
2018 None,2405 None,
2019 &test::directory(),2406 &test::directory(),
2407+ &test::directory(),
2020 )2408 )
2021 .await2409 .await
2022 else {2410 else {
@@ -2032,6 +2420,7 @@ mod tests {
2032 &services,2420 &services,
2033 None,2421 None,
2034 &test::directory(),2422 &test::directory(),
2423+ &test::directory(),
2035 )2424 )
2036 .await2425 .await
2037 else {2426 else {
@@ -2054,6 +2443,7 @@ mod tests {
2054 &services,2443 &services,
2055 None,2444 None,
2056 &test::directory(),2445 &test::directory(),
2446+ &test::directory(),
2057 )2447 )
2058 .await2448 .await
2059 else {2449 else {
@@ -2071,6 +2461,7 @@ mod tests {
2071 &services,2461 &services,
2072 None,2462 None,
2073 &test::directory(),2463 &test::directory(),
2464+ &test::directory(),
2074 )2465 )
2075 .await;2466 .await;
2076 2467
@@ -2083,6 +2474,7 @@ mod tests {
2083 &services,2474 &services,
2084 None,2475 None,
2085 &test::directory(),2476 &test::directory(),
2477+ &test::directory(),
2086 )2478 )
2087 .await;2479 .await;
2088 2480
crates/server/src/stats.rsmodified+1 -5
@@ -52,11 +52,7 @@ pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, Error>
52 Ok(stats)52 Ok(stats)
53 }53 }
54 54
55-async fn count(55+async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result<u64, Error> {
56- conn: &Connection,
57- sql: &str,
58- params: impl turso::IntoParams,
59-) -> Result<u64, Error> {
60 let mut rows = conn.query(sql, params).await?;56 let mut rows = conn.query(sql, params).await?;
61 let row = rows57 let row = rows
62 .next()58 .next()
crates/server/src/user.rsmodified+61 -10
@@ -1,7 +1,7 @@
1 use common::{1 use common::{
2 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},2 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},
3 error::{Error as CommonError, InvalidInput},3 error::{Error as CommonError, InvalidInput},
4- model::{Account, Role, User},4+ model::{Account, Presence, Role, User},
5 time,5 time,
6 validate::{validate_avatar_size, validate_status, validate_username},6 validate::{validate_avatar_size, validate_status, validate_username},
7 };7 };
@@ -77,7 +77,10 @@ pub async fn any(conn: &Connection) -> Result<bool, Error> {
77 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {77 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {
78 let mut rows = conn78 let mut rows = conn
79 .query(79 .query(
80- &format!("SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE", user_columns("user")),80+ &format!(
81+ "SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE",
82+ user_columns("user")
83+ ),
81 (username,),84 (username,),
82 )85 )
83 .await?;86 .await?;
@@ -91,7 +94,10 @@ pub async fn credentials(
91 ) -> Result<Option<(User, String)>, Error> {94 ) -> Result<Option<(User, String)>, Error> {
92 let mut rows = conn95 let mut rows = conn
93 .query(96 .query(
94- &format!("SELECT {}, password_hash FROM user WHERE username = ?1", user_columns("user")),97+ &format!(
98+ "SELECT {}, password_hash FROM user WHERE username = ?1",
99+ user_columns("user")
100+ ),
95 (username,),101 (username,),
96 )102 )
97 .await?;103 .await?;
@@ -114,7 +120,10 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<
114 120
115 let mut rows = conn121 let mut rows = conn
116 .query(122 .query(
117- &format!("UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")),123+ &format!(
124+ "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}",
125+ user_columns("user")
126+ ),
118 (user_id, username),127 (user_id, username),
119 )128 )
120 .await?;129 .await?;
@@ -128,7 +137,10 @@ pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Re
128 137
129 let mut rows = conn138 let mut rows = conn
130 .query(139 .query(
131- &format!("UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")),140+ &format!(
141+ "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}",
142+ user_columns("user")
143+ ),
132 (user_id, status),144 (user_id, status),
133 )145 )
134 .await?;146 .await?;
@@ -186,7 +198,10 @@ async fn set_avatar_id(
186 ) -> Result<User, Error> {198 ) -> Result<User, Error> {
187 let mut rows = conn199 let mut rows = conn
188 .query(200 .query(
189- &format!("UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")),201+ &format!(
202+ "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}",
203+ user_columns("user")
204+ ),
190 (user_id, avatar_id),205 (user_id, avatar_id),
191 )206 )
192 .await?;207 .await?;
@@ -210,7 +225,10 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error
210 pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<User, Error> {225 pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<User, Error> {
211 let mut rows = conn226 let mut rows = conn
212 .query(227 .query(
213- &format!("UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}", user_columns("user")),228+ &format!(
229+ "UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}",
230+ user_columns("user")
231+ ),
214 (username, role.as_str()),232 (username, role.as_str()),
215 )233 )
216 .await?;234 .await?;
@@ -222,7 +240,10 @@ pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<U
222 pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {240 pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {
223 let mut rows = conn241 let mut rows = conn
224 .query(242 .query(
225- &format!("UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")),243+ &format!(
244+ "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}",
245+ user_columns("user")
246+ ),
226 (user_id, role.as_str()),247 (user_id, role.as_str()),
227 )248 )
228 .await?;249 .await?;
@@ -332,9 +353,36 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> {
332 Ok(flag != 0)353 Ok(flag != 0)
333 }354 }
334 355
356+pub async fn presence(user_id: &str, conn: &Connection) -> Result<Presence, Error> {
357+ let mut rows = conn
358+ .query("SELECT presence FROM user WHERE id = ?1", (user_id,))
359+ .await?;
360+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
361+ let text: String = row.get(0)?;
362+
363+ Ok(Presence::parse(&text).ok_or(CommonError::Server)?)
364+}
365+
366+pub async fn update_presence(
367+ user_id: &str,
368+ presence: Presence,
369+ conn: &Connection,
370+) -> Result<(), Error> {
371+ conn.execute(
372+ "UPDATE user SET presence = ?2 WHERE id = ?1",
373+ (user_id, presence.as_str()),
374+ )
375+ .await?;
376+
377+ Ok(())
378+}
379+
335 pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> {380 pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> {
336 let mut rows = conn381 let mut rows = conn
337- .query("SELECT voice_muted FROM user WHERE id = ?1", (user_id,))382+ .query(
383+ "SELECT voice_muted AND role != ?2 FROM user WHERE id = ?1",
384+ (user_id, Role::Builder.as_str()),
385+ )
338 .await?;386 .await?;
339 let row = rows.next().await?.ok_or(CommonError::NotFound)?;387 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
340 let muted: i64 = row.get(0)?;388 let muted: i64 = row.get(0)?;
@@ -384,7 +432,10 @@ pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> {
384 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {432 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
385 let mut rows = conn433 let mut rows = conn
386 .query(434 .query(
387- &format!("DELETE FROM user WHERE id = ?1 RETURNING {}", user_columns("user")),435+ &format!(
436+ "DELETE FROM user WHERE id = ?1 RETURNING {}",
437+ user_columns("user")
438+ ),
388 (user_id,),439 (user_id,),
389 )440 )
390 .await?;441 .await?;
crates/server/src/user_community.rsmodified+58 -2
@@ -1,10 +1,10 @@
1 use common::{1 use common::{
2 error::Error as CommonError,2 error::Error as CommonError,
3- model::{Ban, Member, Rank},3+ model::{Ban, Member, Rank, Unread},
4 };4 };
5 use turso::{Connection, Row};5 use turso::{Connection, Row};
6 6
7-use crate::{error::Error, user};7+use crate::{community, error::Error, user};
8 8
9 fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> {9 fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> {
10 let text: String = row.get(index)?;10 let text: String = row.get(index)?;
@@ -71,6 +71,49 @@ pub async fn set_rank(
71 Ok(())71 Ok(())
72 }72 }
73 73
74+pub async fn mark_read(
75+ user_id: &str,
76+ community_id: &str,
77+ message_id: &str,
78+ conn: &Connection,
79+) -> Result<(), Error> {
80+ conn.execute(
81+ "UPDATE user_community SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)",
82+ (user_id, community_id, message_id),
83+ )
84+ .await?;
85+
86+ Ok(())
87+}
88+
89+pub async fn unreads(
90+ user_id: &str,
91+ username: &str,
92+ conn: &Connection,
93+) -> Result<Vec<Unread>, Error> {
94+ let mention = format!("@{}", username.to_lowercase());
95+ let mut rows = conn
96+ .query(
97+ "SELECT uc.community_id, (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read)), (SELECT COUNT(*) FROM message m WHERE m.community_id = uc.community_id AND m.user_id != ?1 AND (uc.last_read IS NULL OR m.id > uc.last_read) AND instr(lower(m.body), ?2) > 0), uc.last_read FROM user_community uc WHERE uc.user_id = ?1",
98+ (user_id, mention.as_str()),
99+ )
100+ .await?;
101+
102+ let mut unreads = Vec::new();
103+ while let Some(row) = rows.next().await? {
104+ let messages: i64 = row.get(1)?;
105+ let mentions: i64 = row.get(2)?;
106+ unreads.push(Unread {
107+ community_id: row.get(0)?,
108+ messages: messages as u32,
109+ mentions: mentions as u32,
110+ last_read: row.get::<Option<String>>(3)?,
111+ });
112+ }
113+
114+ Ok(unreads)
115+}
116+
74 pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, Error> {117 pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, Error> {
75 let mut rows = conn118 let mut rows = conn
76 .query(119 .query(
@@ -90,6 +133,19 @@ pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member
90 Ok(members)133 Ok(members)
91 }134 }
92 135
136+pub async fn owned_groups(user_id: &str, conn: &Connection) -> Result<usize, Error> {
137+ let mut rows = conn
138+ .query(
139+ "SELECT COUNT(*) FROM user_community JOIN community ON community.id = user_community.community_id WHERE user_community.user_id = ?1 AND user_community.rank = ?2 AND community.kind = ?3",
140+ (user_id, Rank::Owner.as_str(), community::Kind::Group.as_str()),
141+ )
142+ .await?;
143+ let row = rows.next().await?.ok_or(CommonError::Server)?;
144+ let count: i64 = row.get(0)?;
145+
146+ Ok(count as usize)
147+}
148+
93 pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {149 pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
94 let mut rows = conn150 let mut rows = conn
95 .query(151 .query(
crates/server/src/voice.rsmodified+162 -37
@@ -5,7 +5,10 @@ use std::{
5 };5 };
6 6
7 use bytes::Bytes;7 use bytes::Bytes;
8-use common::voice::{SEQUENCE_LENGTH, encode_relay};8+use common::{
9+ time,
10+ voice::{SEQUENCE_LENGTH, encode_relay},
11+};
9 use quinn::Connection;12 use quinn::Connection;
10 13
11 struct Participant {14 struct Participant {
@@ -16,13 +19,72 @@ struct Participant {
16 joined_at: Instant,19 joined_at: Instant,
17 }20 }
18 21
22+pub enum CallEnd {
23+ Answered { seconds: u64 },
24+ Unanswered,
25+ Declined,
26+}
27+
28+pub struct GhostChange {
29+ pub community_id: String,
30+ pub ghost_seconds: Option<u64>,
31+ pub call: Option<CallEnd>,
32+}
33+
19 pub struct Left {34 pub struct Left {
20 pub community_id: String,35 pub community_id: String,
21 pub user_id: String,36 pub user_id: String,
22 pub ghost_seconds: Option<u64>,37 pub ghost_seconds: Option<u64>,
38+ pub call: Option<CallEnd>,
39+}
40+
41+struct Room {
42+ participants: Vec<Participant>,
43+ started_ms: u64,
44+ answered: bool,
45+ declined: bool,
46+}
47+
48+impl Room {
49+ fn new() -> Self {
50+ Self {
51+ participants: Vec::new(),
52+ started_ms: time::now_ms(),
53+ answered: false,
54+ declined: false,
55+ }
56+ }
57+
58+ fn occupied(&self) -> bool {
59+ self.participants
60+ .iter()
61+ .any(|participant| !participant.ghost)
62+ }
63+
64+ fn admit(&mut self) {
65+ if self.occupied() {
66+ self.answered = true;
67+ } else {
68+ self.started_ms = time::now_ms();
69+ self.answered = false;
70+ self.declined = false;
71+ }
72+ }
73+
74+ fn end(&self) -> CallEnd {
75+ if self.answered {
76+ CallEnd::Answered {
77+ seconds: time::now_ms().saturating_sub(self.started_ms) / 1000,
78+ }
79+ } else if self.declined {
80+ CallEnd::Declined
81+ } else {
82+ CallEnd::Unanswered
83+ }
84+ }
23 }85 }
24 86
25-type Rooms = HashMap<String, Vec<Participant>>;87+type Rooms = HashMap<String, Room>;
26 88
27 #[derive(Clone, Default)]89 #[derive(Clone, Default)]
28 pub struct Voice(Arc<Mutex<Rooms>>);90 pub struct Voice(Arc<Mutex<Rooms>>);
@@ -38,24 +100,34 @@ impl Voice {
38 ) -> Option<Left> {100 ) -> Option<Left> {
39 let mut rooms = self.0.lock().unwrap();101 let mut rooms = self.0.lock().unwrap();
40 let previous = leave_locked(&mut rooms, user_id);102 let previous = leave_locked(&mut rooms, user_id);
41- rooms103+ let room = rooms
42 .entry(community_id.to_string())104 .entry(community_id.to_string())
43- .or_default()105+ .or_insert_with(Room::new);
44- .push(Participant {106+ if !ghost {
45- user_id: user_id.to_string(),107+ room.admit();
46- connection,108+ }
47- muted,109+ room.participants.push(Participant {
48- ghost,110+ user_id: user_id.to_string(),
49- joined_at: Instant::now(),111+ connection,
50- });112+ muted,
113+ ghost,
114+ joined_at: Instant::now(),
115+ });
51 116
52 previous117 previous
53 }118 }
54 119
120+ pub fn decline(&self, community_id: &str) {
121+ if let Some(room) = self.0.lock().unwrap().get_mut(community_id) {
122+ room.declined = true;
123+ }
124+ }
125+
55 pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> {126 pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> {
56 let mut rooms = self.0.lock().unwrap();127 let mut rooms = self.0.lock().unwrap();
57 for (community_id, room) in rooms.iter_mut() {128 for (community_id, room) in rooms.iter_mut() {
58 if let Some(participant) = room129 if let Some(participant) = room
130+ .participants
59 .iter_mut()131 .iter_mut()
60 .find(|participant| participant.user_id == user_id)132 .find(|participant| participant.user_id == user_id)
61 {133 {
@@ -68,29 +140,67 @@ impl Voice {
68 None140 None
69 }141 }
70 142
71- pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<(String, Option<u64>)> {143+ pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<GhostChange> {
72 let mut rooms = self.0.lock().unwrap();144 let mut rooms = self.0.lock().unwrap();
73 for (community_id, room) in rooms.iter_mut() {145 for (community_id, room) in rooms.iter_mut() {
74- if let Some(participant) = room146+ let Some(index) = room
75- .iter_mut()147+ .participants
76- .find(|participant| participant.user_id == user_id)148+ .iter()
77- {149+ .position(|participant| participant.user_id == user_id)
78- if participant.ghost == ghost {150+ else {
79- return None;151+ continue;
80- }152+ };
81- let seconds = participant153+ if room.participants[index].ghost == ghost {
82- .ghost154+ return None;
83- .then(|| participant.joined_at.elapsed().as_secs());
84- participant.ghost = ghost;
85- participant.joined_at = Instant::now();
86-
87- return Some((community_id.clone(), seconds));
88 }155 }
156+ if !ghost {
157+ room.admit();
158+ }
159+ let participant = &mut room.participants[index];
160+ let seconds = participant
161+ .ghost
162+ .then(|| participant.joined_at.elapsed().as_secs());
163+ participant.ghost = ghost;
164+ participant.joined_at = Instant::now();
165+ let call = (ghost && !room.occupied()).then(|| room.end());
166+
167+ return Some(GhostChange {
168+ community_id: community_id.clone(),
169+ ghost_seconds: seconds,
170+ call,
171+ });
89 }172 }
90 173
91 None174 None
92 }175 }
93 176
177+ pub fn room_users(&self, community_id: &str) -> Vec<String> {
178+ self.0
179+ .lock()
180+ .unwrap()
181+ .get(community_id)
182+ .map(|room| {
183+ room.participants
184+ .iter()
185+ .map(|participant| participant.user_id.clone())
186+ .collect()
187+ })
188+ .unwrap_or_default()
189+ }
190+
191+ pub fn room_of(&self, user_id: &str) -> Option<String> {
192+ self.0
193+ .lock()
194+ .unwrap()
195+ .iter()
196+ .find(|(_, room)| {
197+ room.participants
198+ .iter()
199+ .any(|participant| participant.user_id == user_id)
200+ })
201+ .map(|(community_id, _)| community_id.clone())
202+ }
203+
94 pub fn leave(&self, user_id: &str) -> Option<Left> {204 pub fn leave(&self, user_id: &str) -> Option<Left> {
95 leave_locked(&mut self.0.lock().unwrap(), user_id)205 leave_locked(&mut self.0.lock().unwrap(), user_id)
96 }206 }
@@ -107,7 +217,12 @@ impl Voice {
107 }217 }
108 218
109 pub fn count(&self) -> usize {219 pub fn count(&self) -> usize {
110- self.0.lock().unwrap().values().map(Vec::len).sum()220+ self.0
221+ .lock()
222+ .unwrap()
223+ .values()
224+ .map(|room| room.participants.len())
225+ .sum()
111 }226 }
112 227
113 pub fn participants(&self, community_id: &str) -> Vec<String> {228 pub fn participants(&self, community_id: &str) -> Vec<String> {
@@ -116,7 +231,8 @@ impl Voice {
116 .unwrap()231 .unwrap()
117 .get(community_id)232 .get(community_id)
118 .map(|room| {233 .map(|room| {
119- room.iter()234+ room.participants
235+ .iter()
120 .filter(|participant| !participant.ghost)236 .filter(|participant| !participant.ghost)
121 .map(|participant| participant.user_id.clone())237 .map(|participant| participant.user_id.clone())
122 .collect()238 .collect()
@@ -131,10 +247,12 @@ impl Voice {
131 .iter()247 .iter()
132 .map(|(community_id, room)| {248 .map(|(community_id, room)| {
133 let user_ids = room249 let user_ids = room
250+ .participants
134 .iter()251 .iter()
135 .map(|participant| participant.user_id.clone())252 .map(|participant| participant.user_id.clone())
136 .collect();253 .collect();
137 let ghost_ids = room254 let ghost_ids = room
255+ .participants
138 .iter()256 .iter()
139 .filter(|participant| participant.ghost)257 .filter(|participant| participant.ghost)
140 .map(|participant| participant.user_id.clone())258 .map(|participant| participant.user_id.clone())
@@ -150,16 +268,18 @@ impl Voice {
150 .lock()268 .lock()
151 .unwrap()269 .unwrap()
152 .remove(community_id)270 .remove(community_id)
271+ .map(|room| room.participants)
153 .unwrap_or_default()272 .unwrap_or_default()
154 .into_iter()273 .into_iter()
155- .map(|participant| left(community_id, participant))274+ .map(|participant| left(community_id, participant, None))
156 .collect()275 .collect()
157 }276 }
158 277
159 pub fn relay(&self, connection_id: usize, packet: &[u8]) {278 pub fn relay(&self, connection_id: usize, packet: &[u8]) {
160 let rooms = self.0.lock().unwrap();279 let rooms = self.0.lock().unwrap();
161 let Some(room) = rooms.values().find(|room| {280 let Some(room) = rooms.values().find(|room| {
162- room.iter()281+ room.participants
282+ .iter()
163 .any(|participant| participant.connection.stable_id() == connection_id)283 .any(|participant| participant.connection.stable_id() == connection_id)
164 }) else {284 }) else {
165 return;285 return;
@@ -167,7 +287,7 @@ impl Voice {
167 let Some(sender) = find(&rooms, connection_id) else {287 let Some(sender) = find(&rooms, connection_id) else {
168 return;288 return;
169 };289 };
170- if sender.muted || sender.ghost {290+ if sender.muted {
171 return;291 return;
172 }292 }
173 let (Some(relay), Some(echo)) = (293 let (Some(relay), Some(echo)) = (
@@ -180,6 +300,7 @@ impl Voice {
180 let bytes = Bytes::from(relay);300 let bytes = Bytes::from(relay);
181 301
182 for participant in room302 for participant in room
303+ .participants
183 .iter()304 .iter()
184 .filter(|participant| participant.user_id != sender.user_id)305 .filter(|participant| participant.user_id != sender.user_id)
185 {306 {
@@ -191,38 +312,42 @@ impl Voice {
191 fn find(rooms: &Rooms, connection_id: usize) -> Option<&Participant> {312 fn find(rooms: &Rooms, connection_id: usize) -> Option<&Participant> {
192 rooms313 rooms
193 .values()314 .values()
194- .flatten()315+ .flat_map(|room| &room.participants)
195 .find(|participant| participant.connection.stable_id() == connection_id)316 .find(|participant| participant.connection.stable_id() == connection_id)
196 }317 }
197 318
198-fn left(community_id: &str, participant: Participant) -> Left {319+fn left(community_id: &str, participant: Participant, call: Option<CallEnd>) -> Left {
199 Left {320 Left {
200 community_id: community_id.to_string(),321 community_id: community_id.to_string(),
201 user_id: participant.user_id,322 user_id: participant.user_id,
202 ghost_seconds: participant323 ghost_seconds: participant
203 .ghost324 .ghost
204 .then(|| participant.joined_at.elapsed().as_secs()),325 .then(|| participant.joined_at.elapsed().as_secs()),
326+ call,
205 }327 }
206 }328 }
207 329
208 fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option<Left> {330 fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option<Left> {
209 let room = rooms.get_mut(community_id)?;331 let room = rooms.get_mut(community_id)?;
210 let index = room332 let index = room
333+ .participants
211 .iter()334 .iter()
212 .position(|participant| participant.user_id == user_id)?;335 .position(|participant| participant.user_id == user_id)?;
213- let participant = room.remove(index);336+ let participant = room.participants.remove(index);
214- if room.is_empty() {337+ let call = (!participant.ghost && !room.occupied()).then(|| room.end());
338+ if room.participants.is_empty() {
215 rooms.remove(community_id);339 rooms.remove(community_id);
216 }340 }
217 341
218- Some(left(community_id, participant))342+ Some(left(community_id, participant, call))
219 }343 }
220 344
221 fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option<Left> {345 fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option<Left> {
222 let community_id = rooms346 let community_id = rooms
223 .iter()347 .iter()
224 .find(|(_, room)| {348 .find(|(_, room)| {
225- room.iter()349+ room.participants
350+ .iter()
226 .any(|participant| participant.user_id == user_id)351 .any(|participant| participant.user_id == user_id)
227 })352 })
228 .map(|(community_id, _)| community_id.clone())?;353 .map(|(community_id, _)| community_id.clone())?;