diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 8984a5c..36e0773 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -9,18 +9,18 @@ tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } gpui-kit = "0.11.0" -ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } -ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e7e5914914a6a7d37093879f4b4e76b56542ad76" } +ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } +ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } ureq = "3.5.2" bytes = "1.12.2" tracing = "0.1.44" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 0defcf9..1e98497 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -34,8 +34,8 @@ use crate::{ settings::{Look, Scale, Settings, ThemeChoice}, }; -mod admin; mod auth; +mod builder; mod chat; mod community_settings; mod composer; @@ -275,6 +275,28 @@ pub fn community_icon( } } +pub const KB: f64 = 1024.0; +pub const MB: f64 = KB * 1024.0; +const GB: f64 = MB * 1024.0; + +pub const STAMP: &str = "%b %-d, %H:%M"; +pub const YEAR_STAMP: &str = "%b %-d %Y, %H:%M"; +pub const CLOCK: &str = "%H:%M"; +pub const DAY: &str = "%b %-d"; +pub const DAY_YEAR: &str = "%b %-d, %Y"; +pub const DATE: &str = "%b %-d %Y"; + +pub fn storage(bytes: u64) -> String { + let bytes = bytes as f64; + if bytes >= GB { + format!("{:.1} GB", bytes / GB) + } else if bytes >= MB { + format!("{:.1} MB", bytes / MB) + } else { + format!("{:.1} KB", bytes / KB) + } +} + pub fn id_time(id: &str, format: &str) -> String { created_at_ms(id) .map(|millis| millis_time(millis, format)) @@ -388,12 +410,11 @@ impl RenderOnce for Trigger { } pub fn rank_tag(rank: Option, palette: Palette) -> Option
{ - let (label, color) = match rank? { - Rank::Owner => ("Owner", palette.muted), - Rank::Admin => ("Admin", palette.muted), - Rank::Moderator => ("Mod", palette.muted), + let rank = rank?; + let color = match rank { Rank::Member => return None, - Rank::Builder => ("Builder", palette.text), + Rank::Builder => palette.text, + _ => palette.muted, }; Some( @@ -404,7 +425,7 @@ pub fn rank_tag(rank: Option, palette: Palette) -> Option
{ .bg(palette.hover) .text_size(text(11.)) .text_color(color) - .child(label), + .child(rank.label()), ) } @@ -611,8 +632,8 @@ impl Yumush { .status_input .update(cx, |input, cx| input.set_value(status, window, cx)); } - if view == View::Admin { - self.load_admin(window, cx); + if view == View::Builder { + self.load_builder(window, cx); } if view == View::CommunitySettings { let name = self @@ -636,7 +657,7 @@ impl Yumush { pub fn themed(&self, cx: &App) -> Palette { let community = match self.chat.view { - View::Settings | View::Admin => None, + View::Settings | View::Builder => None, _ => self.chat.selected_community(), }; palette(cx).for_community(community, &self.chat.hues) @@ -689,7 +710,7 @@ impl Yumush { if self.is_me(&user.id) { self.user = Some(user.clone()); self.accounts.rename(user); - if !self.is_builder() && self.chat.view == View::Admin { + if !self.is_builder() && self.chat.view == View::Builder { self.chat.view = View::Chat; } } @@ -746,7 +767,10 @@ impl Yumush { } pub(super) fn dismiss_announcement(&mut self, cx: &mut Context) { - self.dismissed_announcement = self.server.as_ref().map(|settings| settings.announcement.clone()); + self.dismissed_announcement = self + .server + .as_ref() + .map(|settings| settings.announcement.clone()); cx.notify(); } diff --git a/crates/client/src/gui/admin.rs b/crates/client/src/gui/admin.rs deleted file mode 100644 index 42efecd..0000000 --- a/crates/client/src/gui/admin.rs +++ /dev/null @@ -1,3224 +0,0 @@ -use std::future::Future; - -use super::text; -use crate::network::NetworkHandle; -use common::{ - error::Error, - model::{ - Account, AdminAction, AdminLogEntry, AttachmentInfo, Community, CommunityKind, - CommunitySummary, - DayStat, InviteCode, Member, MessageHit, Rank, Report, ReportStatus, Role, ServerBan, - ServerSettings, SessionInfo, User, action_detail, action_name, - }, - permission, - time::{DAY_MILLIS, created_at_ms, now_ms}, -}; -use gpui_kit::{ - AnyElement, App, ClipboardItem, Context, Div, Entity, FontWeight, InteractiveElement, - IntoElement, ParentElement, StatefulInteractiveElement, Styled, Window, - component::{ - WindowExt, - input::{Input, InputState}, - notification::Notification, - select::Select, - }, - div, - prelude::FluentBuilder as _, - px, -}; -use jiff::{Timestamp, civil::Date, tz::TimeZone}; - -use super::{ - Palette, Yumush, - auth::field, - avatar, - chat::View, - clickable, community_icon, - community_settings::{search_text, user_name}, - entity_action, id_time, millis_time, notify_error, primary_button, - settings_page::{page, row, section, segment, segment_track, segmented}, -}; - -const ADMIN_TABS: [(AdminTab, &str); 10] = [ - (AdminTab::Overview, "Overview"), - (AdminTab::Users, "Users"), - (AdminTab::Communities, "Communities"), - (AdminTab::Messages, "Messages"), - (AdminTab::Voice, "Voice"), - (AdminTab::Storage, "Storage"), - (AdminTab::Access, "Access"), - (AdminTab::Reports, "Reports"), - (AdminTab::Server, "Server"), - (AdminTab::Log, "Log"), -]; - -const REPORT_FILTERS: [(Option, &str); 4] = [ - (Some(ReportStatus::Open), "Open"), - (Some(ReportStatus::Resolved), "Resolved"), - (Some(ReportStatus::Dismissed), "Dismissed"), - (None, "All"), -]; - -const KB: f64 = 1024.0; -const MB: f64 = KB * 1024.0; -const GB: f64 = MB * 1024.0; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum AdminTab { - Overview, - Users, - Communities, - Messages, - Voice, - Storage, - Access, - Reports, - Server, - Log, -} - -pub(super) struct Transfer { - pub(super) community_id: String, - pub(super) members: Vec, - pub(super) pending: Option, -} - -fn storage(bytes: u64) -> String { - let bytes = bytes as f64; - if bytes >= GB { - format!("{:.1} GB", bytes / GB) - } else if bytes >= MB { - format!("{:.1} MB", bytes / MB) - } else { - format!("{:.1} KB", bytes / KB) - } -} - -fn megabytes_bytes(text: &str) -> u64 { - text.trim() - .parse::() - .ok() - .and_then(|megabytes| megabytes.checked_mul(MB as u64)) - .unwrap_or(0) -} - -fn kilobytes_bytes(text: &str) -> u64 { - text.trim() - .parse::() - .ok() - .and_then(|kilobytes| kilobytes.checked_mul(KB as u64)) - .unwrap_or(0) -} - -fn number(text: &str) -> u32 { - text.trim().parse().unwrap_or(0) -} - -fn admin_log_text(entry: &AdminLogEntry) -> String { - let actor = user_name(&entry.actor); - let target = user_name(&entry.target); - let community = entry.community.as_deref().unwrap_or_default(); - - match &entry.action { - AdminAction::RoleChanged { role } => format!("{actor} set {target} to {}", role.as_str()), - AdminAction::UserDeleted => format!("{actor} deleted {target}"), - AdminAction::UserSuspended => format!("{actor} suspended {target}"), - AdminAction::UserUnsuspended => format!("{actor} unsuspended {target}"), - AdminAction::SessionsRevoked => format!("{actor} revoked sessions of {target}"), - AdminAction::PasswordReset => format!("{actor} reset password of {target}"), - AdminAction::ProfileCleared => format!("{actor} cleared profile of {target}"), - AdminAction::UserCreated => format!("{actor} created {target}"), - AdminAction::CommunityDeleted => format!("{actor} deleted {community}"), - AdminAction::OwnershipTransferred => { - format!("{actor} transferred {community} to {target}") - } - AdminAction::SettingsChanged => format!("{actor} changed settings"), - AdminAction::UserRenamed { from } => format!("{actor} renamed {from} to {target}"), - AdminAction::UserTimedOut { minutes: 0 } => format!("{actor} cleared timeout of {target}"), - AdminAction::UserTimedOut { minutes } => { - format!("{actor} timed out {target} for {minutes} min") - } - AdminAction::UserBanned { .. } => format!("{actor} banned {target}"), - AdminAction::BanRemoved => format!("{actor} removed a ban"), - AdminAction::InviteCreated => format!("{actor} created an invite code"), - AdminAction::InviteDeleted => format!("{actor} deleted an invite code"), - AdminAction::ReportHandled { status } => { - format!("{actor} marked a report of {target} as {}", status.as_str()) - } - AdminAction::MessageDeleted => { - format!("{actor} deleted a message of {target} in {community}") - } - AdminAction::UserPurged { messages } => { - format!("{actor} purged {target}, {messages} messages") - } - AdminAction::VoiceKicked => format!("{actor} kicked {target} from voice"), - AdminAction::VoiceMuted { muted: true } => format!("{actor} muted {target} in voice"), - AdminAction::VoiceMuted { muted: false } => format!("{actor} unmuted {target} in voice"), - AdminAction::CommunityVoiceSet { enabled: true } => { - format!("{actor} enabled voice in {community}") - } - AdminAction::CommunityVoiceSet { enabled: false } => { - format!("{actor} disabled voice in {community}") - } - AdminAction::AttachmentDeleted => { - format!("{actor} deleted an attachment of {target} in {community}") - } - AdminAction::GhostEnabled => format!("{actor} enabled ghost mode"), - AdminAction::GhostDisabled => format!("{actor} disabled ghost mode"), - AdminAction::GhostVisit => format!("{actor} visited {community} as ghost"), - AdminAction::GhostVoice { seconds } => { - format!("{actor} listened in {community} as ghost for {seconds}s") - } - } -} - -fn seen_text(last_seen: Option) -> String { - let Some(last_seen) = last_seen else { - return "never".to_string(); - }; - let minutes = now_ms().saturating_sub(last_seen) / 60_000; - - match minutes { - 0 => "now".to_string(), - 1..60 => format!("{minutes}m ago"), - 60..1440 => format!("{}h ago", minutes / 60), - _ => millis_time(last_seen, "%b %-d"), - } -} - -fn csv_field(text: &str) -> String { - format!("\"{}\"", text.replace('"', "\"\"")) -} - -fn admin_log_csv(entries: &[AdminLogEntry]) -> String { - let mut lines = vec!["time,actor,action,target,community,detail".to_string()]; - for entry in entries { - let time = created_at_ms(&entry.id) - .and_then(|millis| Timestamp::from_millisecond(millis as i64).ok()) - .map(|timestamp| timestamp.to_string()) - .unwrap_or_default(); - let actor = entry - .actor - .as_ref() - .map_or_else(String::new, |user| user.username.clone()); - let target = entry - .target - .as_ref() - .map_or_else(String::new, |user| user.username.clone()); - let fields = [ - time, - actor, - action_name(&entry.action).to_string(), - target, - entry.community.clone().unwrap_or_default(), - action_detail(&entry.action).unwrap_or_default(), - ]; - lines.push( - fields - .iter() - .map(|field| csv_field(field)) - .collect::>() - .join(","), - ); - } - - lines.join("\n") -} - -fn day_label(day: u64) -> String { - Timestamp::from_millisecond((day * DAY_MILLIS) as i64) - .map(|timestamp| timestamp.strftime("%b %-d").to_string()) - .unwrap_or_default() -} - -fn bar_chart( - title: &'static str, - stats: &[DayStat], - value: fn(&DayStat) -> u64, - palette: Palette, -) -> Div { - let values: Vec = stats.iter().map(value).collect(); - let maximum = values.iter().copied().max().unwrap_or_default(); - let first = stats.first().map(|stat| day_label(stat.day)).unwrap_or_default(); - let last = stats.last().map(|stat| day_label(stat.day)).unwrap_or_default(); - - div() - .flex() - .flex_col() - .gap(px(4.)) - .child( - div() - .flex() - .justify_between() - .text_size(text(11.)) - .text_color(palette.muted) - .child(title) - .child(maximum.to_string()), - ) - .child( - div() - .h(px(48.)) - .flex() - .items_end() - .gap(px(2.)) - .children(values.iter().map(|&value| { - let height = if maximum == 0 { - 0. - } else { - 48. * value as f32 / maximum as f32 - }; - - div() - .flex_1() - .max_w(px(12.)) - .h(px(height)) - .rounded_t(px(2.)) - .bg(palette.accent) - })), - ) - .child( - div() - .flex() - .justify_between() - .text_size(text(10.)) - .text_color(palette.muted) - .child(first) - .child(last), - ) -} - -fn admin_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { - div() - .min_h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(admin_log_text(entry)), - ) - .child( - div() - .flex_shrink_0() - .text_size(text(11.)) - .text_color(palette.muted) - .child(id_time(&entry.id, "%b %-d, %H:%M")), - ) -} - -fn invite_row( - invite: &InviteCode, - pending: bool, - entity: &Entity, - palette: Palette, -) -> Div { - let copy_code = invite.code.clone(); - let delete_code = invite.code.clone(); - let expiry = invite.expires_at.map_or_else( - || "no expiry".to_string(), - |at| format!("until {}", millis_time(at, "%b %-d, %H:%M")), - ); - - div() - .min_h(px(44.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child( - div() - .font_weight(FontWeight::SEMIBOLD) - .child(invite.code.clone()), - ) - .child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(format!("{} left · {expiry}", invite.uses_left)), - ), - ) - .child(admin_button( - format!("copy_invite_{}", invite.code), - "Copy", - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.copy_invite(©_code, cx) - }), - )) - .child(danger_button( - format!("delete_invite_{}", invite.code), - "Delete", - pending, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_invite(&delete_code, window, cx) - }), - )) -} - -fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { - let remove_id = ban.id.clone(); - let detail = format!( - "{} · {}", - ban.kind.as_str(), - ban.reason.as_deref().unwrap_or_default() - ); - - div() - .min_h(px(44.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child(div().truncate().child(ban.value.clone())) - .child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(detail), - ), - ) - .child(admin_button( - format!("remove_ban_{}", ban.id), - "Remove", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.remove_ban(&remove_id, window, cx) - }), - )) -} - -fn danger_button( - id: String, - label: &'static str, - pending: bool, - palette: Palette, - action: impl Fn(&mut Window, &mut App) + 'static, -) -> impl IntoElement { - clickable(id, palette, action) - .h(px(28.)) - .px(px(8.)) - .flex() - .items_center() - .rounded(px(6.)) - .text_size(text(13.)) - .border_1() - .border_color(palette.danger.opacity(0.5)) - .text_color(palette.danger) - .when(pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) - }) - .child(if pending { "Confirm" } else { label }) -} - -fn day_millis(text: &str, end_of_day: bool) -> Option { - let date: Date = text.parse().ok()?; - let date = if end_of_day { - date.tomorrow().ok()? - } else { - date - }; - let millis = date - .to_zoned_datetime(TimeZone::system()) - .ok()? - .timestamp() - .as_millisecond(); - - u64::try_from(millis - i64::from(end_of_day)).ok() -} - -fn message_hit_row( - hit: &MessageHit, - pending: bool, - entity: &Entity, - palette: Palette, -) -> Div { - let message_id = hit.message.id.clone(); - - div() - .px(px(12.)) - .py(px(6.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(format!( - "{} · {} · {}", - id_time(&hit.message.id, "%b %-d %Y, %H:%M"), - hit.community, - user_name(&hit.author) - )), - ) - .child(div().truncate().child(hit.message.body.clone())), - ) - .child(danger_button( - format!("delete_message_{}", hit.message.id), - "Delete", - pending, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_admin_message(&message_id, window, cx) - }), - )) -} - -fn usage_row(name: &str, bytes: u64, count: u64, palette: Palette) -> Div { - div() - .px(px(12.)) - .py(px(6.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(name.to_string()), - ) - .child(div().text_size(text(13.)).child(storage(bytes))) - .child( - div() - .w(px(60.)) - .text_size(text(13.)) - .text_color(palette.muted) - .child(count.to_string()), - ) -} - -fn attachment_row( - info: &AttachmentInfo, - pending: bool, - entity: &Entity, - palette: Palette, -) -> Div { - let attachment_id = info.attachment.id.clone(); - - div() - .px(px(12.)) - .py(px(6.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child(div().truncate().child(info.attachment.name.clone())) - .child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(format!( - "{} · {} · {}", - storage(info.attachment.size), - user_name(&info.uploader), - info.community - )), - ), - ) - .child(danger_button( - format!("delete_attachment_{}", info.attachment.id), - "Delete", - pending, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_admin_attachment(&attachment_id, window, cx) - }), - )) -} - -fn accent_button( - id: &'static str, - label: &'static str, - palette: Palette, - action: impl Fn(&mut Window, &mut App) + 'static, -) -> impl IntoElement { - primary_button(id, palette, action) - .h(px(28.)) - .px(px(12.)) - .flex() - .items_center() - .rounded(px(6.)) - .text_size(text(13.)) - .child(label) -} - -fn admin_button( - id: String, - label: &'static str, - palette: Palette, - action: impl Fn(&mut Window, &mut App) + 'static, -) -> impl IntoElement { - clickable(id, palette, action) - .h(px(28.)) - .px(px(8.)) - .flex() - .items_center() - .rounded(px(6.)) - .text_size(text(13.)) - .text_color(palette.muted) - .child(label) -} - -impl Yumush { - pub(super) fn is_builder(&self) -> bool { - self.user - .as_ref() - .is_some_and(|me| me.role == Role::Builder) - } - - pub(super) fn load_admin(&self, window: &mut Window, cx: &mut Context) { - self.load_open_reports(window, cx); - match self.chat.admin_tab { - AdminTab::Overview => self.load_overview(window, cx), - AdminTab::Users => self.load_users(window, cx), - AdminTab::Communities => self.load_admin_communities(window, cx), - AdminTab::Messages => {} - AdminTab::Storage => { - self.load_users(window, cx); - self.load_admin_communities(window, cx); - self.load_storage(window, cx); - } - AdminTab::Voice => self.load_voice_rooms(window, cx), - AdminTab::Access => self.load_access(window, cx), - AdminTab::Reports => self.load_reports(window, cx), - AdminTab::Server => {} - AdminTab::Log => { - self.load_users(window, cx); - self.load_admin_logs(window, cx); - } - } - } - - pub(super) fn report_created(&self, window: &mut Window, cx: &mut Context) { - self.load_open_reports(window, cx); - if self.chat.view == View::Admin && self.chat.admin_tab == AdminTab::Reports { - self.load_reports(window, cx); - } - } - - fn load_open_reports(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let count = match network.reports(Some(ReportStatus::Open)).await { - Ok(reports) => reports.len(), - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.open_reports = count; - cx.notify(); - }); - }) - .detach(); - } - - fn load_reports(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let status = self.chat.report_filter; - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let reports = match network.reports(status).await { - Ok(reports) => reports, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_reports = reports; - cx.notify(); - }); - }) - .detach(); - } - - fn refresh_reports(&self, window: &mut Window, cx: &mut Context) { - self.load_reports(window, cx); - self.load_open_reports(window, cx); - } - - fn select_report_filter( - &mut self, - status: Option, - window: &mut Window, - cx: &mut Context, - ) { - self.chat.report_filter = status; - self.load_reports(window, cx); - cx.notify(); - } - - fn report_action( - &mut self, - window: &mut Window, - cx: &mut Context, - action: impl FnOnce(NetworkHandle) -> Fut + 'static, - ) where - Fut: Future> + 'static, - { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| match action(network).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| yumush.refresh_reports(window, cx)); - } - Err(error) => notify_error(&this, cx, error), - }) - .detach(); - } - - fn handle_report( - &mut self, - report_id: &str, - status: ReportStatus, - window: &mut Window, - cx: &mut Context, - ) { - let report_id = report_id.to_string(); - self.report_action(window, cx, move |network| async move { - network.handle_report(&report_id, status).await - }); - } - - fn delete_report_message( - &mut self, - message_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - let message_id = message_id.to_string(); - self.report_action(window, cx, move |network| async move { - network.delete_message(&message_id).await - }); - } - - fn timeout_report_target( - &mut self, - user_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - let user_id = user_id.to_string(); - self.report_action(window, cx, move |network| async move { - network.timeout_user(&user_id, 60).await - }); - } - - fn ban_report_target( - &mut self, - user_id: &str, - reason: &str, - window: &mut Window, - cx: &mut Context, - ) { - let user_id = user_id.to_string(); - let reason = reason.to_string(); - self.report_action(window, cx, move |network| async move { - network - .ban_user(&user_id, Some(reason.as_str()), false) - .await - }); - } - - fn select_admin_tab(&mut self, tab: AdminTab, window: &mut Window, cx: &mut Context) { - self.chat.admin_tab = tab; - if tab == AdminTab::Server { - self.fill_server_form(window, cx); - } - self.load_admin(window, cx); - cx.notify(); - } - - fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context) { - let Some(settings) = self.server.clone() else { - return; - }; - self.chat.server_registration_open = settings.registration_open; - self.chat.server_maintenance = settings.maintenance; - self.chat.server_name.update(cx, |input, cx| { - input.set_value(settings.name.as_str(), window, cx) - }); - self.chat.server_limit.update(cx, |input, cx| { - input.set_value( - (settings.max_attachment_bytes / MB as u64) - .to_string() - .as_str(), - window, - cx, - ) - }); - self.chat.server_user_quota.update(cx, |input, cx| { - input.set_value( - (settings.user_quota_bytes / MB as u64) - .to_string() - .as_str(), - window, - cx, - ) - }); - self.chat.server_community_quota.update(cx, |input, cx| { - input.set_value( - (settings.community_quota_bytes / MB as u64) - .to_string() - .as_str(), - window, - cx, - ) - }); - self.chat.server_message_retention.update(cx, |input, cx| { - input.set_value(settings.message_retention_days.to_string().as_str(), window, cx) - }); - self.chat - .server_attachment_retention - .update(cx, |input, cx| { - input.set_value( - settings.attachment_retention_days.to_string().as_str(), - window, - cx, - ) - }); - self.chat.server_announcement.update(cx, |input, cx| { - input.set_value(settings.announcement.as_str(), window, cx) - }); - self.chat.server_max_communities.update(cx, |input, cx| { - input.set_value(settings.max_communities_per_user.to_string().as_str(), window, cx) - }); - self.chat.server_max_message_length.update(cx, |input, cx| { - input.set_value(settings.max_message_length.to_string().as_str(), window, cx) - }); - self.chat.server_max_avatar.update(cx, |input, cx| { - input.set_value( - (settings.max_avatar_bytes / KB as u64).to_string().as_str(), - window, - cx, - ) - }); - self.chat.server_messages_per_minute.update(cx, |input, cx| { - input.set_value(settings.messages_per_minute.to_string().as_str(), window, cx) - }); - self.chat.server_logins_per_minute.update(cx, |input, cx| { - input.set_value(settings.logins_per_minute.to_string().as_str(), window, cx) - }); - } - - fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context) { - let name = self.chat.server_name.read(cx).text().to_string(); - let max_attachment_bytes = - megabytes_bytes(&self.chat.server_limit.read(cx).text().to_string()); - let user_quota_bytes = - megabytes_bytes(&self.chat.server_user_quota.read(cx).text().to_string()); - let community_quota_bytes = - megabytes_bytes(&self.chat.server_community_quota.read(cx).text().to_string()); - let message_retention_days = - number(&self.chat.server_message_retention.read(cx).text().to_string()); - let attachment_retention_days = - number(&self.chat.server_attachment_retention.read(cx).text().to_string()); - let announcement = self.chat.server_announcement.read(cx).text().to_string(); - let max_communities_per_user = - number(&self.chat.server_max_communities.read(cx).text().to_string()); - let max_message_length = - number(&self.chat.server_max_message_length.read(cx).text().to_string()); - let max_avatar_bytes = kilobytes_bytes(&self.chat.server_max_avatar.read(cx).text().to_string()); - let messages_per_minute = - number(&self.chat.server_messages_per_minute.read(cx).text().to_string()); - let logins_per_minute = - number(&self.chat.server_logins_per_minute.read(cx).text().to_string()); - let settings = ServerSettings { - name, - registration_open: self.chat.server_registration_open, - max_attachment_bytes, - maintenance: self.chat.server_maintenance, - user_quota_bytes, - community_quota_bytes, - message_retention_days, - attachment_retention_days, - announcement, - max_communities_per_user, - max_message_length, - max_avatar_bytes, - messages_per_minute, - logins_per_minute, - }; - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.update_server_settings(settings).await { - Ok(settings) => { - let _ = this.update(cx, |yumush, cx| { - yumush.server = Some(settings); - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn submit_new_user(&mut self, window: &mut Window, cx: &mut Context) { - let username = self.chat.new_username.read(cx).text().to_string(); - let password = self.chat.new_password.read(cx).text().to_string(); - self.chat - .new_password - .update(cx, |input, cx| input.set_value("", window, cx)); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.create_user(&username, &password).await { - Ok(_) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush - .chat - .new_username - .update(cx, |input, cx| input.set_value("", window, cx)); - yumush.load_users(window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn load_overview(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let loaded = async { - Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?)) - } - .await; - let (overview, stats) = match loaded { - Ok(loaded) => loaded, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_overview = Some(overview); - yumush.chat.admin_stats = stats; - cx.notify(); - }); - }) - .detach(); - } - - fn load_admin_logs(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let (Some(actor_id), Some(target_id)) = ( - self.log_user(&self.chat.admin_log_actor, cx), - self.log_user(&self.chat.admin_log_target, cx), - ) else { - window.push_notification(Notification::error("Unknown user"), cx); - return; - }; - let action = self - .chat - .admin_log_action - .read(cx) - .selected_value() - .copied() - .filter(|name| *name != "All") - .map(str::to_string); - let after_ms = day_millis(&search_text(&self.chat.admin_log_from, cx), false); - let before_ms = day_millis(&search_text(&self.chat.admin_log_to, cx), true); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let entries = match network - .admin_logs(actor_id, target_id, action, after_ms, before_ms) - .await - { - Ok(entries) => entries, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_logs = entries; - cx.notify(); - }); - }) - .detach(); - } - - pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let accounts = match network.users().await { - Ok(accounts) => accounts, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - for account in &accounts { - yumush.request_user_avatar(&account.user, cx); - } - yumush.chat.ghost = yumush - .user - .as_ref() - .and_then(|me| accounts.iter().find(|account| account.user.id == me.id)) - .is_some_and(|account| account.ghost); - yumush.chat.admin_users = accounts; - cx.notify(); - }); - }) - .detach(); - } - - pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context) { - if self.chat.view == View::Admin && self.chat.admin_tab == AdminTab::Voice { - self.load_voice_rooms(window, cx); - } - } - - fn load_voice_rooms(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let rooms = match network.voice_rooms().await { - Ok(rooms) => rooms, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_voice_rooms = rooms; - cx.notify(); - }); - }) - .detach(); - } - - fn voice_action( - &mut self, - window: &mut Window, - cx: &mut Context, - action: impl FnOnce(NetworkHandle) -> Fut + 'static, - ) where - Fut: Future> + 'static, - { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| match action(network).await { - Ok(()) => { - let _ = - this.update_in(cx, |yumush, window, cx| yumush.load_voice_rooms(window, cx)); - } - Err(error) => notify_error(&this, cx, error), - }) - .detach(); - } - - fn set_server_mute( - &mut self, - user_id: &str, - muted: bool, - window: &mut Window, - cx: &mut Context, - ) { - let user_id = user_id.to_string(); - self.voice_action(window, cx, move |network| async move { - network.server_mute(&user_id, muted).await - }); - } - - fn kick_from_voice(&mut self, user_id: &str, window: &mut Window, cx: &mut Context) { - let user_id = user_id.to_string(); - self.voice_action(window, cx, move |network| async move { - network.kick_from_voice(&user_id).await - }); - } - - fn set_admin_community_voice( - &mut self, - community_id: &str, - enabled: bool, - window: &mut Window, - cx: &mut Context, - ) { - let network = self.network.clone(); - let community_id = community_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.set_community_voice(&community_id, enabled).await { - Ok(_) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.load_admin_communities(window, cx) - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn load_admin_communities(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let summaries = match network.all_communities().await { - Ok(summaries) => summaries, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - for summary in &summaries { - if let Some(avatar_id) = &summary.community.avatar_id { - yumush.request_avatar(avatar_id, cx); - } - if let Some(owner) = &summary.owner { - yumush.request_user_avatar(owner, cx); - } - } - yumush.chat.admin_communities = summaries; - cx.notify(); - }); - }) - .detach(); - } - - fn delete_admin_community( - &mut self, - community_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - if self.chat.pending_community_delete.as_deref() != Some(community_id) { - self.chat.pending_community_delete = Some(community_id.to_string()); - cx.notify(); - return; - } - self.chat.pending_community_delete = None; - let network = self.network.clone(); - let community_id = community_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_community(&community_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.remove_community(&community_id); - yumush.load_admin_communities(window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn open_transfer(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { - self.chat.transfer = Some(Transfer { - community_id: community_id.clone(), - members: Vec::new(), - pending: None, - }); - let entity = cx.entity(); - window.open_dialog(cx, move |dialog, _, cx| { - let yumush = entity.read(cx); - let palette = yumush.themed(cx); - let rows: Vec = yumush.transfer_rows(&entity, palette); - - dialog.title("Transfer ownership").child( - div() - .id("transfer_scroll") - .max_h(px(360.)) - .overflow_y_scroll() - .child(div().flex().flex_col().children(rows)), - ) - }); - self.load_transfer_members(community_id, window, cx); - } - - fn load_transfer_members( - &self, - community_id: String, - window: &mut Window, - cx: &mut Context, - ) { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let members = match network.members(&community_id).await { - Ok(members) => members, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update_in(cx, |yumush, window, cx| { - for member in &members { - yumush.request_user_avatar(&member.user, cx); - } - let Some(transfer) = yumush.chat.transfer.as_mut() else { - return; - }; - if transfer.community_id == community_id { - transfer.members = members; - window.refresh(); - cx.notify(); - } - }); - }) - .detach(); - } - - fn transfer_rows(&self, entity: &Entity, palette: Palette) -> Vec { - let Some(transfer) = &self.chat.transfer else { - return Vec::new(); - }; - - transfer - .members - .iter() - .filter(|member| member.rank != Rank::Owner) - .map(|member| { - let pending = transfer.pending.as_deref() == Some(member.user.id.as_str()); - self.transfer_row(member, pending, entity, palette) - .into_any_element() - }) - .collect() - } - - fn transfer_to(&mut self, user_id: &str, window: &mut Window, cx: &mut Context) { - let Some(transfer) = self.chat.transfer.as_mut() else { - return; - }; - if transfer.pending.as_deref() != Some(user_id) { - transfer.pending = Some(user_id.to_string()); - window.refresh(); - cx.notify(); - return; - } - let community_id = transfer.community_id.clone(); - let network = self.network.clone(); - let user_id = user_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.transfer_ownership(&community_id, &user_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.transfer = None; - window.close_dialog(cx); - yumush.load_admin_communities(window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn set_admin_role( - &mut self, - user_id: &str, - role: Role, - window: &mut Window, - cx: &mut Context, - ) { - let network = self.network.clone(); - let user_id = user_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.set_role(&user_id, role).await { - Ok(user) => { - let _ = this.update(cx, |yumush, cx| { - let index = yumush - .chat - .admin_users - .iter() - .position(|existing| existing.user.id == user.id); - if let Some(index) = index { - yumush.chat.admin_users[index].user = user; - } - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn delete_admin_user(&mut self, user_id: &str, window: &mut Window, cx: &mut Context) { - if self.chat.pending_admin_delete.as_deref() != Some(user_id) { - self.chat.pending_admin_delete = Some(user_id.to_string()); - cx.notify(); - return; - } - self.chat.pending_admin_delete = None; - let network = self.network.clone(); - let user_id = user_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_user(&user_id).await { - Ok(()) => { - let _ = this.update(cx, |yumush, cx| { - yumush - .chat - .admin_users - .retain(|account| account.user.id != user_id); - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn admin_user_action( - &mut self, - window: &mut Window, - cx: &mut Context, - action: impl FnOnce(NetworkHandle) -> Fut + 'static, - ) where - Fut: Future> + 'static, - { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| match action(network).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| yumush.load_users(window, cx)); - } - Err(error) => notify_error(&this, cx, error), - }) - .detach(); - } - - fn suspend_admin_user( - &mut self, - user_id: &str, - suspended: bool, - window: &mut Window, - cx: &mut Context, - ) { - let user_id = user_id.to_string(); - self.admin_user_action(window, cx, move |network| async move { - network.suspend_user(&user_id, suspended).await - }); - } - - fn revoke_admin_sessions( - &mut self, - user_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - let user_id = user_id.to_string(); - self.admin_user_action(window, cx, move |network| async move { - network.revoke_sessions(&user_id).await - }); - } - - fn clear_admin_profile(&mut self, user_id: &str, window: &mut Window, cx: &mut Context) { - let user_id = user_id.to_string(); - self.admin_user_action(window, cx, move |network| async move { - network.clear_profile(&user_id).await.map(|_| ()) - }); - } - - fn toggle_admin_password(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_admin_password.as_deref() == Some(user_id) { - self.chat.pending_admin_password = None; - } else { - self.chat.pending_admin_password = Some(user_id.to_string()); - } - cx.notify(); - } - - fn reset_admin_password(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_admin_password.take() else { - return; - }; - let password = self.chat.admin_password.read(cx).text().to_string(); - self.chat - .admin_password - .update(cx, |input, cx| input.set_value("", window, cx)); - self.admin_user_action(window, cx, move |network| async move { - network.reset_password(&user_id, &password).await - }); - } - - fn load_sessions(&self, user_id: String, window: &mut Window, cx: &mut Context) { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.sessions(&user_id).await { - Ok(sessions) => { - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_sessions = Some((user_id, sessions)); - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn toggle_admin_sessions( - &mut self, - user_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - if self - .chat - .admin_sessions - .as_ref() - .is_some_and(|(open, _)| open == user_id) - { - self.chat.admin_sessions = None; - cx.notify(); - return; - } - self.load_sessions(user_id.to_string(), window, cx); - } - - fn revoke_admin_session( - &mut self, - user_id: &str, - session_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - let network = self.network.clone(); - let user_id = user_id.to_string(); - let session_id = session_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.revoke_session(&user_id, &session_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.load_sessions(user_id, window, cx) - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn toggle_admin_rename(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_admin_rename.as_deref() == Some(user_id) { - self.chat.pending_admin_rename = None; - } else { - self.chat.pending_admin_rename = Some(user_id.to_string()); - } - cx.notify(); - } - - fn rename_admin_user(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_admin_rename.take() else { - return; - }; - let username = self.chat.admin_rename.read(cx).text().to_string(); - self.chat - .admin_rename - .update(cx, |input, cx| input.set_value("", window, cx)); - self.admin_user_action(window, cx, move |network| async move { - network.rename_user(&user_id, &username).await.map(|_| ()) - }); - } - - fn toggle_admin_timeout(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_admin_timeout.as_deref() == Some(user_id) { - self.chat.pending_admin_timeout = None; - } else { - self.chat.pending_admin_timeout = Some(user_id.to_string()); - } - cx.notify(); - } - - fn confirm_admin_timeout(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_admin_timeout.clone() else { - return; - }; - let minutes = self.chat.admin_timeout.read(cx).text().to_string(); - let Ok(minutes) = minutes.trim().parse::() else { - return; - }; - self.chat.pending_admin_timeout = None; - self.chat - .admin_timeout - .update(cx, |input, cx| input.set_value("", window, cx)); - self.admin_user_action(window, cx, move |network| async move { - network.timeout_user(&user_id, minutes).await - }); - } - - fn toggle_admin_ban(&mut self, user_id: &str, cx: &mut Context) { - if self.chat.pending_admin_ban.as_deref() == Some(user_id) { - self.chat.pending_admin_ban = None; - } else { - self.chat.pending_admin_ban = Some(user_id.to_string()); - } - cx.notify(); - } - - fn toggle_admin_ban_ip(&mut self, cx: &mut Context) { - self.chat.admin_ban_ip = !self.chat.admin_ban_ip; - cx.notify(); - } - - fn confirm_admin_ban(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_admin_ban.take() else { - return; - }; - let reason = self.chat.admin_ban_reason.read(cx).text().to_string(); - let reason = reason.trim().to_string(); - let reason = (!reason.is_empty()).then_some(reason); - let ip = self.chat.admin_ban_ip; - self.chat - .admin_ban_reason - .update(cx, |input, cx| input.set_value("", window, cx)); - self.admin_user_action(window, cx, move |network| async move { - network.ban_user(&user_id, reason.as_deref(), ip).await - }); - } - - fn load_access(&self, window: &mut Window, cx: &mut Context) { - self.load_invites(window, cx); - self.load_server_bans(window, cx); - } - - fn load_invites(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let codes = match network.invite_codes().await { - Ok(codes) => codes, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_invites = codes; - cx.notify(); - }); - }) - .detach(); - } - - fn load_server_bans(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let bans = match network.server_bans().await { - Ok(bans) => bans, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_bans = bans; - cx.notify(); - }); - }) - .detach(); - } - - fn create_invite(&mut self, window: &mut Window, cx: &mut Context) { - let uses = self.chat.invite_uses.read(cx).text().to_string(); - let Ok(uses) = uses.trim().parse::() else { - return; - }; - let hours = self.chat.invite_hours.read(cx).text().to_string(); - let hours = match hours.trim() { - "" => None, - text => match text.parse::() { - Ok(hours) => Some(hours), - Err(_) => return, - }, - }; - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.create_invite_code(uses, hours).await { - Ok(_) => { - let _ = - this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx)); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn delete_invite(&mut self, code: &str, window: &mut Window, cx: &mut Context) { - if self.chat.pending_invite_delete.as_deref() != Some(code) { - self.chat.pending_invite_delete = Some(code.to_string()); - cx.notify(); - return; - } - self.chat.pending_invite_delete = None; - let network = self.network.clone(); - let code = code.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_invite_code(&code).await { - Ok(()) => { - let _ = - this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx)); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn copy_invite(&self, code: &str, cx: &mut Context) { - cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); - } - - fn remove_ban(&mut self, id: &str, window: &mut Window, cx: &mut Context) { - let network = self.network.clone(); - let id = id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.remove_server_ban(&id).await { - Ok(()) => { - let _ = this - .update_in(cx, |yumush, window, cx| yumush.load_server_bans(window, cx)); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn messages_body(&self, entity: &Entity, palette: Palette) -> Vec { - let filters = div() - .px(px(12.)) - .py(px(8.)) - .flex() - .flex_col() - .gap(px(8.)) - .child(field(palette, &self.chat.admin_message_text)) - .child(field(palette, &self.chat.admin_message_user)) - .child(field(palette, &self.chat.admin_message_community)) - .child( - div() - .flex() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_message_from)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_message_to)), - ), - ) - .child(div().flex().justify_end().child(accent_button( - "search_messages", - "Search", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.search_messages(window, cx) - }), - ))); - let rows: Vec
= self - .chat - .admin_messages - .iter() - .map(|hit| { - let pending = - self.chat.pending_message_delete.as_deref() == Some(hit.message.id.as_str()); - message_hit_row(hit, pending, entity, palette) - }) - .collect(); - - vec![ - filters.into_any_element(), - section("Messages", palette, rows).into_any_element(), - ] - } - - fn storage_body(&self, entity: &Entity, palette: Palette) -> Vec { - let users: Vec
= self - .chat - .admin_usage_users - .iter() - .map(|usage| usage_row(&usage.user.username, usage.bytes, usage.count, palette)) - .collect(); - let communities: Vec
= self - .chat - .admin_usage_communities - .iter() - .map(|usage| usage_row(&usage.community, usage.bytes, usage.count, palette)) - .collect(); - let filters = div() - .px(px(12.)) - .py(px(8.)) - .flex() - .flex_col() - .gap(px(8.)) - .child( - div() - .flex() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_attachment_user)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_attachment_community)), - ), - ) - .child(div().flex().justify_end().child(accent_button( - "search_attachments", - "Search", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.search_attachments(window, cx) - }), - ))); - let attachments: Vec
= self - .chat - .admin_attachments - .iter() - .map(|info| { - let pending = self.chat.pending_attachment_delete.as_deref() - == Some(info.attachment.id.as_str()); - attachment_row(info, pending, entity, palette) - }) - .collect(); - - vec![ - section("Users", palette, users).into_any_element(), - section("Communities", palette, communities).into_any_element(), - filters.into_any_element(), - section("Attachments", palette, attachments).into_any_element(), - ] - } - - fn search_messages(&mut self, window: &mut Window, cx: &mut Context) { - let text = search_text(&self.chat.admin_message_text, cx); - let username = search_text(&self.chat.admin_message_user, cx); - let community = search_text(&self.chat.admin_message_community, cx); - let user_id = self.resolve_user(&username); - let community_id = self.resolve_community(&community); - let after_ms = day_millis(&search_text(&self.chat.admin_message_from, cx), false); - let before_ms = day_millis(&search_text(&self.chat.admin_message_to, cx), true); - let text = (!text.is_empty()).then_some(text); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let hits = match network - .search_messages(text, user_id, community_id, after_ms, before_ms) - .await - { - Ok(hits) => hits, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_messages = hits; - cx.notify(); - }); - }) - .detach(); - } - - fn delete_admin_message( - &mut self, - message_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - if self.chat.pending_message_delete.as_deref() != Some(message_id) { - self.chat.pending_message_delete = Some(message_id.to_string()); - cx.notify(); - return; - } - self.chat.pending_message_delete = None; - let network = self.network.clone(); - let message_id = message_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_message(&message_id).await { - Ok(()) => { - let _ = this.update(cx, |yumush, cx| { - yumush - .chat - .admin_messages - .retain(|hit| hit.message.id != message_id); - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn purge_admin_user(&mut self, user_id: &str, window: &mut Window, cx: &mut Context) { - if self.chat.pending_admin_purge.as_deref() != Some(user_id) { - self.chat.pending_admin_purge = Some(user_id.to_string()); - cx.notify(); - return; - } - self.chat.pending_admin_purge = None; - let network = self.network.clone(); - let user_id = user_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.purge_user(&user_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush - .chat - .admin_messages - .retain(|hit| hit.message.user_id != user_id); - yumush.load_users(window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn log_user(&self, input: &Entity, cx: &App) -> Option> { - let name = search_text(input, cx); - if name.is_empty() { - return Some(None); - } - - self.resolve_user(&name).map(Some) - } - - fn export_admin_log(&self, window: &mut Window, cx: &mut Context) { - let Some(directory) = dirs::download_dir() else { - window.push_notification(Notification::error("No download folder"), cx); - return; - }; - let name = format!( - "yumush-admin-log-{}.csv", - millis_time(now_ms(), "%Y%m%d-%H%M%S") - ); - let path = directory.join(name); - match std::fs::write(&path, admin_log_csv(&self.chat.admin_logs)) { - Ok(()) => window.push_notification( - Notification::success(path.display().to_string()), - cx, - ), - Err(error) => window.push_notification(Notification::error(error.to_string()), cx), - } - } - - fn resolve_user(&self, username: &str) -> Option { - self.chat - .admin_users - .iter() - .find(|account| account.user.username.to_lowercase() == username) - .map(|account| account.user.id.clone()) - } - - fn resolve_community(&self, name: &str) -> Option { - self.chat - .admin_communities - .iter() - .find(|summary| { - summary.community.kind == CommunityKind::Group - && summary.community.name.to_lowercase() == name - }) - .map(|summary| summary.community.id.clone()) - } - - fn load_storage(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } - self.search_attachments(window, cx); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let (users, communities) = match network.storage_usage().await { - Ok(usage) => usage, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_usage_users = users; - yumush.chat.admin_usage_communities = communities; - cx.notify(); - }); - }) - .detach(); - } - - fn search_attachments(&self, window: &mut Window, cx: &mut Context) { - let username = search_text(&self.chat.admin_attachment_user, cx); - let community = search_text(&self.chat.admin_attachment_community, cx); - let user_id = self.resolve_user(&username); - let community_id = self.resolve_community(&community); - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - let attachments = match network.attachments(user_id, community_id).await { - Ok(attachments) => attachments, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; - - let _ = this.update(cx, |yumush, cx| { - yumush.chat.admin_attachments = attachments; - cx.notify(); - }); - }) - .detach(); - } - - fn delete_admin_attachment( - &mut self, - attachment_id: &str, - window: &mut Window, - cx: &mut Context, - ) { - if self.chat.pending_attachment_delete.as_deref() != Some(attachment_id) { - self.chat.pending_attachment_delete = Some(attachment_id.to_string()); - cx.notify(); - return; - } - self.chat.pending_attachment_delete = None; - let network = self.network.clone(); - let attachment_id = attachment_id.to_string(); - - cx.spawn_in(window, async move |this, cx| { - match network.delete_attachment(&attachment_id).await { - Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.load_storage(window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn admin_tabs(&self, entity: &Entity, palette: Palette) -> Div { - segment_track(palette).children(ADMIN_TABS.map(|(tab, label)| { - let label = match tab { - AdminTab::Reports if self.chat.open_reports > 0 => { - format!("{label} {}", self.chat.open_reports) - } - _ => label.to_string(), - }; - segment( - clickable( - label.clone(), - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.select_admin_tab(tab, window, cx) - }), - ), - self.chat.admin_tab == tab, - palette, - ) - .px(px(10.)) - .child(label) - })) - } - - fn ghost_switch(&self, entity: &Entity, palette: Palette) -> impl IntoElement { - let enabled = self.chat.ghost; - - admin_button( - "ghost_switch".to_string(), - if enabled { "Ghost on" } else { "Ghost off" }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.set_ghost(!enabled, window, cx) - }), - ) - } - - fn set_ghost(&self, enabled: bool, window: &mut Window, cx: &mut Context) { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network.set_ghost(enabled).await { - Ok(()) => { - let _ = this.update(cx, |yumush, cx| { - yumush.chat.ghost = enabled; - if enabled { - yumush.force_mute(cx); - } - cx.notify(); - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - fn open_admin_community( - &mut self, - community: Community, - window: &mut Window, - cx: &mut Context, - ) { - let community_id = community.id.clone(); - self.chat.opened = Some(community); - self.show_view(View::Chat, window, cx); - self.select_community(community_id, window, cx); - } - - fn report_filters(&self, entity: &Entity, palette: Palette) -> Div { - segment_track(palette).children(REPORT_FILTERS.map(|(status, label)| { - segment( - clickable( - label, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.select_report_filter(status, window, cx) - }), - ), - self.chat.report_filter == status, - palette, - ) - .px(px(10.)) - .child(label) - })) - } - - fn reports_body(&self, entity: &Entity, palette: Palette) -> Vec { - let rows: Vec
= self - .chat - .admin_reports - .iter() - .map(|report| self.report_row(report, entity, palette)) - .collect(); - - vec![ - self.report_filters(entity, palette).into_any_element(), - section("Reports", palette, rows).into_any_element(), - ] - } - - fn report_row(&self, report: &Report, entity: &Entity, palette: Palette) -> Div { - let mut lines = div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child( - div() - .font_weight(FontWeight::SEMIBOLD) - .truncate() - .child(format!( - "{} → {}", - user_name(&report.reporter), - user_name(&report.target) - )), - ) - .child(div().truncate().child(report.reason.clone())); - if let Some(body) = &report.body { - lines = lines.child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(body.clone()), - ); - } - lines = lines.child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(format!( - "{} · {}", - report.community.as_deref().unwrap_or("deleted community"), - id_time(&report.id, "%b %-d, %H:%M") - )), - ); - if report.status != ReportStatus::Open { - lines = lines.child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(format!( - "{} by {}", - report.status.as_str(), - user_name(&report.handled_by) - )), - ); - } - - let actions = self.report_actions(report, entity, palette); - - div() - .px(px(12.)) - .py(px(6.)) - .flex() - .flex_col() - .gap(px(4.)) - .child(lines) - .children((!actions.is_empty()).then(|| { - div() - .flex() - .flex_wrap() - .items_center() - .gap(px(4.)) - .children(actions) - })) - } - - fn report_actions( - &self, - report: &Report, - entity: &Entity, - palette: Palette, - ) -> Vec { - if report.status != ReportStatus::Open { - return Vec::new(); - } - let resolve_id = report.id.clone(); - let dismiss_id = report.id.clone(); - let mut buttons = vec![ - admin_button( - format!("resolve_report_{}", report.id), - "Resolve", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.handle_report(&resolve_id, ReportStatus::Resolved, window, cx) - }), - ) - .into_any_element(), - admin_button( - format!("dismiss_report_{}", report.id), - "Dismiss", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.handle_report(&dismiss_id, ReportStatus::Dismissed, window, cx) - }), - ) - .into_any_element(), - ]; - if let (Some(message_id), Some(_)) = (&report.message_id, &report.community_id) { - let message_id = message_id.clone(); - buttons.push( - admin_button( - format!("delete_report_message_{}", report.id), - "Delete message", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_report_message(&message_id, window, cx) - }), - ) - .into_any_element(), - ); - } - if let Some(target) = &report.target { - let timeout_id = target.id.clone(); - let ban_id = target.id.clone(); - let ban_reason = report.reason.clone(); - buttons.push( - admin_button( - format!("timeout_report_{}", report.id), - "Timeout 1h", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.timeout_report_target(&timeout_id, window, cx) - }), - ) - .into_any_element(), - ); - buttons.push( - admin_button( - format!("ban_report_{}", report.id), - "Ban", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.ban_report_target(&ban_id, &ban_reason, window, cx) - }), - ) - .into_any_element(), - ); - } - - buttons - } - - fn overview_rows(&self, palette: Palette) -> Vec
{ - let Some(overview) = &self.chat.admin_overview else { - return Vec::new(); - }; - - let mut rows: Vec
= [ - ("Users", overview.users.to_string()), - ("Builders", overview.builders.to_string()), - ("Communities", overview.communities.to_string()), - ("Online", overview.online.to_string()), - ("In voice", overview.voice.to_string()), - ("Storage", storage(overview.storage_bytes)), - ] - .into_iter() - .map(|(label, value)| row(label, div().text_color(palette.muted).child(value))) - .collect(); - rows.push(bar_chart( - "Active users", - &self.chat.admin_stats, - |stat| stat.active_users, - palette, - )); - rows.push(bar_chart( - "Messages", - &self.chat.admin_stats, - |stat| stat.messages, - palette, - )); - - rows - } - - fn server_body(&self, entity: &Entity, palette: Palette) -> Vec { - let rows = vec![ - row( - "Name", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_name)), - ), - row( - "Registration", - segmented( - [(true, "Open"), (false, "Closed")], - self.chat.server_registration_open, - entity, - palette, - |yumush, open, _| yumush.chat.server_registration_open = open, - ), - ), - row( - "Maintenance", - segmented( - [(false, "Off"), (true, "On")], - self.chat.server_maintenance, - entity, - palette, - |yumush, on, _| yumush.chat.server_maintenance = on, - ), - ), - row( - "Max attachment (MB)", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_limit)), - ), - row( - "User quota (MB)", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_user_quota)), - ), - row( - "Community quota (MB)", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_community_quota)), - ), - row( - "Message retention (days)", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_message_retention)), - ), - row( - "Attachment retention (days)", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_attachment_retention)), - ), - row( - "Announcement", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_announcement)), - ), - row( - "Max communities per user", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_max_communities)), - ), - row( - "Max message length", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_max_message_length)), - ), - row( - "Max avatar (KB)", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_max_avatar)), - ), - row( - "Messages per minute", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_messages_per_minute)), - ), - row( - "Logins per minute", - div() - .w(px(200.)) - .child(field(palette, &self.chat.server_logins_per_minute)), - ), - row( - "", - accent_button( - "save_server", - "Save", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.save_server_settings(window, cx) - }), - ), - ), - ]; - - vec![section("Server", palette, rows).into_any_element()] - } - - fn create_user_body(&self, entity: &Entity, palette: Palette) -> AnyElement { - let form = div() - .min_h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.new_username)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.new_password)), - ) - .child(accent_button( - "create_user", - "Create", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.submit_new_user(window, cx) - }), - )); - - section("Create user", palette, vec![form]).into_any_element() - } - - fn log_body(&self, entity: &Entity, palette: Palette) -> Vec { - let filters = div() - .px(px(12.)) - .py(px(8.)) - .flex() - .flex_col() - .gap(px(8.)) - .child( - div() - .flex() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_log_actor)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_log_target)), - ), - ) - .child(Select::new(&self.chat.admin_log_action).w(px(240.))) - .child( - div() - .flex() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_log_from)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_log_to)), - ), - ) - .child( - div() - .flex() - .justify_end() - .gap(px(8.)) - .child(admin_button( - "export_admin_log".to_string(), - "Export", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.export_admin_log(window, cx) - }), - )) - .child(accent_button( - "apply_admin_log", - "Apply", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.load_admin_logs(window, cx) - }), - )), - ); - let rows: Vec
= self - .chat - .admin_logs - .iter() - .map(|entry| admin_log_row(entry, palette)) - .collect(); - - vec![ - filters.into_any_element(), - section("Log", palette, rows).into_any_element(), - ] - } - - fn communities_body( - &self, - entity: &Entity, - palette: Palette, - cx: &App, - ) -> Vec { - let query = search_text(&self.chat.admin_search, cx); - let rows: Vec
= self - .chat - .admin_communities - .iter() - .filter(|summary| { - summary - .community - .name - .to_lowercase() - .contains(query.as_str()) - }) - .map(|summary| self.community_row(summary, entity, palette)) - .collect(); - - vec![ - div() - .child(Input::new(&self.chat.admin_search)) - .into_any_element(), - section("Communities", palette, rows).into_any_element(), - ] - } - - fn users_body(&self, entity: &Entity, palette: Palette, cx: &App) -> Vec { - let query = search_text(&self.chat.admin_search, cx); - let rows: Vec
= match self.user.as_ref() { - Some(me) => self - .chat - .admin_users - .iter() - .filter(|account| { - account - .user - .username - .to_lowercase() - .contains(query.as_str()) - }) - .flat_map(|account| { - let user_id = account.user.id.as_str(); - let mut rows = vec![self.admin_row(account, me, entity, palette)]; - if let Some((_, sessions)) = self - .chat - .admin_sessions - .as_ref() - .filter(|(open, _)| open == user_id) - { - rows.extend(sessions.iter().map(|session| { - self.admin_session_row(user_id, session, entity, palette) - })); - } - if self.chat.pending_admin_password.as_deref() == Some(user_id) { - rows.push(self.admin_password_row(user_id, entity, palette)); - } - if self.chat.pending_admin_rename.as_deref() == Some(user_id) { - rows.push(self.admin_rename_row(user_id, entity, palette)); - } - if self.chat.pending_admin_timeout.as_deref() == Some(user_id) { - rows.push(self.admin_timeout_row(user_id, entity, palette)); - } - if self.chat.pending_admin_ban.as_deref() == Some(user_id) { - rows.push(self.admin_ban_row(user_id, entity, palette)); - } - rows - }) - .collect(), - None => Vec::new(), - }; - - vec![ - self.create_user_body(entity, palette), - div() - .child(Input::new(&self.chat.admin_search)) - .into_any_element(), - section("Users", palette, rows).into_any_element(), - ] - } - - pub(super) fn admin_page( - &self, - entity: &Entity, - palette: Palette, - cx: &App, - ) -> impl IntoElement { - let body = match self.chat.admin_tab { - AdminTab::Overview => { - vec![section("Overview", palette, self.overview_rows(palette)).into_any_element()] - } - AdminTab::Users => self.users_body(entity, palette, cx), - AdminTab::Communities => self.communities_body(entity, palette, cx), - AdminTab::Messages => self.messages_body(entity, palette), - AdminTab::Voice => self.voice_body(entity, palette), - AdminTab::Storage => self.storage_body(entity, palette), - AdminTab::Access => self.access_body(entity, palette), - AdminTab::Reports => self.reports_body(entity, palette), - AdminTab::Server => self.server_body(entity, palette), - AdminTab::Log => self.log_body(entity, palette), - }; - let header = div() - .flex() - .items_center() - .justify_between() - .child(self.admin_tabs(entity, palette)) - .child(self.ghost_switch(entity, palette)); - let mut sections = vec![header.into_any_element()]; - sections.extend(body); - - page("admin_scroll", entity, palette, "Admin", sections) - } - - fn voice_body(&self, entity: &Entity, palette: Palette) -> Vec { - let mut rows = vec![div().flex().justify_end().child(admin_button( - "refresh_voice_button".to_string(), - "Refresh", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.load_voice_rooms(window, cx) - }), - ))]; - for room in &self.chat.admin_voice_rooms { - rows.push( - div() - .h(px(32.)) - .px(px(12.)) - .flex() - .items_center() - .text_size(text(12.)) - .text_color(palette.muted) - .child(room.community.clone()), - ); - rows.extend(room.users.iter().map(|user| { - self.voice_user_row(user, room.muted.contains(&user.id), entity, palette) - })); - } - - vec![section("Voice", palette, rows).into_any_element()] - } - - fn voice_user_row( - &self, - user: &User, - muted: bool, - entity: &Entity, - palette: Palette, - ) -> Div { - let id = user.id.clone(); - let mute_id = id.clone(); - let kick_id = id.clone(); - - div() - .h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(user.username.clone()), - ) - .child(admin_button( - format!("voice_mute_{id}"), - if muted { "Unmute" } else { "Mute" }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.set_server_mute(&mute_id, !muted, window, cx) - }), - )) - .child(admin_button( - format!("voice_kick_{id}"), - "Kick", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.kick_from_voice(&kick_id, window, cx) - }), - )) - } - - fn access_body(&self, entity: &Entity, palette: Palette) -> Vec { - let create = div() - .min_h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .w(px(80.)) - .child(field(palette, &self.chat.invite_uses)), - ) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.invite_hours)), - ) - .child(accent_button( - "create_invite", - "Create", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.create_invite(window, cx) - }), - )); - let invites = std::iter::once(create).chain(self.chat.admin_invites.iter().map(|invite| { - let pending = self.chat.pending_invite_delete.as_deref() == Some(invite.code.as_str()); - invite_row(invite, pending, entity, palette) - })); - let bans = self - .chat - .admin_bans - .iter() - .map(|ban| ban_row(ban, entity, palette)); - - vec![ - section("Invite codes", palette, invites.collect()).into_any_element(), - section("Bans", palette, bans.collect()).into_any_element(), - ] - } - - fn admin_timeout_row(&self, user_id: &str, entity: &Entity, palette: Palette) -> Div { - div() - .h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_timeout)), - ) - .child(admin_button( - format!("confirm_timeout_{user_id}"), - "Confirm", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.confirm_admin_timeout(window, cx) - }), - )) - } - - fn admin_ban_row(&self, user_id: &str, entity: &Entity, palette: Palette) -> Div { - let ip_label = if self.chat.admin_ban_ip { - "IP: on" - } else { - "IP: off" - }; - - div() - .h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_ban_reason)), - ) - .child(admin_button( - format!("ban_ip_{user_id}"), - ip_label, - palette, - entity_action(entity, |yumush, _, cx| yumush.toggle_admin_ban_ip(cx)), - )) - .child(admin_button( - format!("confirm_ban_{user_id}"), - "Confirm", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.confirm_admin_ban(window, cx) - }), - )) - } - - fn admin_session_row( - &self, - user_id: &str, - session: &SessionInfo, - entity: &Entity, - palette: Palette, - ) -> Div { - let revoke_user_id = user_id.to_string(); - let session_id = session.id.clone(); - let revoke_button = admin_button( - format!("revoke_session_{}", session.id), - "Revoke", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.revoke_admin_session(&revoke_user_id, &session_id, window, cx) - }), - ); - let device = if session.device.is_empty() { - "unknown device" - } else { - session.device.as_str() - }; - - div() - .h(px(36.)) - .pl(px(40.)) - .pr(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(device.to_string()), - ) - .child( - div() - .flex_shrink_0() - .text_size(text(11.)) - .text_color(palette.muted) - .child(seen_text(session.last_seen)), - ) - .child(revoke_button) - } - - fn admin_rename_row(&self, user_id: &str, entity: &Entity, palette: Palette) -> Div { - div() - .h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_rename)), - ) - .child(admin_button( - format!("confirm_rename_{user_id}"), - "Confirm", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.rename_admin_user(window, cx) - }), - )) - } - - fn admin_password_row(&self, user_id: &str, entity: &Entity, palette: Palette) -> Div { - div() - .h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.admin_password)), - ) - .child(admin_button( - format!("confirm_password_{user_id}"), - "Confirm", - palette, - entity_action(entity, |yumush, window, cx| { - yumush.reset_admin_password(window, cx) - }), - )) - } - - fn transfer_row( - &self, - member: &Member, - pending: bool, - entity: &Entity, - palette: Palette, - ) -> Div { - let user_id = member.user.id.clone(); - - div() - .h(px(40.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child(avatar( - palette, - &member.user, - px(20.), - text(10.), - &self.chat.avatars, - )) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .child(member.user.username.clone()), - ) - .child(admin_button( - format!("transfer_to_{}", member.user.id), - if pending { "Confirm" } else { "Transfer" }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.transfer_to(&user_id, window, cx) - }), - )) - } - - fn community_row( - &self, - summary: &CommunitySummary, - entity: &Entity, - palette: Palette, - ) -> Div { - let community = &summary.community; - let opened = community.clone(); - let id = community.id.clone(); - let log_id = id.clone(); - let transfer_id = id.clone(); - let delete_id = id.clone(); - let voice_id = id.clone(); - let voice_enabled = community.voice_enabled; - let pending_delete = self.chat.pending_community_delete.as_deref() == Some(id.as_str()); - let owner = summary - .owner - .as_ref() - .map_or("", |owner| owner.username.as_str()); - - div() - .h(px(48.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child(community_icon( - palette, - community, - px(20.), - text(10.), - &self.chat.avatars, - )) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child(div().truncate().child(community.name.clone())) - .child( - div() - .text_size(text(11.)) - .text_color(palette.muted) - .truncate() - .child(owner.to_string()), - ), - ) - .child( - div() - .flex_shrink_0() - .text_size(text(12.)) - .text_color(palette.muted) - .child(summary.members.to_string()), - ) - .child(admin_button( - format!("voice_community_{}", id), - if voice_enabled { - "Voice on" - } else { - "Voice off" - }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.set_admin_community_voice(&voice_id, !voice_enabled, window, cx) - }), - )) - .child(admin_button( - format!("open_community_{}", id), - "Open", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.open_admin_community(opened.clone(), window, cx) - }), - )) - .child(admin_button( - format!("log_community_{}", id), - "Log", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.show_logs(log_id.clone(), window, cx) - }), - )) - .child(admin_button( - format!("transfer_community_{}", id), - "Transfer", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.open_transfer(transfer_id.clone(), window, cx) - }), - )) - .child(danger_button( - format!("delete_community_{}", id), - "Delete", - pending_delete, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_admin_community(&delete_id, window, cx) - }), - )) - } - - fn admin_row( - &self, - account: &Account, - me: &User, - entity: &Entity, - palette: Palette, - ) -> Div { - let user = &account.user; - let is_self = user.id == me.id; - let builder = user.role == Role::Builder; - let manage = permission::can_manage_user(me.role, is_self, user.role); - let suspended = account.suspended; - let timed_out = account - .suspended_until - .filter(|until| *until > now_ms()) - .map(|until| format!("timed out until {}", millis_time(until, "%b %-d, %H:%M"))); - let pending_delete = self.chat.pending_admin_delete.as_deref() == Some(user.id.as_str()); - let role_id = user.id.clone(); - let delete_id = user.id.clone(); - let suspend_id = user.id.clone(); - let sessions_id = user.id.clone(); - let password_id = user.id.clone(); - let profile_id = user.id.clone(); - let sessions_list_id = user.id.clone(); - let rename_id = user.id.clone(); - let timeout_id = user.id.clone(); - let ban_id = user.id.clone(); - let joined = id_time(&user.id, "%b %-d %Y"); - let seen = seen_text(account.last_seen); - let next_role = if builder { Role::User } else { Role::Builder }; - - let role_button = admin_button( - format!("role_{}", user.id), - if builder { - "Remove builder" - } else { - "Make builder" - }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.set_admin_role(&role_id, next_role, window, cx) - }), - ); - - let suspend_button = admin_button( - format!("suspend_user_{}", user.id), - if suspended { "Unsuspend" } else { "Suspend" }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.suspend_admin_user(&suspend_id, !suspended, window, cx) - }), - ); - - let sessions_button = admin_button( - format!("sessions_user_{}", user.id), - "Sign out", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.revoke_admin_sessions(&sessions_id, window, cx) - }), - ); - - let password_button = admin_button( - format!("password_user_{}", user.id), - "Reset password", - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_admin_password(&password_id, cx) - }), - ); - - let sessions_list_button = admin_button( - format!("sessions_list_user_{}", user.id), - "Sessions", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.toggle_admin_sessions(&sessions_list_id, window, cx) - }), - ); - - let rename_button = admin_button( - format!("rename_user_{}", user.id), - "Rename", - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_admin_rename(&rename_id, cx) - }), - ); - - let timeout_button = admin_button( - format!("timeout_user_{}", user.id), - "Timeout", - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_admin_timeout(&timeout_id, cx) - }), - ); - - let ban_button = admin_button( - format!("ban_user_{}", user.id), - "Ban", - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_admin_ban(&ban_id, cx) - }), - ); - - let profile_button = admin_button( - format!("profile_user_{}", user.id), - "Clear profile", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.clear_admin_profile(&profile_id, window, cx) - }), - ); - - let pending_purge = self.chat.pending_admin_purge.as_deref() == Some(user.id.as_str()); - let purge_id = user.id.clone(); - let purge_button = danger_button( - format!("purge_user_{}", user.id), - "Purge", - pending_purge, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.purge_admin_user(&purge_id, window, cx) - }), - ); - - let delete_button = danger_button( - format!("delete_user_{}", user.id), - "Delete", - pending_delete, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_admin_user(&delete_id, window, cx) - }), - ); - - div() - .h(px(48.)) - .px(px(12.)) - .flex() - .items_center() - .gap(px(8.)) - .child(avatar( - palette, - user, - px(20.), - text(10.), - &self.chat.avatars, - )) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .items_center() - .gap(px(6.)) - .child(div().truncate().child(user.username.clone())) - .when(builder, |this| { - this.child( - div() - .text_size(text(11.)) - .text_color(palette.accent) - .child("Builder"), - ) - }) - .when(suspended, |this| { - this.child( - div() - .text_size(text(11.)) - .text_color(palette.danger) - .child("Suspended"), - ) - }) - .when_some(timed_out, |this, label| { - this.child( - div() - .text_size(text(11.)) - .text_color(palette.danger) - .child(label), - ) - }), - ) - .child( - div() - .flex_shrink_0() - .text_size(text(11.)) - .text_color(palette.muted) - .child(format!("joined {joined} · seen {seen}")), - ) - .children(manage.then_some(sessions_list_button)) - .children(manage.then_some(rename_button)) - .children(permission::can_set_role(me.role, is_self).then_some(role_button)) - .children(manage.then_some(suspend_button)) - .children(manage.then_some(sessions_button)) - .children(manage.then_some(password_button)) - .children(manage.then_some(timeout_button)) - .children(manage.then_some(ban_button)) - .children(manage.then_some(profile_button)) - .children(manage.then_some(purge_button)) - .children( - (!is_self && permission::can_delete_user(me.role, is_self, user.role)) - .then_some(delete_button), - ) - } -} diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs new file mode 100644 index 0000000..7b98ae6 --- /dev/null +++ b/crates/client/src/gui/builder.rs @@ -0,0 +1,402 @@ +mod access; +mod communities; +mod log; +mod messages; +mod overview; +mod reports; +mod server; +mod storage; +mod ui; +mod users; +mod voice; + +use common::model::{CommunityKind, Member, Role}; +use gpui_kit::{ + AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, + StatefulInteractiveElement, Styled, Window, + assets::IconName, + component::{Icon, switch::Switch}, + div, + prelude::FluentBuilder as _, + px, +}; + +use self::ui::{accent_button, icon_button, page_heading, plain_button}; +use super::{ + Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header, + text, +}; + +const BUILDER_TABS: [(BuilderTab, &str, IconName); 10] = [ + (BuilderTab::Overview, "Overview", IconName::LayoutDashboard), + (BuilderTab::Users, "Users", IconName::Users), + (BuilderTab::Communities, "Communities", IconName::Building2), + (BuilderTab::Messages, "Messages", IconName::MessageSquare), + (BuilderTab::Voice, "Voice", IconName::Mic), + (BuilderTab::Storage, "Storage", IconName::HardDrive), + (BuilderTab::Access, "Access", IconName::Key), + (BuilderTab::Reports, "Reports", IconName::Flag), + (BuilderTab::Server, "Server", IconName::Server), + (BuilderTab::Log, "Log", IconName::ScrollText), +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum BuilderTab { + Overview, + Users, + Communities, + Messages, + Voice, + Storage, + Access, + Reports, + Server, + Log, +} + +pub(super) struct Transfer { + pub(super) community_id: String, + pub(super) members: Vec, + pub(super) pending: Option, +} + +impl Yumush { + pub(super) fn builder_page( + &self, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> impl IntoElement { + let tab = self.chat.builder_tab; + let title = BUILDER_TABS + .iter() + .find(|(candidate, _, _)| *candidate == tab) + .map_or("", |(_, label, _)| label); + let body = match tab { + BuilderTab::Overview => self + .overview_rows(palette) + .into_iter() + .map(IntoElement::into_any_element) + .collect(), + BuilderTab::Users => self.users_body(entity, palette, cx), + BuilderTab::Communities => self.communities_body(entity, palette, cx), + BuilderTab::Messages => self.messages_body(entity, palette), + BuilderTab::Voice => self.voice_body(entity, palette), + BuilderTab::Storage => self.storage_body(entity, palette), + BuilderTab::Access => self.access_body(entity, palette), + BuilderTab::Reports => self.reports_body(entity, palette), + BuilderTab::Server => self.server_body(entity, palette), + BuilderTab::Log => self.log_body(entity, palette), + }; + let mut sections = vec![ + page_heading(title, self.tab_actions(tab, entity, palette), palette).into_any_element(), + ]; + sections.extend(body); + + div() + .flex_1() + .min_w_0() + .min_h_0() + .flex() + .flex_col() + .child(header(entity, palette, Role::Builder.label())) + .child( + div() + .flex_1() + .min_h_0() + .flex() + .child(self.builder_rail(entity, palette)) + .child( + div() + .id("builder_scroll") + .flex_1() + .min_w_0() + .min_h_0() + .overflow_y_scroll() + .child( + div() + .w_full() + .max_w(px(960.)) + .mx_auto() + .px(px(32.)) + .py(px(28.)) + .flex() + .flex_col() + .gap(px(20.)) + .children(sections), + ), + ), + ) + } + + fn tab_actions( + &self, + tab: BuilderTab, + entity: &Entity, + palette: Palette, + ) -> Vec { + match tab { + BuilderTab::Voice => vec![ + plain_button( + "refresh_voice_button".to_string(), + "Refresh", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.load_voice_rooms(window, cx) + }), + ) + .into_any_element(), + ], + BuilderTab::Server => vec![ + accent_button( + "save_server", + "Save", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.save_server_settings(window, cx) + }), + ) + .into_any_element(), + ], + BuilderTab::Log => vec![ + icon_button( + "export_builder_log".to_string(), + IconName::Download, + "Export", + palette.muted, + palette, + entity_action(entity, |yumush, window, cx| { + yumush.export_builder_log(window, cx) + }), + ) + .into_any_element(), + ], + _ => Vec::new(), + } + } + + fn builder_rail(&self, entity: &Entity, palette: Palette) -> Div { + div() + .w(px(200.)) + .flex_shrink_0() + .flex() + .flex_col() + .gap(px(2.)) + .p(px(8.)) + .bg(palette.panel) + .border_r_1() + .border_color(palette.border) + .children( + BUILDER_TABS.map(|(tab, label, icon)| { + self.builder_nav_item(tab, label, icon, entity, palette) + }), + ) + .child(div().flex_1()) + .child(self.ghost_toggle(entity, palette)) + } + + fn builder_nav_item( + &self, + tab: BuilderTab, + label: &'static str, + icon: IconName, + entity: &Entity, + palette: Palette, + ) -> impl IntoElement { + let active = self.chat.builder_tab == tab; + let color = if active { palette.text } else { palette.muted }; + let open = (tab == BuilderTab::Reports) + .then_some(self.chat.open_reports) + .filter(|count| *count > 0); + + clickable( + format!("builder_tab_{label}"), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.select_builder_tab(tab, window, cx) + }), + ) + .h(px(32.)) + .px(px(10.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .text_size(text(13.)) + .text_color(color) + .when(active, |this| this.bg(palette.hover)) + .child(Icon::new(icon).w(px(14.)).h(px(14.)).text_color(color)) + .child(div().flex_1().min_w_0().truncate().child(label)) + .children(open.map(|count| { + div() + .px(px(6.)) + .rounded_full() + .bg(palette.accent) + .text_color(palette.on_accent) + .text_size(text(11.)) + .child(count.to_string()) + })) + } + + fn ghost_toggle(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + let enabled = self.chat.ghost; + let toggle = entity_action(entity, move |yumush, window, cx| { + yumush.set_ghost(!enabled, window, cx) + }); + + div() + .h(px(32.)) + .px(px(10.)) + .flex() + .items_center() + .justify_between() + .text_size(text(13.)) + .text_color(palette.muted) + .child("Ghost") + .child( + Switch::new("ghost_switch") + .checked(enabled) + .on_change(move |_, window, cx| toggle(window, cx)), + ) + } + + pub(super) fn is_builder(&self) -> bool { + self.user + .as_ref() + .is_some_and(|me| me.role == Role::Builder) + } + + pub(super) fn load_builder(&self, window: &mut Window, cx: &mut Context) { + self.load_open_reports(window, cx); + match self.chat.builder_tab { + BuilderTab::Overview => self.load_overview(window, cx), + BuilderTab::Users => self.load_users(window, cx), + BuilderTab::Communities => self.load_builder_communities(window, cx), + BuilderTab::Messages => {} + BuilderTab::Storage => { + self.load_users(window, cx); + self.load_builder_communities(window, cx); + self.load_storage(window, cx); + } + BuilderTab::Voice => { + self.load_voice_rooms(window, cx); + self.load_builder_communities(window, cx); + } + BuilderTab::Access => self.load_access(window, cx), + BuilderTab::Reports => self.load_reports(window, cx), + BuilderTab::Server => {} + BuilderTab::Log => { + self.load_users(window, cx); + self.load_builder_logs(window, cx); + } + } + } + + pub(super) fn report_created(&self, window: &mut Window, cx: &mut Context) { + self.load_open_reports(window, cx); + if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Reports { + self.load_reports(window, cx); + } + } + + fn select_builder_tab(&mut self, tab: BuilderTab, window: &mut Window, cx: &mut Context) { + self.chat.builder_tab = tab; + if tab == BuilderTab::Server { + self.fill_server_form(window, cx); + } + self.load_builder(window, cx); + cx.notify(); + } + + pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let accounts = match network.users().await { + Ok(accounts) => accounts, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + for account in &accounts { + yumush.request_user_avatar(&account.user, cx); + } + let ghost = yumush + .user + .as_ref() + .and_then(|me| accounts.iter().find(|account| account.user.id == me.id)) + .is_some_and(|account| account.ghost); + yumush.chat.builder_users = accounts; + yumush.set_ghost_state(ghost); + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context) { + if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Voice { + self.load_voice_rooms(window, cx); + } + } + + fn resolve_user(&self, username: &str) -> Option { + self.chat + .builder_users + .iter() + .find(|account| account.user.username.to_lowercase() == username) + .map(|account| account.user.id.clone()) + } + + fn resolve_community(&self, name: &str) -> Option { + self.chat + .builder_communities + .iter() + .find(|summary| { + summary.community.kind == CommunityKind::Group + && summary.community.name.to_lowercase() == name + }) + .map(|summary| summary.community.id.clone()) + } + + fn set_ghost_state(&mut self, ghost: bool) { + self.chat.ghost = ghost; + let Some(me) = self.user.as_ref() else { + return; + }; + if let Some(account) = self + .chat + .builder_users + .iter_mut() + .find(|account| account.user.id == me.id) + { + account.ghost = ghost; + } + } + + fn set_ghost(&self, enabled: bool, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.set_ghost(enabled).await { + Ok(()) => { + let _ = this.update(cx, |yumush, cx| { + yumush.set_ghost_state(enabled); + if enabled { + yumush.force_mute(cx); + } + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/builder/access.rs b/crates/client/src/gui/builder/access.rs new file mode 100644 index 0000000..d2a54b3 --- /dev/null +++ b/crates/client/src/gui/builder/access.rs @@ -0,0 +1,317 @@ +use common::model::{InviteCode, ServerBan, ServerBanKind}; +use gpui_kit::{ + AnyElement, ClipboardItem, Context, Div, Entity, FontWeight, IntoElement, ParentElement, + Styled, Window, assets::IconName, div, prelude::FluentBuilder as _, px, +}; + +use super::ui::{accent_button, card, card_header, icon_button, pill, toolbar}; +use crate::gui::STAMP; +use crate::gui::{Palette, Yumush, auth::field, entity_action, millis_time, notify_error, text}; + +fn list_card(header: Div, rows: Vec
, empty: &str, palette: Palette) -> Div { + let body = if rows.is_empty() { + div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child(empty.to_string()) + } else { + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) + }; + + card(palette).child(header).child(body) +} + +fn invite_row( + invite: &InviteCode, + pending: bool, + entity: &Entity, + palette: Palette, +) -> Div { + let copy_code = invite.code.clone(); + let delete_code = invite.code.clone(); + let expiry = invite.expires_at.map_or_else( + || "never".to_string(), + |at| format!("expires {}", millis_time(at, STAMP)), + ); + let (delete_icon, delete_tip, delete_color) = if pending { + (IconName::Check, "Confirm", palette.on_accent) + } else { + (IconName::Trash, "Delete", palette.danger) + }; + + div() + .min_h(px(44.)) + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .gap(px(10.)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .font_weight(FontWeight::MEDIUM) + .truncate() + .child(invite.code.clone()), + ) + .child( + div() + .text_size(text(11.)) + .text_color(palette.muted) + .truncate() + .child(format!( + "{} {} left · {expiry}", + invite.uses_left, + if invite.uses_left == 1 { "use" } else { "uses" } + )), + ), + ) + .child(icon_button( + format!("copy_invite_{}", invite.code), + IconName::Copy, + "Copy", + palette.muted, + palette, + entity_action(entity, move |yumush, _, cx| { + yumush.copy_invite(©_code, cx) + }), + )) + .child(icon_button( + format!("delete_invite_{}", invite.code), + delete_icon, + delete_tip, + delete_color, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_invite(&delete_code, window, cx) + }), + )) +} + +fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { + let remove_id = ban.id.clone(); + let kind = match ban.kind { + ServerBanKind::Ip => "IP", + ServerBanKind::Username => "Username", + }; + + div() + .min_h(px(44.)) + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .gap(px(10.)) + .child(pill(kind, palette.text, palette)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .font_weight(FontWeight::MEDIUM) + .truncate() + .child(ban.value.clone()), + ) + .children(ban.reason.as_ref().map(|reason| { + div() + .text_size(text(11.)) + .text_color(palette.muted) + .truncate() + .child(reason.clone()) + })), + ) + .child(icon_button( + format!("remove_ban_{}", ban.id), + IconName::X, + "Remove", + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.remove_ban(&remove_id, window, cx) + }), + )) +} + +impl Yumush { + pub(super) fn load_access(&self, window: &mut Window, cx: &mut Context) { + self.load_invites(window, cx); + self.load_server_bans(window, cx); + } + + pub(super) fn load_invites(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let codes = match network.invite_codes().await { + Ok(codes) => codes, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_invites = codes; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn load_server_bans(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let bans = match network.server_bans().await { + Ok(bans) => bans, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_bans = bans; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn create_invite(&mut self, window: &mut Window, cx: &mut Context) { + let uses = self.chat.invite_uses.read(cx).text().to_string(); + let Ok(uses) = uses.trim().parse::() else { + return; + }; + let hours = self.chat.invite_hours.read(cx).text().to_string(); + let hours = match hours.trim() { + "" => None, + text => match text.parse::() { + Ok(hours) => Some(hours), + Err(_) => return, + }, + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.create_invite_code(uses, hours).await { + Ok(_) => { + let _ = + this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn delete_invite( + &mut self, + code: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_invite_delete.as_deref() != Some(code) { + self.chat.pending_invite_delete = Some(code.to_string()); + cx.notify(); + return; + } + self.chat.pending_invite_delete = None; + let network = self.network.clone(); + let code = code.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_invite_code(&code).await { + Ok(()) => { + let _ = + this.update_in(cx, |yumush, window, cx| yumush.load_invites(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn copy_invite(&self, code: &str, cx: &mut Context) { + cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); + } + + pub(super) fn remove_ban(&mut self, id: &str, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + let id = id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.remove_server_ban(&id).await { + Ok(()) => { + let _ = this + .update_in(cx, |yumush, window, cx| yumush.load_server_bans(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn access_body(&self, entity: &Entity, palette: Palette) -> Vec { + let controls = toolbar(vec![ + div() + .w(px(80.)) + .child(field(palette, &self.chat.invite_uses)) + .into_any_element(), + div() + .w(px(90.)) + .child(field(palette, &self.chat.invite_hours)) + .into_any_element(), + accent_button( + "create_invite", + "Create", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.create_invite(window, cx) + }), + ) + .into_any_element(), + ]) + .into_any_element(); + let invite_header = card_header("Invite codes", vec![controls], palette); + let invites = self.chat.builder_invites.iter().map(|invite| { + let pending = self.chat.pending_invite_delete.as_deref() == Some(invite.code.as_str()); + invite_row(invite, pending, entity, palette) + }); + let bans = self + .chat + .builder_bans + .iter() + .map(|ban| ban_row(ban, entity, palette)); + let ban_header = card_header("Bans", Vec::new(), palette); + + vec![ + list_card(invite_header, invites.collect(), "No invite codes", palette) + .into_any_element(), + list_card(ban_header, bans.collect(), "No bans", palette).into_any_element(), + ] + } +} diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs new file mode 100644 index 0000000..6659a9e --- /dev/null +++ b/crates/client/src/gui/builder/communities.rs @@ -0,0 +1,474 @@ +use common::model::{Community, CommunitySummary, Member, Rank}; +use gpui_kit::{ + AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px, +}; + +use super::{ + Transfer, + ui::{card, icon_button, pill, plain_button}, +}; +use crate::gui::{ + Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text, + entity_action, notify_error, text, +}; + +fn rows_body(rows: Vec
, empty: &str, palette: Palette) -> Div { + if rows.is_empty() { + return div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child(empty.to_string()); + } + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) +} + +impl Yumush { + pub(super) fn set_builder_community_voice( + &mut self, + community_id: &str, + enabled: bool, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + let community_id = community_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.set_community_voice(&community_id, enabled).await { + Ok(_) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.load_builder_communities(window, cx) + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn load_builder_communities(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let summaries = match network.all_communities().await { + Ok(summaries) => summaries, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + for summary in &summaries { + if let Some(avatar_id) = &summary.community.avatar_id { + yumush.request_avatar(avatar_id, cx); + } + if let Some(owner) = &summary.owner { + yumush.request_user_avatar(owner, cx); + } + } + yumush.chat.builder_communities = summaries; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn delete_builder_community( + &mut self, + community_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_community_delete.as_deref() != Some(community_id) { + self.chat.pending_community_delete = Some(community_id.to_string()); + cx.notify(); + return; + } + self.chat.pending_community_delete = None; + let network = self.network.clone(); + let community_id = community_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_community(&community_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.remove_community(&community_id); + yumush.load_builder_communities(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn open_transfer( + &mut self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + if self + .chat + .transfer + .as_ref() + .is_some_and(|transfer| transfer.community_id == community_id) + { + self.chat.transfer = None; + cx.notify(); + return; + } + self.chat.transfer = Some(Transfer { + community_id: community_id.clone(), + members: Vec::new(), + pending: None, + }); + cx.notify(); + self.load_transfer_members(community_id, window, cx); + } + + pub(super) fn load_transfer_members( + &self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let members = match network.members(&community_id).await { + Ok(members) => members, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update_in(cx, |yumush, window, cx| { + for member in &members { + yumush.request_user_avatar(&member.user, cx); + } + let Some(transfer) = yumush.chat.transfer.as_mut() else { + return; + }; + if transfer.community_id == community_id { + transfer.members = members; + window.refresh(); + cx.notify(); + } + }); + }) + .detach(); + } + + pub(super) fn transfer_rows(&self, entity: &Entity, palette: Palette) -> Vec { + let Some(transfer) = &self.chat.transfer else { + return Vec::new(); + }; + + transfer + .members + .iter() + .filter(|member| member.rank != Rank::Owner) + .map(|member| { + let pending = transfer.pending.as_deref() == Some(member.user.id.as_str()); + self.transfer_row(member, pending, entity, palette) + .into_any_element() + }) + .collect() + } + + pub(super) fn transfer_to( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let Some(transfer) = self.chat.transfer.as_mut() else { + return; + }; + if transfer.pending.as_deref() != Some(user_id) { + transfer.pending = Some(user_id.to_string()); + window.refresh(); + cx.notify(); + return; + } + let community_id = transfer.community_id.clone(); + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.transfer_ownership(&community_id, &user_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.transfer = None; + yumush.load_builder_communities(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn open_builder_community( + &mut self, + community: Community, + window: &mut Window, + cx: &mut Context, + ) { + let community_id = community.id.clone(); + self.chat.opened = Some(community); + self.show_view(View::Chat, window, cx); + self.select_community(community_id, window, cx); + } + + pub(super) fn communities_body( + &self, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> Vec { + let query = search_text(&self.chat.builder_search, cx); + let rows: Vec
= self + .chat + .builder_communities + .iter() + .filter(|summary| { + summary + .community + .name + .to_lowercase() + .contains(query.as_str()) + }) + .map(|summary| self.community_row(summary, entity, palette)) + .collect(); + + vec![ + card(palette) + .child( + div() + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .border_b_1() + .border_color(palette.border) + .child( + div() + .w(px(240.)) + .child(Input::new(&self.chat.builder_search)), + ), + ) + .child(rows_body(rows, "No communities", palette)) + .into_any_element(), + ] + } + + pub(super) fn transfer_row( + &self, + member: &Member, + pending: bool, + entity: &Entity, + palette: Palette, + ) -> Div { + let user_id = member.user.id.clone(); + + div() + .h(px(40.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child(avatar( + palette, + &member.user, + px(20.), + text(10.), + &self.chat.avatars, + )) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .child(member.user.username.clone()), + ) + .child(plain_button( + format!("transfer_to_{}", member.user.id), + if pending { "Confirm" } else { "Transfer" }, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.transfer_to(&user_id, window, cx) + }), + )) + } + + pub(super) fn community_row( + &self, + summary: &CommunitySummary, + entity: &Entity, + palette: Palette, + ) -> Div { + let community = &summary.community; + let opened = community.clone(); + let id = community.id.clone(); + let log_id = id.clone(); + let transfer_id = id.clone(); + let delete_id = id.clone(); + let voice_id = id.clone(); + let voice_enabled = community.voice_enabled; + let pending_delete = self.chat.pending_community_delete.as_deref() == Some(id.as_str()); + let expanded = self + .chat + .transfer + .as_ref() + .is_some_and(|transfer| transfer.community_id == id); + let owner = summary.owner.as_ref().map_or(String::new(), |owner| { + format!(" · owner {}", owner.username) + }); + let meta = format!("{} members{owner}", summary.members); + + let row = div() + .min_h(px(48.)) + .px(px(14.)) + .py(px(8.)) + .flex() + .items_center() + .gap(px(10.)) + .child(community_icon( + palette, + community, + px(28.), + text(11.), + &self.chat.avatars, + )) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(text(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .truncate() + .child(community.name.clone()), + ) + .child( + div() + .text_size(text(11.)) + .text_color(palette.muted) + .truncate() + .child(meta), + ), + ) + .children((!voice_enabled).then(|| pill("Voice off", palette.muted, palette))) + .child(icon_button( + format!("open_community_{id}"), + IconName::ArrowUpRight, + "Open", + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.open_builder_community(opened.clone(), window, cx) + }), + )) + .child(icon_button( + format!("log_community_{id}"), + IconName::ScrollText, + "Log", + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.show_logs(log_id.clone(), window, cx) + }), + )) + .child(icon_button( + format!("voice_community_{id}"), + if voice_enabled { + IconName::Phone + } else { + IconName::PhoneOff + }, + if voice_enabled { + "Voice on" + } else { + "Voice off" + }, + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_builder_community_voice(&voice_id, !voice_enabled, window, cx) + }), + )) + .child(icon_button( + format!("transfer_community_{id}"), + IconName::ArrowRightLeft, + "Transfer", + if expanded { + palette.text + } else { + palette.muted + }, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.open_transfer(transfer_id.clone(), window, cx) + }), + )) + .child( + icon_button( + format!("delete_community_{id}"), + IconName::Trash, + if pending_delete { + "Confirm delete" + } else { + "Delete" + }, + if pending_delete { + palette.on_accent + } else { + palette.danger + }, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_builder_community(&delete_id, window, cx) + }), + ) + .when(pending_delete, |this| this.bg(palette.danger)), + ); + + div() + .flex() + .flex_col() + .child(row) + .children(expanded.then(|| { + div().px(px(14.)).pb(px(10.)).child( + div() + .flex() + .flex_col() + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .children(self.transfer_rows(entity, palette)), + ) + })) + } +} diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs new file mode 100644 index 0000000..676f993 --- /dev/null +++ b/crates/client/src/gui/builder/log.rs @@ -0,0 +1,322 @@ +use common::{ + model::{AdminAction, AdminLogEntry, action_detail, action_name}, + time::{created_at_ms, now_ms}, +}; +use gpui_kit::{ + AnyElement, App, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, + assets::IconName, + component::{Icon, WindowExt, input::InputState, notification::Notification, select::Select}, + div, + prelude::FluentBuilder as _, + px, +}; +use jiff::Timestamp; + +use super::ui::{accent_button, card, day_millis, list_row, pill, toolbar}; +use crate::gui::STAMP; +use crate::gui::{ + Palette, Yumush, + auth::field, + community_settings::{search_text, user_name}, + entity_action, id_time, millis_time, notify_error, text, +}; + +fn builder_log_text(entry: &AdminLogEntry) -> String { + let actor = user_name(&entry.actor); + let target = user_name(&entry.target); + let community = entry.community.as_deref().unwrap_or_default(); + + match &entry.action { + AdminAction::RoleChanged { role } => format!("{actor} set {target} to {}", role.as_str()), + AdminAction::UserDeleted => format!("{actor} deleted {target}"), + AdminAction::UserSuspended => format!("{actor} suspended {target}"), + AdminAction::UserUnsuspended => format!("{actor} unsuspended {target}"), + AdminAction::SessionsRevoked => format!("{actor} revoked sessions of {target}"), + AdminAction::PasswordReset => format!("{actor} reset password of {target}"), + AdminAction::ProfileCleared => format!("{actor} cleared profile of {target}"), + AdminAction::UserCreated => format!("{actor} created {target}"), + AdminAction::CommunityDeleted => format!("{actor} deleted {community}"), + AdminAction::OwnershipTransferred => { + format!("{actor} transferred {community} to {target}") + } + AdminAction::SettingsChanged => format!("{actor} changed settings"), + AdminAction::UserRenamed { from } => format!("{actor} renamed {from} to {target}"), + AdminAction::UserTimedOut { minutes: 0 } => format!("{actor} cleared timeout of {target}"), + AdminAction::UserTimedOut { minutes } => { + format!("{actor} timed out {target} for {minutes} min") + } + AdminAction::UserBanned { .. } => format!("{actor} banned {target}"), + AdminAction::BanRemoved => format!("{actor} removed a ban"), + AdminAction::InviteCreated => format!("{actor} created an invite code"), + AdminAction::InviteDeleted => format!("{actor} deleted an invite code"), + AdminAction::ReportHandled { status } => { + format!("{actor} marked a report of {target} as {}", status.as_str()) + } + AdminAction::MessageDeleted => { + format!("{actor} deleted a message of {target} in {community}") + } + AdminAction::UserPurged { messages } => { + format!("{actor} purged {target}, {messages} messages") + } + AdminAction::VoiceKicked => format!("{actor} kicked {target} from voice"), + AdminAction::VoiceMuted { muted: true } => format!("{actor} muted {target} in voice"), + AdminAction::VoiceMuted { muted: false } => format!("{actor} unmuted {target} in voice"), + AdminAction::CommunityVoiceSet { enabled: true } => { + format!("{actor} enabled voice in {community}") + } + AdminAction::CommunityVoiceSet { enabled: false } => { + format!("{actor} disabled voice in {community}") + } + AdminAction::AttachmentDeleted => { + format!("{actor} deleted an attachment of {target} in {community}") + } + AdminAction::GhostEnabled => format!("{actor} enabled ghost mode"), + AdminAction::GhostDisabled => format!("{actor} disabled ghost mode"), + AdminAction::GhostVisit => format!("{actor} visited {community} as ghost"), + AdminAction::GhostVoice { seconds } => { + format!("{actor} listened in {community} as ghost for {seconds}s") + } + } +} + +fn csv_field(text: &str) -> String { + format!("\"{}\"", text.replace('"', "\"\"")) +} + +fn builder_log_csv(entries: &[AdminLogEntry]) -> String { + let mut lines = vec!["time,actor,action,target,community,detail".to_string()]; + for entry in entries { + let time = created_at_ms(&entry.id) + .and_then(|millis| Timestamp::from_millisecond(millis as i64).ok()) + .map(|timestamp| timestamp.to_string()) + .unwrap_or_default(); + let actor = entry + .actor + .as_ref() + .map_or_else(String::new, |user| user.username.clone()); + let target = entry + .target + .as_ref() + .map_or_else(String::new, |user| user.username.clone()); + let fields = [ + time, + actor, + action_name(&entry.action).to_string(), + target, + entry.community.clone().unwrap_or_default(), + action_detail(&entry.action).unwrap_or_default(), + ]; + lines.push( + fields + .iter() + .map(|field| csv_field(field)) + .collect::>() + .join(","), + ); + } + + lines.join("\n") +} + +fn action_icon(action: &AdminAction) -> IconName { + match action { + AdminAction::UserDeleted + | AdminAction::CommunityDeleted + | AdminAction::MessageDeleted + | AdminAction::AttachmentDeleted + | AdminAction::UserPurged { .. } => IconName::Trash, + AdminAction::UserBanned { .. } + | AdminAction::BanRemoved + | AdminAction::UserSuspended + | AdminAction::UserUnsuspended + | AdminAction::UserTimedOut { .. } => IconName::Ban, + AdminAction::RoleChanged { .. } + | AdminAction::OwnershipTransferred + | AdminAction::UserRenamed { .. } + | AdminAction::ProfileCleared + | AdminAction::PasswordReset + | AdminAction::SessionsRevoked => IconName::UserCog, + AdminAction::UserCreated => IconName::UserPlus, + AdminAction::VoiceKicked | AdminAction::VoiceMuted { .. } => IconName::MicOff, + AdminAction::CommunityVoiceSet { .. } => IconName::Mic, + AdminAction::InviteCreated | AdminAction::InviteDeleted => IconName::Key, + AdminAction::ReportHandled { .. } => IconName::Flag, + AdminAction::SettingsChanged => IconName::Settings, + AdminAction::GhostEnabled + | AdminAction::GhostDisabled + | AdminAction::GhostVisit + | AdminAction::GhostVoice { .. } => IconName::Eye, + } +} + +fn fixed(width: f32, control: impl IntoElement) -> AnyElement { + div() + .w(px(width)) + .flex_shrink_0() + .child(control) + .into_any_element() +} + +fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { + list_row() + .child( + Icon::new(action_icon(&entry.action)) + .w(px(14.)) + .h(px(14.)) + .text_color(palette.muted), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .truncate() + .text_size(text(13.)) + .text_color(palette.text) + .child(builder_log_text(entry)), + ) + .child( + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child(id_time(&entry.id, STAMP)), + ), + ) + .children( + entry + .community + .as_deref() + .map(|community| pill(community, palette.accent, palette)), + ) +} + +impl Yumush { + pub(super) fn load_builder_logs(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let (Some(actor_id), Some(target_id)) = ( + self.log_user(&self.chat.builder_log_actor, cx), + self.log_user(&self.chat.builder_log_target, cx), + ) else { + window.push_notification(Notification::error("Unknown user"), cx); + return; + }; + let action = self + .chat + .builder_log_action + .read(cx) + .selected_value() + .copied() + .filter(|name| *name != "All") + .map(str::to_string); + let after_ms = day_millis(&search_text(&self.chat.builder_log_from, cx), false); + let before_ms = day_millis(&search_text(&self.chat.builder_log_to, cx), true); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let entries = match network + .admin_logs(actor_id, target_id, action, after_ms, before_ms) + .await + { + Ok(entries) => entries, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_logs = entries; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn log_user(&self, input: &Entity, cx: &App) -> Option> { + let name = search_text(input, cx); + if name.is_empty() { + return Some(None); + } + + self.resolve_user(&name).map(Some) + } + + pub(super) fn export_builder_log(&self, window: &mut Window, cx: &mut Context) { + let Some(directory) = dirs::download_dir() else { + window.push_notification(Notification::error("No download folder"), cx); + return; + }; + let name = format!( + "yumush-admin-log-{}.csv", + millis_time(now_ms(), "%Y%m%d-%H%M%S") + ); + let path = directory.join(name); + match std::fs::write(&path, builder_log_csv(&self.chat.builder_logs)) { + Ok(()) => { + window.push_notification(Notification::success(path.display().to_string()), cx) + } + Err(error) => window.push_notification(Notification::error(error.to_string()), cx), + } + } + + pub(super) fn log_body(&self, entity: &Entity, palette: Palette) -> Vec { + let filters = toolbar(vec![ + fixed(130., field(palette, &self.chat.builder_log_actor)), + fixed(130., field(palette, &self.chat.builder_log_target)), + fixed(160., Select::new(&self.chat.builder_log_action)), + fixed(150., field(palette, &self.chat.builder_log_from)), + fixed(150., field(palette, &self.chat.builder_log_to)), + accent_button( + "apply_builder_log", + "Apply", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.load_builder_logs(window, cx) + }), + ) + .into_any_element(), + ]); + let rows: Vec
= self + .chat + .builder_logs + .iter() + .enumerate() + .map(|(index, entry)| { + builder_log_row(entry, palette).when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + }) + .collect(); + let body = if rows.is_empty() { + div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child("No entries") + } else { + div().flex().flex_col().children(rows) + }; + + vec![ + card(palette) + .child( + div() + .px(px(14.)) + .py(px(10.)) + .border_b_1() + .border_color(palette.border) + .child(filters), + ) + .child(body) + .into_any_element(), + ] + } +} diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs new file mode 100644 index 0000000..344d34c --- /dev/null +++ b/crates/client/src/gui/builder/messages.rs @@ -0,0 +1,250 @@ +use common::model::MessageHit; +use gpui_kit::{ + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + assets::IconName, div, prelude::FluentBuilder as _, px, +}; + +use super::ui::{accent_button, card, day_millis, icon_button, list_card, list_row}; +use crate::gui::YEAR_STAMP; +use crate::gui::{ + Palette, Yumush, + auth::field, + avatar, + community_settings::{search_text, user_name}, + entity_action, id_time, notify_error, text, +}; + +fn fixed(width: f32, control: impl IntoElement) -> Div { + div().w(px(width)).flex_shrink_0().child(control) +} + +fn message_hit_row( + hit: &MessageHit, + pending: bool, + purge_pending: bool, + picture: Div, + entity: &Entity, + palette: Palette, +) -> Div { + let message_id = hit.message.id.clone(); + let delete = icon_button( + format!("delete_message_{}", hit.message.id), + IconName::Trash, + if pending { "Confirm" } else { "Delete" }, + palette.danger, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_builder_message(&message_id, window, cx) + }), + ) + .when(pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }); + let purge = hit.author.as_ref().map(|author| { + let user_id = author.id.clone(); + icon_button( + format!("purge_message_user_{}", author.id), + IconName::UserX, + if purge_pending { + "Confirm purge" + } else { + "Purge user" + }, + palette.danger, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.purge_builder_user(&user_id, window, cx) + }), + ) + .when(purge_pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) + }); + + list_row() + .child(picture) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .min_w_0() + .child( + div() + .min_w_0() + .truncate() + .text_size(text(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .child(user_name(&hit.author).to_string()), + ) + .child( + div() + .min_w_0() + .truncate() + .text_size(text(11.)) + .text_color(palette.muted) + .child(hit.community.clone()), + ) + .child( + div() + .flex_shrink_0() + .text_size(text(11.)) + .text_color(palette.muted) + .child(id_time(&hit.message.id, YEAR_STAMP)), + ), + ) + .child( + div() + .text_size(text(13.)) + .text_color(palette.body) + .line_clamp(2) + .child(hit.message.body.clone()), + ), + ) + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .flex_shrink_0() + .child(delete) + .children(purge), + ) +} + +impl Yumush { + pub(super) fn messages_body(&self, entity: &Entity, palette: Palette) -> Vec { + let filters = div() + .px(px(14.)) + .py(px(12.)) + .flex() + .flex_col() + .gap(px(8.)) + .child( + div().flex().child( + div() + .flex_1() + .min_w_0() + .child(field(palette, &self.chat.builder_message_text)), + ), + ) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(fixed(180., field(palette, &self.chat.builder_message_user))) + .child(fixed( + 180., + field(palette, &self.chat.builder_message_community), + )) + .child(fixed(150., field(palette, &self.chat.builder_message_from))) + .child(fixed(150., field(palette, &self.chat.builder_message_to))) + .child(accent_button( + "search_messages", + "Search", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.search_messages(window, cx) + }), + )), + ); + let rows: Vec
= self + .chat + .builder_messages + .iter() + .map(|hit| { + let pending = + self.chat.pending_message_delete.as_deref() == Some(hit.message.id.as_str()); + let purge_pending = hit.author.as_ref().is_some_and(|author| { + self.chat.pending_builder_purge.as_deref() == Some(author.id.as_str()) + }); + let picture = match &hit.author { + Some(author) => avatar(palette, author, px(28.), text(11.), &self.chat.avatars), + None => div() + .size(px(28.)) + .flex_shrink_0() + .rounded_full() + .bg(palette.hover), + }; + message_hit_row(hit, pending, purge_pending, picture, entity, palette) + }) + .collect(); + + vec![ + card(palette).child(filters).into_any_element(), + list_card(None, rows, "No messages", palette).into_any_element(), + ] + } + + pub(super) fn search_messages(&mut self, window: &mut Window, cx: &mut Context) { + let text = search_text(&self.chat.builder_message_text, cx); + let username = search_text(&self.chat.builder_message_user, cx); + let community = search_text(&self.chat.builder_message_community, cx); + let user_id = self.resolve_user(&username); + let community_id = self.resolve_community(&community); + let after_ms = day_millis(&search_text(&self.chat.builder_message_from, cx), false); + let before_ms = day_millis(&search_text(&self.chat.builder_message_to, cx), true); + let text = (!text.is_empty()).then_some(text); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let hits = match network + .search_messages(text, user_id, community_id, after_ms, before_ms) + .await + { + Ok(hits) => hits, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_messages = hits; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn delete_builder_message( + &mut self, + message_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_message_delete.as_deref() != Some(message_id) { + self.chat.pending_message_delete = Some(message_id.to_string()); + cx.notify(); + return; + } + self.chat.pending_message_delete = None; + let network = self.network.clone(); + let message_id = message_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_message(&message_id).await { + Ok(()) => { + let _ = this.update(cx, |yumush, cx| { + yumush + .chat + .builder_messages + .retain(|hit| hit.message.id != message_id); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/builder/overview.rs b/crates/client/src/gui/builder/overview.rs new file mode 100644 index 0000000..b3d6191 --- /dev/null +++ b/crates/client/src/gui/builder/overview.rs @@ -0,0 +1,176 @@ +use common::{error::Error, model::DayStat, time::DAY_MILLIS}; +use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px}; +use jiff::Timestamp; + +use super::ui::{card, card_header, stat_tile}; +use crate::gui::{DAY, Palette, Yumush, notify_error, storage, text}; + +const CHART_HEIGHT: f32 = 80.; + +fn day_label(day: u64) -> String { + Timestamp::from_millisecond((day * DAY_MILLIS) as i64) + .map(|timestamp| timestamp.strftime(DAY).to_string()) + .unwrap_or_default() +} + +fn tile_row(tiles: &[(&str, String)], palette: Palette) -> Div { + div().flex().gap(px(12.)).children( + tiles + .iter() + .map(|(label, value)| stat_tile(label, value, palette).flex_1().min_w(px(200.))), + ) +} + +fn bar_chart( + title: &'static str, + stats: &[DayStat], + value: fn(&DayStat) -> u64, + summary: u64, + palette: Palette, +) -> Div { + let values: Vec = stats.iter().map(value).collect(); + let maximum = values.iter().copied().max().unwrap_or_default(); + let first = stats + .first() + .map(|stat| day_label(stat.day)) + .unwrap_or_default(); + let last = stats + .last() + .map(|stat| day_label(stat.day)) + .unwrap_or_default(); + + card(palette) + .flex_1() + .min_w_0() + .child(card_header( + title, + vec![ + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child(summary.to_string()) + .into_any_element(), + ], + palette, + )) + .child( + div() + .h(px(140.)) + .px(px(14.)) + .py(px(12.)) + .flex() + .flex_col() + .gap(px(4.)) + .child( + div() + .text_size(text(10.)) + .text_color(palette.muted) + .child(maximum.to_string()), + ) + .child( + div() + .h(px(CHART_HEIGHT)) + .flex() + .items_end() + .gap(px(2.)) + .children(values.iter().map(|&value| { + let (height, color) = if value == 0 { + (2., palette.hover) + } else { + ( + (CHART_HEIGHT * value as f32 / maximum as f32).max(2.), + palette.accent.opacity(0.85), + ) + }; + + div().flex_1().h(px(height)).rounded_t(px(2.)).bg(color) + })), + ) + .child( + div() + .pt(px(4.)) + .border_t_1() + .border_color(palette.border) + .flex() + .justify_between() + .text_size(text(11.)) + .text_color(palette.muted) + .child(first) + .child(last), + ), + ) +} + +impl Yumush { + pub(super) fn load_overview(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let loaded = async { + Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?)) + } + .await; + let (overview, stats) = match loaded { + Ok(loaded) => loaded, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_overview = Some(overview); + yumush.chat.builder_stats = stats; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn overview_rows(&self, palette: Palette) -> Vec
{ + let Some(overview) = &self.chat.builder_overview else { + return Vec::new(); + }; + let stats = &self.chat.builder_stats; + let active = stats.last().map_or(0, |stat| stat.active_users); + let messages = stats.iter().map(|stat| stat.messages).sum::(); + + let tiles = [ + ("Users", overview.users.to_string()), + ("Builders", overview.builders.to_string()), + ("Communities", overview.communities.to_string()), + ("Online", overview.online.to_string()), + ("In voice", overview.voice.to_string()), + ("Storage", storage(overview.storage_bytes)), + ]; + + let mut rows: Vec
= tiles + .chunks(3) + .map(|chunk| tile_row(chunk, palette)) + .collect(); + rows.push( + div() + .flex() + .gap(px(12.)) + .child(bar_chart( + "Active users", + stats, + |stat| stat.active_users, + active, + palette, + )) + .child(bar_chart( + "Messages", + stats, + |stat| stat.messages, + messages, + palette, + )), + ); + + rows + } +} diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs new file mode 100644 index 0000000..377a380 --- /dev/null +++ b/crates/client/src/gui/builder/reports.rs @@ -0,0 +1,393 @@ +use std::future::Future; + +use common::{ + error::Error, + model::{Report, ReportStatus}, +}; +use gpui_kit::{ + AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, + div, px, +}; + +use super::ui::{danger_button, list_card, pill, plain_button}; +use crate::gui::STAMP; +use crate::{ + gui::{ + Palette, Yumush, avatar, badge, clickable, + community_settings::user_name, + entity_action, id_time, notify_error, + settings_page::{segment, segment_track}, + text, + }, + network::NetworkHandle, +}; + +const REPORT_FILTERS: [(Option, &str); 4] = [ + (Some(ReportStatus::Open), "Open"), + (Some(ReportStatus::Resolved), "Resolved"), + (Some(ReportStatus::Dismissed), "Dismissed"), + (None, "All"), +]; + +fn status_label(status: ReportStatus) -> &'static str { + match status { + ReportStatus::Open => "Open", + ReportStatus::Resolved => "Resolved", + ReportStatus::Dismissed => "Dismissed", + } +} + +fn status_color(status: ReportStatus, palette: Palette) -> Hsla { + match status { + ReportStatus::Open => palette.accent, + ReportStatus::Resolved => palette.ok, + ReportStatus::Dismissed => palette.muted, + } +} + +impl Yumush { + pub(super) fn load_open_reports(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let count = match network.reports(Some(ReportStatus::Open)).await { + Ok(reports) => reports.len(), + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.open_reports = count; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn load_reports(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let status = self.chat.report_filter; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let reports = match network.reports(status).await { + Ok(reports) => reports, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_reports = reports; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn refresh_reports(&self, window: &mut Window, cx: &mut Context) { + self.load_reports(window, cx); + self.load_open_reports(window, cx); + } + + pub(super) fn select_report_filter( + &mut self, + status: Option, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.report_filter = status; + self.load_reports(window, cx); + cx.notify(); + } + + pub(super) fn report_action( + &mut self, + window: &mut Window, + cx: &mut Context, + action: impl FnOnce(NetworkHandle) -> Fut + 'static, + ) where + Fut: Future> + 'static, + { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| match action(network).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| yumush.refresh_reports(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + }) + .detach(); + } + + pub(super) fn handle_report( + &mut self, + report_id: &str, + status: ReportStatus, + window: &mut Window, + cx: &mut Context, + ) { + let report_id = report_id.to_string(); + self.report_action(window, cx, move |network| async move { + network.handle_report(&report_id, status).await + }); + } + + pub(super) fn delete_report_message( + &mut self, + message_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let message_id = message_id.to_string(); + self.report_action(window, cx, move |network| async move { + network.delete_message(&message_id).await + }); + } + + pub(super) fn timeout_report_target( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + self.report_action(window, cx, move |network| async move { + network.timeout_user(&user_id, 60).await + }); + } + + pub(super) fn ban_report_target( + &mut self, + user_id: &str, + reason: &str, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + let reason = reason.to_string(); + self.report_action(window, cx, move |network| async move { + network + .ban_user(&user_id, Some(reason.as_str()), false) + .await + }); + } + + pub(super) fn report_filters(&self, entity: &Entity, palette: Palette) -> Div { + div() + .flex() + .child( + segment_track(palette).children(REPORT_FILTERS.map(|(status, label)| { + segment( + clickable( + label, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.select_report_filter(status, window, cx) + }), + ), + self.chat.report_filter == status, + palette, + ) + .px(px(10.)) + .child(label) + })), + ) + } + + pub(super) fn reports_body(&self, entity: &Entity, palette: Palette) -> Vec { + let rows: Vec
= self + .chat + .builder_reports + .iter() + .map(|report| self.report_row(report, entity, palette)) + .collect(); + + vec![ + self.report_filters(entity, palette).into_any_element(), + list_card(None, rows, "No reports", palette).into_any_element(), + ] + } + + pub(super) fn report_row( + &self, + report: &Report, + entity: &Entity, + palette: Palette, + ) -> Div { + let target_avatar = match &report.target { + Some(user) => { + avatar(palette, user, px(20.), text(9.), &self.chat.avatars).into_any_element() + } + None => badge(palette, &report.id, "someone", px(20.), text(9.)).into_any_element(), + }; + let head = div() + .flex_1() + .min_w_0() + .flex() + .items_center() + .gap(px(8.)) + .child(target_avatar) + .child( + div() + .font_weight(FontWeight::MEDIUM) + .truncate() + .child(user_name(&report.target).to_string()), + ) + .child(pill( + status_label(report.status), + status_color(report.status, palette), + palette, + )) + .child( + div() + .min_w_0() + .text_size(text(11.)) + .text_color(palette.muted) + .truncate() + .child(format!("reported by {}", user_name(&report.reporter))), + ); + let meta = div() + .flex_shrink_0() + .text_size(text(11.)) + .text_color(palette.muted) + .child(format!( + "{} · {}", + report.community.as_deref().unwrap_or("deleted community"), + id_time(&report.id, STAMP) + )); + let actions = self.report_actions(report, entity, palette); + let handled = (report.status != ReportStatus::Open).then(|| { + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child(format!("by {}", user_name(&report.handled_by))) + }); + + div() + .px(px(14.)) + .py(px(10.)) + .flex() + .flex_col() + .gap(px(6.)) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(head) + .child(meta), + ) + .child( + div() + .text_size(text(13.)) + .text_color(palette.body) + .child(report.reason.clone()), + ) + .children(report.body.as_ref().map(|body| { + div() + .px(px(8.)) + .py(px(6.)) + .rounded(px(6.)) + .bg(palette.window) + .text_size(text(12.)) + .text_color(palette.muted) + .line_clamp(2) + .child(body.clone()) + })) + .children(handled) + .children((!actions.is_empty()).then(|| { + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(4.)) + .children(actions) + })) + } + + pub(super) fn report_actions( + &self, + report: &Report, + entity: &Entity, + palette: Palette, + ) -> Vec { + if report.status != ReportStatus::Open { + return Vec::new(); + } + let resolve_id = report.id.clone(); + let dismiss_id = report.id.clone(); + let mut buttons = vec![ + plain_button( + format!("resolve_report_{}", report.id), + "Resolve", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.handle_report(&resolve_id, ReportStatus::Resolved, window, cx) + }), + ) + .into_any_element(), + plain_button( + format!("dismiss_report_{}", report.id), + "Dismiss", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.handle_report(&dismiss_id, ReportStatus::Dismissed, window, cx) + }), + ) + .into_any_element(), + ]; + if let (Some(message_id), Some(_)) = (&report.message_id, &report.community_id) { + let message_id = message_id.clone(); + buttons.push( + plain_button( + format!("delete_report_message_{}", report.id), + "Delete message", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_report_message(&message_id, window, cx) + }), + ) + .into_any_element(), + ); + } + if let Some(target) = &report.target { + let timeout_id = target.id.clone(); + let ban_id = target.id.clone(); + let ban_reason = report.reason.clone(); + buttons.push( + plain_button( + format!("timeout_report_{}", report.id), + "Timeout 1h", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.timeout_report_target(&timeout_id, window, cx) + }), + ) + .into_any_element(), + ); + buttons.push( + danger_button( + format!("ban_report_{}", report.id), + "Ban", + false, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.ban_report_target(&ban_id, &ban_reason, window, cx) + }), + ) + .into_any_element(), + ); + } + + buttons + } +} diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs new file mode 100644 index 0000000..6c3d498 --- /dev/null +++ b/crates/client/src/gui/builder/server.rs @@ -0,0 +1,288 @@ +use common::model::ServerSettings; +use gpui_kit::{AnyElement, Context, Entity, IntoElement, Window}; + +use super::ui::{ + field_row, kilobytes_bytes, kilobytes_text, list_card, megabytes_bytes, megabytes_text, number, +}; +use crate::gui::{Palette, Yumush, auth::field, notify_error, settings_page::segmented}; + +impl Yumush { + pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context) { + let Some(settings) = self.server.clone() else { + return; + }; + self.chat.server_registration_open = settings.registration_open; + self.chat.server_maintenance = settings.maintenance; + self.chat.server_name.update(cx, |input, cx| { + input.set_value(settings.name.as_str(), window, cx) + }); + self.chat.server_limit.update(cx, |input, cx| { + input.set_value( + megabytes_text(settings.max_attachment_bytes).as_str(), + window, + cx, + ) + }); + self.chat.server_user_quota.update(cx, |input, cx| { + input.set_value( + megabytes_text(settings.user_quota_bytes).as_str(), + window, + cx, + ) + }); + self.chat.server_community_quota.update(cx, |input, cx| { + input.set_value( + megabytes_text(settings.community_quota_bytes).as_str(), + window, + cx, + ) + }); + self.chat.server_message_retention.update(cx, |input, cx| { + input.set_value( + settings.message_retention_days.to_string().as_str(), + window, + cx, + ) + }); + self.chat + .server_attachment_retention + .update(cx, |input, cx| { + input.set_value( + settings.attachment_retention_days.to_string().as_str(), + window, + cx, + ) + }); + self.chat.server_announcement.update(cx, |input, cx| { + input.set_value(settings.announcement.as_str(), window, cx) + }); + self.chat.server_max_communities.update(cx, |input, cx| { + input.set_value( + settings.max_communities_per_user.to_string().as_str(), + window, + cx, + ) + }); + self.chat.server_max_message_length.update(cx, |input, cx| { + input.set_value(settings.max_message_length.to_string().as_str(), window, cx) + }); + self.chat.server_max_avatar.update(cx, |input, cx| { + input.set_value( + kilobytes_text(settings.max_avatar_bytes).as_str(), + window, + cx, + ) + }); + self.chat + .server_messages_per_minute + .update(cx, |input, cx| { + input.set_value( + settings.messages_per_minute.to_string().as_str(), + window, + cx, + ) + }); + self.chat.server_logins_per_minute.update(cx, |input, cx| { + input.set_value(settings.logins_per_minute.to_string().as_str(), window, cx) + }); + } + + pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context) { + let name = self.chat.server_name.read(cx).text().to_string(); + let max_attachment_bytes = + megabytes_bytes(&self.chat.server_limit.read(cx).text().to_string()); + let user_quota_bytes = + megabytes_bytes(&self.chat.server_user_quota.read(cx).text().to_string()); + let community_quota_bytes = + megabytes_bytes(&self.chat.server_community_quota.read(cx).text().to_string()); + let message_retention_days = number( + &self + .chat + .server_message_retention + .read(cx) + .text() + .to_string(), + ); + let attachment_retention_days = number( + &self + .chat + .server_attachment_retention + .read(cx) + .text() + .to_string(), + ); + let announcement = self.chat.server_announcement.read(cx).text().to_string(); + let max_communities_per_user = + number(&self.chat.server_max_communities.read(cx).text().to_string()); + let max_message_length = number( + &self + .chat + .server_max_message_length + .read(cx) + .text() + .to_string(), + ); + let max_avatar_bytes = + kilobytes_bytes(&self.chat.server_max_avatar.read(cx).text().to_string()); + let messages_per_minute = number( + &self + .chat + .server_messages_per_minute + .read(cx) + .text() + .to_string(), + ); + let logins_per_minute = number( + &self + .chat + .server_logins_per_minute + .read(cx) + .text() + .to_string(), + ); + let settings = ServerSettings { + name, + registration_open: self.chat.server_registration_open, + max_attachment_bytes, + maintenance: self.chat.server_maintenance, + user_quota_bytes, + community_quota_bytes, + message_retention_days, + attachment_retention_days, + announcement, + max_communities_per_user, + max_message_length, + max_avatar_bytes, + messages_per_minute, + logins_per_minute, + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.update_server_settings(settings).await { + Ok(settings) => { + let _ = this.update(cx, |yumush, cx| { + yumush.server = Some(settings); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn server_body(&self, entity: &Entity, palette: Palette) -> Vec { + let general = vec![ + field_row( + "Name", + None, + field(palette, &self.chat.server_name), + palette, + ), + field_row( + "Registration", + None, + segmented( + [(true, "Open"), (false, "Closed")], + self.chat.server_registration_open, + entity, + palette, + |yumush, open, _| yumush.chat.server_registration_open = open, + ), + palette, + ), + field_row( + "Maintenance", + None, + segmented( + [(false, "Off"), (true, "On")], + self.chat.server_maintenance, + entity, + palette, + |yumush, on, _| yumush.chat.server_maintenance = on, + ), + palette, + ), + field_row( + "Announcement", + None, + field(palette, &self.chat.server_announcement), + palette, + ), + ]; + let limits = vec![ + field_row( + "Max attachment (MB)", + None, + field(palette, &self.chat.server_limit), + palette, + ), + field_row( + "Max avatar (KB)", + None, + field(palette, &self.chat.server_max_avatar), + palette, + ), + field_row( + "Max message length", + None, + field(palette, &self.chat.server_max_message_length), + palette, + ), + field_row( + "Communities per user", + Some("0 = unlimited"), + field(palette, &self.chat.server_max_communities), + palette, + ), + ]; + let storage = vec![ + field_row( + "User quota (MB)", + Some("0 = unlimited"), + field(palette, &self.chat.server_user_quota), + palette, + ), + field_row( + "Community quota (MB)", + Some("0 = unlimited"), + field(palette, &self.chat.server_community_quota), + palette, + ), + field_row( + "Message retention (days)", + Some("0 = off"), + field(palette, &self.chat.server_message_retention), + palette, + ), + field_row( + "Attachment retention (days)", + Some("0 = off"), + field(palette, &self.chat.server_attachment_retention), + palette, + ), + ]; + let rate = vec![ + field_row( + "Messages / min", + Some("0 = off"), + field(palette, &self.chat.server_messages_per_minute), + palette, + ), + field_row( + "Logins / min", + Some("0 = off"), + field(palette, &self.chat.server_logins_per_minute), + palette, + ), + ]; + + vec![ + list_card(Some("General"), general, "", palette).into_any_element(), + list_card(Some("Limits"), limits, "", palette).into_any_element(), + list_card(Some("Storage"), storage, "", palette).into_any_element(), + list_card(Some("Rate limits"), rate, "", palette).into_any_element(), + ] + } +} diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs new file mode 100644 index 0000000..97d68b5 --- /dev/null +++ b/crates/client/src/gui/builder/storage.rs @@ -0,0 +1,338 @@ +use common::model::AttachmentInfo; +use gpui_kit::{ + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative, +}; + +use super::ui::{accent_button, card, card_header, list_card, list_row, toolbar}; +use crate::gui::{ + DATE, Palette, Tooltip, Yumush, + auth::field, + clickable, + community_settings::{search_text, user_name}, + entity_action, id_time, notify_error, storage, text, +}; + +fn fixed(width: f32, control: impl IntoElement) -> Div { + div().w(px(width)).flex_shrink_0().child(control) +} + +fn share(bytes: u64, max: u64) -> f32 { + if max == 0 { + 0. + } else { + bytes as f32 / max as f32 + } +} + +fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, palette: Palette) -> Div { + div() + .px(px(14.)) + .py(px(8.)) + .flex() + .flex_col() + .gap(px(6.)) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(text(13.)) + .text_color(palette.text) + .child(name.to_string()), + ) + .child( + div() + .flex_shrink_0() + .text_size(text(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .child(storage(bytes)), + ) + .child( + div() + .w(px(48.)) + .flex_shrink_0() + .flex() + .justify_end() + .text_size(text(11.)) + .text_color(palette.muted) + .child(count.to_string()), + ), + ) + .child( + div().h(px(3.)).rounded(px(3.)).bg(palette.hover).child( + div() + .h_full() + .w(relative(fraction)) + .rounded(px(3.)) + .bg(palette.accent), + ), + ) +} + +fn attachment_row( + info: &AttachmentInfo, + pending: bool, + entity: &Entity, + palette: Palette, +) -> Div { + let attachment_id = info.attachment.id.clone(); + let delete = clickable( + format!("delete_attachment_{}", info.attachment.id), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_builder_attachment(&attachment_id, window, cx) + }), + ) + .tip(if pending { "Confirm" } else { "Delete" }) + .size(px(26.)) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.danger) + .when(pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) + .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.))); + + list_row() + .child( + Icon::new(IconName::File) + .w(px(16.)) + .h(px(16.)) + .flex_shrink_0() + .text_color(palette.muted), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .truncate() + .text_size(text(13.)) + .text_color(palette.text) + .child(info.attachment.name.clone()), + ) + .child( + div() + .truncate() + .text_size(text(11.)) + .text_color(palette.muted) + .child(format!( + "{} · {} · {}", + user_name(&info.uploader), + info.community, + id_time(&info.attachment.id, DATE) + )), + ), + ) + .child( + div() + .flex_shrink_0() + .text_size(text(12.)) + .text_color(palette.muted) + .child(storage(info.attachment.size)), + ) + .child(delete) +} + +impl Yumush { + pub(super) fn storage_body(&self, entity: &Entity, palette: Palette) -> Vec { + let user_max = self + .chat + .builder_usage_users + .iter() + .map(|usage| usage.bytes) + .max() + .unwrap_or(0); + let community_max = self + .chat + .builder_usage_communities + .iter() + .map(|usage| usage.bytes) + .max() + .unwrap_or(0); + let users: Vec
= self + .chat + .builder_usage_users + .iter() + .map(|usage| { + usage_row( + &usage.user.username, + usage.bytes, + usage.count, + share(usage.bytes, user_max), + palette, + ) + }) + .collect(); + let communities: Vec
= self + .chat + .builder_usage_communities + .iter() + .map(|usage| { + usage_row( + &usage.community, + usage.bytes, + usage.count, + share(usage.bytes, community_max), + palette, + ) + }) + .collect(); + let usage = + div() + .flex() + .gap(px(20.)) + .child( + div() + .flex_1() + .min_w_0() + .child(list_card(Some("Users"), users, "No data", palette).h_full()), + ) + .child(div().flex_1().min_w_0().child( + list_card(Some("Communities"), communities, "No data", palette).h_full(), + )); + + let controls = toolbar(vec![ + fixed(160., field(palette, &self.chat.builder_attachment_user)).into_any_element(), + fixed( + 160., + field(palette, &self.chat.builder_attachment_community), + ) + .into_any_element(), + accent_button( + "search_attachments", + "Search", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.search_attachments(window, cx) + }), + ) + .into_any_element(), + ]) + .into_any_element(); + let rows: Vec
= self + .chat + .builder_attachments + .iter() + .map(|info| { + let pending = self.chat.pending_attachment_delete.as_deref() + == Some(info.attachment.id.as_str()); + attachment_row(info, pending, entity, palette) + }) + .collect(); + let body = if rows.is_empty() { + div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child("No attachments") + } else { + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) + }; + let attachments = card(palette) + .child(card_header("Attachments", vec![controls], palette)) + .child(body); + + vec![usage.into_any_element(), attachments.into_any_element()] + } + + pub(super) fn load_storage(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + self.search_attachments(window, cx); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let (users, communities) = match network.storage_usage().await { + Ok(usage) => usage, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_usage_users = users; + yumush.chat.builder_usage_communities = communities; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context) { + let username = search_text(&self.chat.builder_attachment_user, cx); + let community = search_text(&self.chat.builder_attachment_community, cx); + let user_id = self.resolve_user(&username); + let community_id = self.resolve_community(&community); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let attachments = match network.attachments(user_id, community_id).await { + Ok(attachments) => attachments, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_attachments = attachments; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn delete_builder_attachment( + &mut self, + attachment_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_attachment_delete.as_deref() != Some(attachment_id) { + self.chat.pending_attachment_delete = Some(attachment_id.to_string()); + cx.notify(); + return; + } + self.chat.pending_attachment_delete = None; + let network = self.network.clone(); + let attachment_id = attachment_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_attachment(&attachment_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.load_storage(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs new file mode 100644 index 0000000..ac57e8a --- /dev/null +++ b/crates/client/src/gui/builder/ui.rs @@ -0,0 +1,280 @@ +use crate::gui::{KB, MB, Palette, Tooltip as _, clickable, primary_button, text}; +use gpui_kit::{ + AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window, + assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, +}; +use jiff::{civil::Date, tz::TimeZone}; + +pub(super) fn megabytes_bytes(text: &str) -> u64 { + text.trim() + .parse::() + .ok() + .and_then(|megabytes| megabytes.checked_mul(MB as u64)) + .unwrap_or(0) +} + +pub(super) fn kilobytes_bytes(text: &str) -> u64 { + text.trim() + .parse::() + .ok() + .and_then(|kilobytes| kilobytes.checked_mul(KB as u64)) + .unwrap_or(0) +} + +pub(super) fn megabytes_text(bytes: u64) -> String { + (bytes / MB as u64).to_string() +} + +pub(super) fn kilobytes_text(bytes: u64) -> String { + (bytes / KB as u64).to_string() +} + +pub(super) fn number(text: &str) -> u32 { + text.trim().parse().unwrap_or(0) +} + +pub(super) fn icon_button( + id: String, + icon: IconName, + tip: &'static str, + color: Hsla, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + clickable(id, palette, action) + .tip(tip) + .size(px(26.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(color) + .child(Icon::new(icon).w(px(14.)).h(px(14.))) +} + +pub(super) fn danger_button( + id: String, + label: &'static str, + pending: bool, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> impl IntoElement { + clickable(id, palette, action) + .h(px(28.)) + .px(px(12.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_size(text(12.)) + .font_weight(FontWeight::MEDIUM) + .border_1() + .border_color(palette.danger.opacity(0.5)) + .text_color(palette.danger) + .when(pending, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) + .child(if pending { "Confirm" } else { label }) +} + +pub(super) fn day_millis(text: &str, end_of_day: bool) -> Option { + let date: Date = text.parse().ok()?; + let date = if end_of_day { + date.tomorrow().ok()? + } else { + date + }; + let millis = date + .to_zoned_datetime(TimeZone::system()) + .ok()? + .timestamp() + .as_millisecond(); + + u64::try_from(millis - i64::from(end_of_day)).ok() +} + +pub(super) fn accent_button( + id: &'static str, + label: &'static str, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> impl IntoElement { + primary_button(id, palette, action) + .h(px(28.)) + .px(px(12.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_size(text(12.)) + .font_weight(FontWeight::MEDIUM) + .child(label) +} + +pub(super) fn plain_button( + id: String, + label: &'static str, + palette: Palette, + action: impl Fn(&mut Window, &mut App) + 'static, +) -> impl IntoElement { + clickable(id, palette, action) + .h(px(28.)) + .px(px(12.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_size(text(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.muted) + .child(label) +} + +pub(super) fn card(palette: Palette) -> Div { + div() + .flex() + .flex_col() + .rounded(px(10.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .overflow_hidden() +} + +pub(super) fn card_header(title: &str, actions: Vec, palette: Palette) -> Div { + div() + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .border_b_1() + .border_color(palette.border) + .child( + div() + .text_size(text(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .child(title.to_string()), + ) + .children(actions) +} + +pub(super) fn list_card(title: Option<&str>, rows: Vec
, empty: &str, palette: Palette) -> Div { + let body = if rows.is_empty() { + div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child(empty.to_string()) + } else { + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) + }; + + card(palette) + .children(title.map(|title| card_header(title, Vec::new(), palette))) + .child(body) +} + +pub(super) fn list_row() -> Div { + div() + .min_h(px(44.)) + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .gap(px(10.)) +} + +pub(super) fn toolbar(items: Vec) -> Div { + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .children(items) +} + +pub(super) fn stat_tile(label: &str, value: &str, palette: Palette) -> Div { + card(palette) + .p(px(14.)) + .gap(px(4.)) + .child( + div() + .text_size(text(22.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text) + .child(value.to_string()), + ) + .child( + div() + .text_size(text(12.)) + .text_color(palette.muted) + .child(label.to_string()), + ) +} + +pub(super) fn field_row( + label: &str, + hint: Option<&str>, + control: impl IntoElement, + palette: Palette, +) -> Div { + list_row() + .justify_between() + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(text(13.)) + .text_color(palette.text) + .child(label.to_string()), + ) + .children(hint.map(|hint| { + div() + .text_size(text(11.)) + .text_color(palette.muted) + .child(hint.to_string()) + })), + ) + .child(div().w(px(220.)).flex_shrink_0().child(control)) +} + +pub(super) fn pill(label: &str, color: Hsla, palette: Palette) -> Div { + div() + .px(px(6.)) + .py(px(1.)) + .rounded(px(4.)) + .bg(palette.hover) + .text_size(text(11.)) + .text_color(color) + .child(label.to_string()) +} + +pub(super) fn page_heading(title: &str, actions: Vec, palette: Palette) -> Div { + div() + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .child( + div() + .text_size(text(20.)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text) + .child(title.to_string()), + ) + .children(actions) +} diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs new file mode 100644 index 0000000..4de01e6 --- /dev/null +++ b/crates/client/src/gui/builder/users.rs @@ -0,0 +1,912 @@ +use std::future::Future; + +use common::{ + error::Error, + model::{Account, Role, SessionInfo, User}, + permission, + time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, +}; +use gpui_kit::{ + AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + assets::IconName, + component::{Icon, input::Input}, + div, + prelude::FluentBuilder as _, + px, +}; + +use super::ui::{accent_button, card, danger_button, pill, plain_button}; +use crate::{ + gui::{ + DATE, DAY, Palette, Tooltip as _, Yumush, auth::field, avatar, clickable, + community_settings::search_text, entity_action, id_time, millis_time, notify_error, text, + }, + network::NetworkHandle, +}; + +const MINUTES_PER_HOUR: u64 = HOUR_MILLIS / MINUTE_MILLIS; +const MINUTES_PER_DAY: u64 = DAY_MILLIS / MINUTE_MILLIS; + +fn seen_text(last_seen: Option) -> String { + let Some(last_seen) = last_seen else { + return "never".to_string(); + }; + let minutes = now_ms().saturating_sub(last_seen) / MINUTE_MILLIS; + + match minutes { + 0 => "now".to_string(), + 1..MINUTES_PER_HOUR => format!("{minutes}m ago"), + MINUTES_PER_HOUR..MINUTES_PER_DAY => format!("{}h ago", minutes / MINUTES_PER_HOUR), + _ => millis_time(last_seen, DAY), + } +} + +fn status(label: &str, color: gpui_kit::Hsla, palette: Palette) -> Div { + div().flex_shrink_0().child(pill(label, color, palette)) +} + +fn divider(palette: Palette) -> Div { + div().w(px(1.)).h(px(16.)).mx(px(4.)).bg(palette.border) +} + +impl Yumush { + pub(super) fn submit_new_user(&mut self, window: &mut Window, cx: &mut Context) { + let username = self.chat.new_username.read(cx).text().to_string(); + let password = self.chat.new_password.read(cx).text().to_string(); + self.chat + .new_password + .update(cx, |input, cx| input.set_value("", window, cx)); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.create_user(&username, &password).await { + Ok(_) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush + .chat + .new_username + .update(cx, |input, cx| input.set_value("", window, cx)); + yumush.load_users(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn set_builder_role( + &mut self, + user_id: &str, + role: Role, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.set_role(&user_id, role).await { + Ok(user) => { + let _ = this.update(cx, |yumush, cx| { + let index = yumush + .chat + .builder_users + .iter() + .position(|existing| existing.user.id == user.id); + if let Some(index) = index { + yumush.chat.builder_users[index].user = user; + } + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn delete_builder_user( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_builder_delete.as_deref() != Some(user_id) { + self.chat.pending_builder_delete = Some(user_id.to_string()); + cx.notify(); + return; + } + self.chat.pending_builder_delete = None; + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_user(&user_id).await { + Ok(()) => { + let _ = this.update(cx, |yumush, cx| { + yumush + .chat + .builder_users + .retain(|account| account.user.id != user_id); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn builder_user_action( + &mut self, + window: &mut Window, + cx: &mut Context, + action: impl FnOnce(NetworkHandle) -> Fut + 'static, + ) where + Fut: Future> + 'static, + { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| match action(network).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| yumush.load_users(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + }) + .detach(); + } + + pub(super) fn suspend_builder_user( + &mut self, + user_id: &str, + suspended: bool, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + self.builder_user_action(window, cx, move |network| async move { + network.suspend_user(&user_id, suspended).await + }); + } + + pub(super) fn revoke_builder_sessions( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + self.builder_user_action(window, cx, move |network| async move { + network.revoke_sessions(&user_id).await + }); + } + + pub(super) fn clear_builder_profile( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + self.builder_user_action(window, cx, move |network| async move { + network.clear_profile(&user_id).await.map(|_| ()) + }); + } + + pub(super) fn toggle_builder_password(&mut self, user_id: &str, cx: &mut Context) { + if self.chat.pending_builder_password.as_deref() == Some(user_id) { + self.chat.pending_builder_password = None; + } else { + self.chat.pending_builder_password = Some(user_id.to_string()); + } + cx.notify(); + } + + pub(super) fn reset_builder_password(&mut self, window: &mut Window, cx: &mut Context) { + let Some(user_id) = self.chat.pending_builder_password.take() else { + return; + }; + let password = self.chat.builder_password.read(cx).text().to_string(); + self.chat + .builder_password + .update(cx, |input, cx| input.set_value("", window, cx)); + self.builder_user_action(window, cx, move |network| async move { + network.reset_password(&user_id, &password).await + }); + } + + pub(super) fn load_sessions( + &self, + user_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.sessions(&user_id).await { + Ok(sessions) => { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_sessions = Some((user_id, sessions)); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn toggle_builder_sessions( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self + .chat + .builder_sessions + .as_ref() + .is_some_and(|(open, _)| open == user_id) + { + self.chat.builder_sessions = None; + cx.notify(); + return; + } + self.load_sessions(user_id.to_string(), window, cx); + } + + pub(super) fn revoke_builder_session( + &mut self, + user_id: &str, + session_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + let user_id = user_id.to_string(); + let session_id = session_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.revoke_session(&user_id, &session_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.load_sessions(user_id, window, cx) + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn toggle_builder_rename(&mut self, user_id: &str, cx: &mut Context) { + if self.chat.pending_builder_rename.as_deref() == Some(user_id) { + self.chat.pending_builder_rename = None; + } else { + self.chat.pending_builder_rename = Some(user_id.to_string()); + } + cx.notify(); + } + + pub(super) fn rename_builder_user(&mut self, window: &mut Window, cx: &mut Context) { + let Some(user_id) = self.chat.pending_builder_rename.take() else { + return; + }; + let username = self.chat.builder_rename.read(cx).text().to_string(); + self.chat + .builder_rename + .update(cx, |input, cx| input.set_value("", window, cx)); + self.builder_user_action(window, cx, move |network| async move { + network.rename_user(&user_id, &username).await.map(|_| ()) + }); + } + + pub(super) fn toggle_builder_timeout(&mut self, user_id: &str, cx: &mut Context) { + if self.chat.pending_builder_timeout.as_deref() == Some(user_id) { + self.chat.pending_builder_timeout = None; + } else { + self.chat.pending_builder_timeout = Some(user_id.to_string()); + } + cx.notify(); + } + + pub(super) fn confirm_builder_timeout(&mut self, window: &mut Window, cx: &mut Context) { + let Some(user_id) = self.chat.pending_builder_timeout.clone() else { + return; + }; + let minutes = self.chat.builder_timeout.read(cx).text().to_string(); + let Ok(minutes) = minutes.trim().parse::() else { + return; + }; + self.chat.pending_builder_timeout = None; + self.chat + .builder_timeout + .update(cx, |input, cx| input.set_value("", window, cx)); + self.builder_user_action(window, cx, move |network| async move { + network.timeout_user(&user_id, minutes).await + }); + } + + pub(super) fn toggle_builder_ban(&mut self, user_id: &str, cx: &mut Context) { + if self.chat.pending_builder_ban.as_deref() == Some(user_id) { + self.chat.pending_builder_ban = None; + } else { + self.chat.pending_builder_ban = Some(user_id.to_string()); + } + cx.notify(); + } + + pub(super) fn toggle_builder_ban_ip(&mut self, cx: &mut Context) { + self.chat.builder_ban_ip = !self.chat.builder_ban_ip; + cx.notify(); + } + + pub(super) fn confirm_builder_ban(&mut self, window: &mut Window, cx: &mut Context) { + let Some(user_id) = self.chat.pending_builder_ban.take() else { + return; + }; + let reason = self.chat.builder_ban_reason.read(cx).text().to_string(); + let reason = reason.trim().to_string(); + let reason = (!reason.is_empty()).then_some(reason); + let ip = self.chat.builder_ban_ip; + self.chat + .builder_ban_reason + .update(cx, |input, cx| input.set_value("", window, cx)); + self.builder_user_action(window, cx, move |network| async move { + network.ban_user(&user_id, reason.as_deref(), ip).await + }); + } + + pub(super) fn purge_builder_user( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.pending_builder_purge.as_deref() != Some(user_id) { + self.chat.pending_builder_purge = Some(user_id.to_string()); + cx.notify(); + return; + } + self.chat.pending_builder_purge = None; + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.purge_user(&user_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush + .chat + .builder_messages + .retain(|hit| hit.message.user_id != user_id); + yumush.load_users(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn users_body( + &self, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> Vec { + let query = search_text(&self.chat.builder_search, cx); + let rows: Vec
= match self.user.as_ref() { + Some(me) => self + .chat + .builder_users + .iter() + .filter(|account| { + account + .user + .username + .to_lowercase() + .contains(query.as_str()) + }) + .map(|account| self.builder_row(account, me, entity, palette)) + .collect(), + None => Vec::new(), + }; + + let toolbar = div() + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .gap(px(8.)) + .border_b_1() + .border_color(palette.border) + .child( + div() + .flex_1() + .min_w_0() + .child(Input::new(&self.chat.builder_search)), + ) + .child( + div() + .w(px(160.)) + .flex_shrink_0() + .child(field(palette, &self.chat.new_username)), + ) + .child( + div() + .w(px(160.)) + .flex_shrink_0() + .child(field(palette, &self.chat.new_password)), + ) + .child(accent_button( + "create_user", + "Create", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.submit_new_user(window, cx) + }), + )); + + let body = if rows.is_empty() { + div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child("No users".to_string()) + } else { + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) + }; + + vec![card(palette).child(toolbar).child(body).into_any_element()] + } + + pub(super) fn builder_timeout_row( + &self, + user_id: &str, + entity: &Entity, + palette: Palette, + ) -> Div { + div() + .h(px(40.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_1() + .min_w_0() + .child(field(palette, &self.chat.builder_timeout)), + ) + .child(plain_button( + format!("confirm_timeout_{user_id}"), + "Confirm", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.confirm_builder_timeout(window, cx) + }), + )) + } + + pub(super) fn builder_ban_row( + &self, + user_id: &str, + entity: &Entity, + palette: Palette, + ) -> Div { + let ip_label = if self.chat.builder_ban_ip { + "IP: on" + } else { + "IP: off" + }; + + div() + .h(px(40.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_1() + .min_w_0() + .child(field(palette, &self.chat.builder_ban_reason)), + ) + .child(plain_button( + format!("ban_ip_{user_id}"), + ip_label, + palette, + entity_action(entity, |yumush, _, cx| yumush.toggle_builder_ban_ip(cx)), + )) + .child(plain_button( + format!("confirm_ban_{user_id}"), + "Confirm", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.confirm_builder_ban(window, cx) + }), + )) + } + + pub(super) fn builder_session_row( + &self, + user_id: &str, + session: &SessionInfo, + entity: &Entity, + palette: Palette, + ) -> Div { + let revoke_user_id = user_id.to_string(); + let session_id = session.id.clone(); + let revoke_button = plain_button( + format!("revoke_session_{}", session.id), + "Revoke", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.revoke_builder_session(&revoke_user_id, &session_id, window, cx) + }), + ); + let device = if session.device.is_empty() { + "unknown device" + } else { + session.device.as_str() + }; + + div() + .h(px(36.)) + .pl(px(40.)) + .pr(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .child(device.to_string()), + ) + .child( + div() + .flex_shrink_0() + .text_size(text(11.)) + .text_color(palette.muted) + .child(seen_text(session.last_seen)), + ) + .child(revoke_button) + } + + pub(super) fn builder_rename_row( + &self, + user_id: &str, + entity: &Entity, + palette: Palette, + ) -> Div { + div() + .h(px(40.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_1() + .min_w_0() + .child(field(palette, &self.chat.builder_rename)), + ) + .child(plain_button( + format!("confirm_rename_{user_id}"), + "Confirm", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.rename_builder_user(window, cx) + }), + )) + } + + pub(super) fn builder_password_row( + &self, + user_id: &str, + entity: &Entity, + palette: Palette, + ) -> Div { + div() + .h(px(40.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .flex_1() + .min_w_0() + .child(field(palette, &self.chat.builder_password)), + ) + .child(plain_button( + format!("confirm_password_{user_id}"), + "Confirm", + palette, + entity_action(entity, |yumush, window, cx| { + yumush.reset_builder_password(window, cx) + }), + )) + } + + pub(super) fn builder_row( + &self, + account: &Account, + me: &User, + entity: &Entity, + palette: Palette, + ) -> Div { + let user = &account.user; + let is_self = user.id == me.id; + let builder = user.role == Role::Builder; + let manage = permission::can_manage_user(me.role, is_self, user.role); + let can_role = permission::can_set_role(me.role, is_self); + let can_delete = !is_self && permission::can_delete_user(me.role, is_self, user.role); + let has_actions = manage || can_role || can_delete; + let suspended = account.suspended; + let timed_out = account + .suspended_until + .is_some_and(|until| until > now_ms()); + let expanded_sessions = self + .chat + .builder_sessions + .as_ref() + .filter(|(open, _)| *open == user.id) + .map(|(_, sessions)| sessions); + let expanded = expanded_sessions.is_some(); + let pending_delete = self.chat.pending_builder_delete.as_deref() == Some(user.id.as_str()); + let pending_purge = self.chat.pending_builder_purge.as_deref() == Some(user.id.as_str()); + let role_id = user.id.clone(); + let delete_id = user.id.clone(); + let suspend_id = user.id.clone(); + let sessions_id = user.id.clone(); + let password_id = user.id.clone(); + let profile_id = user.id.clone(); + let sessions_list_id = user.id.clone(); + let rename_id = user.id.clone(); + let timeout_id = user.id.clone(); + let ban_id = user.id.clone(); + let purge_id = user.id.clone(); + let joined = id_time(&user.id, DATE); + let seen = seen_text(account.last_seen); + let next_role = if builder { Role::User } else { Role::Builder }; + + let role_button = plain_button( + format!("role_{}", user.id), + if builder { + "Remove builder" + } else { + "Make builder" + }, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_builder_role(&role_id, next_role, window, cx) + }), + ); + + let suspend_button = plain_button( + format!("suspend_user_{}", user.id), + if suspended { "Unsuspend" } else { "Suspend" }, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.suspend_builder_user(&suspend_id, !suspended, window, cx) + }), + ); + + let sessions_button = plain_button( + format!("sessions_user_{}", user.id), + "Sign out", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.revoke_builder_sessions(&sessions_id, window, cx) + }), + ); + + let password_button = plain_button( + format!("password_user_{}", user.id), + "Reset password", + palette, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_builder_password(&password_id, cx) + }), + ); + + let toggle_button = clickable( + format!("sessions_list_user_{}", user.id), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.toggle_builder_sessions(&sessions_list_id, window, cx) + }), + ) + .tip("Actions") + .size(px(28.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .when(expanded, |this| this.bg(palette.hover)) + .child(Icon::new(IconName::Ellipsis).w(px(16.)).h(px(16.))); + + let rename_button = plain_button( + format!("rename_user_{}", user.id), + "Rename", + palette, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_builder_rename(&rename_id, cx) + }), + ); + + let timeout_button = plain_button( + format!("timeout_user_{}", user.id), + "Timeout", + palette, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_builder_timeout(&timeout_id, cx) + }), + ); + + let ban_button = plain_button( + format!("ban_user_{}", user.id), + "Ban", + palette, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_builder_ban(&ban_id, cx) + }), + ); + + let profile_button = plain_button( + format!("profile_user_{}", user.id), + "Clear profile", + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.clear_builder_profile(&profile_id, window, cx) + }), + ); + + let purge_button = danger_button( + format!("purge_user_{}", user.id), + "Purge", + pending_purge, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.purge_builder_user(&purge_id, window, cx) + }), + ); + + let delete_button = danger_button( + format!("delete_user_{}", user.id), + "Delete", + pending_delete, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_builder_user(&delete_id, window, cx) + }), + ); + + let row = div() + .px(px(14.)) + .py(px(10.)) + .flex() + .items_center() + .gap(px(10.)) + .child(avatar( + palette, + user, + px(28.), + text(11.), + &self.chat.avatars, + )) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .min_w_0() + .flex() + .items_center() + .gap(px(6.)) + .child( + div() + .min_w_0() + .truncate() + .text_size(text(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text) + .child(user.username.clone()), + ) + .when(builder, |this| { + this.child(status("Builder", palette.accent, palette)) + }) + .when(suspended, |this| { + this.child(status("Suspended", palette.danger, palette)) + }) + .when(timed_out, |this| { + this.child(status("Timed out", palette.danger, palette)) + }) + .when(account.ghost, |this| { + this.child(status("Ghost", palette.muted, palette)) + }), + ) + .child( + div() + .min_w_0() + .truncate() + .text_size(text(11.)) + .text_color(palette.muted) + .child(format!("joined {joined} · seen {seen}")), + ), + ) + .children(has_actions.then_some(toggle_button)); + + let panel = expanded_sessions.map(|sessions| { + let open_id = user.id.as_str(); + let password_open = self.chat.pending_builder_password.as_deref() == Some(open_id); + let rename_open = self.chat.pending_builder_rename.as_deref() == Some(open_id); + let timeout_open = self.chat.pending_builder_timeout.as_deref() == Some(open_id); + let ban_open = self.chat.pending_builder_ban.as_deref() == Some(open_id); + + let actions = div() + .px(px(14.)) + .flex() + .flex_wrap() + .items_center() + .gap(px(6.)) + .children(manage.then_some(rename_button)) + .children(manage.then_some(password_button)) + .children(can_role.then_some(role_button)) + .children(manage.then(|| divider(palette))) + .children(manage.then_some(timeout_button)) + .children(manage.then_some(suspend_button)) + .children(manage.then_some(ban_button)) + .children(manage.then_some(sessions_button)) + .children(manage.then(|| divider(palette))) + .children(manage.then_some(profile_button)) + .children(manage.then_some(purge_button)) + .children(can_delete.then_some(delete_button)); + + div() + .flex() + .flex_col() + .gap(px(6.)) + .pt(px(4.)) + .pb(px(10.)) + .bg(palette.window) + .border_t_1() + .border_color(palette.border) + .child(actions) + .children( + password_open.then(|| self.builder_password_row(&user.id, entity, palette)), + ) + .children(rename_open.then(|| self.builder_rename_row(&user.id, entity, palette))) + .children(timeout_open.then(|| self.builder_timeout_row(&user.id, entity, palette))) + .children(ban_open.then(|| self.builder_ban_row(&user.id, entity, palette))) + .children( + sessions.iter().map(|session| { + self.builder_session_row(&user.id, session, entity, palette) + }), + ) + }); + + div().flex().flex_col().child(row).children(panel) + } +} diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs new file mode 100644 index 0000000..badc3e3 --- /dev/null +++ b/crates/client/src/gui/builder/voice.rs @@ -0,0 +1,240 @@ +use std::future::Future; + +use common::{ + error::Error, + model::{User, VoiceRoom}, +}; +use gpui_kit::{ + AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, + div, prelude::FluentBuilder as _, px, +}; + +use super::ui::{card, card_header, icon_button, list_card, pill}; +use crate::{ + gui::{Palette, Yumush, avatar, entity_action, notify_error, text}, + network::NetworkHandle, +}; + +fn rows_body(rows: Vec
, empty: &str, palette: Palette) -> Div { + if rows.is_empty() { + return div() + .py(px(24.)) + .flex() + .justify_center() + .text_size(text(12.)) + .text_color(palette.muted) + .child(empty.to_string()); + } + div() + .flex() + .flex_col() + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })) +} + +impl Yumush { + pub(super) fn load_voice_rooms(&self, window: &mut Window, cx: &mut Context) { + if !self.is_builder() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let rooms = match network.voice_rooms().await { + Ok(rooms) => rooms, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.builder_voice_rooms = rooms; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn voice_action( + &mut self, + window: &mut Window, + cx: &mut Context, + action: impl FnOnce(NetworkHandle) -> Fut + 'static, + ) where + Fut: Future> + 'static, + { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| match action(network).await { + Ok(()) => { + let _ = + this.update_in(cx, |yumush, window, cx| yumush.load_voice_rooms(window, cx)); + } + Err(error) => notify_error(&this, cx, error), + }) + .detach(); + } + + pub(super) fn set_server_mute( + &mut self, + user_id: &str, + muted: bool, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + self.voice_action(window, cx, move |network| async move { + network.server_mute(&user_id, muted).await + }); + } + + pub(super) fn kick_from_voice( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + let user_id = user_id.to_string(); + self.voice_action(window, cx, move |network| async move { + network.kick_from_voice(&user_id).await + }); + } + + pub(super) fn voice_body(&self, entity: &Entity, palette: Palette) -> Vec { + let mut body = Vec::new(); + + if self.chat.builder_voice_rooms.is_empty() { + body.push( + list_card(None, Vec::new(), "No active voice rooms", palette).into_any_element(), + ); + } + body.extend(self.chat.builder_voice_rooms.iter().map(|room| { + self.voice_room_card(room, entity, palette) + .into_any_element() + })); + + body + } + + pub(super) fn voice_room_card( + &self, + room: &VoiceRoom, + entity: &Entity, + palette: Palette, + ) -> Div { + let id = room.community_id.clone(); + let voice = self + .chat + .builder_communities + .iter() + .find(|summary| summary.community.id == id) + .map(|summary| summary.community.voice_enabled); + + let mut actions = + vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()]; + if let Some(enabled) = voice { + actions.push( + icon_button( + format!("room_voice_{id}"), + if enabled { + IconName::Phone + } else { + IconName::PhoneOff + }, + if enabled { "Voice on" } else { "Voice off" }, + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_builder_community_voice(&id, !enabled, window, cx) + }), + ) + .into_any_element(), + ); + } + + let rows = room + .users + .iter() + .map(|user| { + self.voice_user_row( + user, + room.muted.contains(&user.id), + room.ghosts.contains(&user.id), + entity, + palette, + ) + }) + .collect(); + + card(palette) + .child(card_header(&room.community, actions, palette)) + .child(rows_body(rows, "No users", palette)) + } + + pub(super) fn voice_user_row( + &self, + user: &User, + muted: bool, + ghost: bool, + entity: &Entity, + palette: Palette, + ) -> Div { + let id = user.id.clone(); + let mute_id = id.clone(); + let kick_id = id.clone(); + + div() + .min_h(px(44.)) + .px(px(14.)) + .py(px(8.)) + .flex() + .items_center() + .gap(px(10.)) + .child(avatar( + palette, + user, + px(24.), + text(10.), + &self.chat.avatars, + )) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(text(13.)) + .text_color(palette.text) + .child(user.username.clone()), + ) + .children(muted.then(|| pill("Muted", palette.danger, palette))) + .children(ghost.then(|| pill("Ghost", palette.muted, palette))) + .child(icon_button( + format!("voice_mute_{id}"), + if muted { + IconName::Mic + } else { + IconName::MicOff + }, + if muted { "Unmute" } else { "Mute" }, + palette.muted, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_server_mute(&mute_id, !muted, window, cx) + }), + )) + .child(icon_button( + format!("voice_kick_{id}"), + IconName::UserX, + "Kick", + palette.danger, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.kick_from_voice(&kick_id, window, cx) + }), + )) + } +} diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index e042bf1..22083da 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,4 +1,5 @@ use super::text; +use crate::gui::CLOCK; use std::{ collections::{HashMap, HashSet}, sync::Arc, @@ -7,9 +8,9 @@ use std::{ use crate::gui::social::InviteLookup; use crate::gui::{ - FIND_HINT, Palette, Tooltip as _, Yumush, - admin::{AdminTab, Transfer}, - avatar, badge, clickable, community_icon, community_name, + FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, + builder::{BuilderTab, Transfer}, + clickable, community_icon, community_name, community_settings::{BanSort, LogSort}, composer::{self, Composer}, entity_action, hoverable, id_time, @@ -24,16 +25,17 @@ use common::{ constant::MESSAGE_PAGE_LIMIT, event::Event, model::{ - ACTION_NAMES, Account, AdminLogEntry, Ban, Community, CommunityKind, CommunitySummary, - DayStat, Friends, Invitation, InviteCode, LogEntry, Member, Message, MessageHit, Overview, - Rank, Report, ReportStatus, ServerBan, SessionInfo, User, VoiceRoom, AttachmentInfo, - CommunityUsage, Usage, + ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, Community, CommunityKind, + CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry, + Member, Message, MessageHit, Overview, Rank, Report, ReportStatus, ServerBan, SessionInfo, + Usage, User, VoiceRoom, }, permission, }; use gpui_kit::{ - Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, InteractiveElement, IntoElement, - ParentElement, RenderOnce, ScrollHandle, StatefulInteractiveElement, Styled, Task, Window, + Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, + InteractiveElement, IntoElement, ParentElement, RenderOnce, ScrollHandle, + StatefulInteractiveElement, Styled, Task, Window, assets::IconName, base::Selectable, component::{ @@ -53,7 +55,7 @@ pub enum View { Chat, Settings, CommunitySettings, - Admin, + Builder, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -129,13 +131,13 @@ pub struct Chat { pub(super) friends: Friends, pub(super) invitations: Vec, pub(super) pending_user_delete: Option, - pub(super) pending_admin_delete: Option, - pub(super) admin_users: Vec, - pub(super) pending_admin_password: Option, - pub(super) admin_password: Entity, - pub(super) admin_sessions: Option<(String, Vec)>, - pub(super) pending_admin_rename: Option, - pub(super) admin_rename: Entity, + pub(super) pending_builder_delete: Option, + pub(super) builder_users: Vec, + pub(super) pending_builder_password: Option, + pub(super) builder_password: Entity, + pub(super) builder_sessions: Option<(String, Vec)>, + pub(super) pending_builder_rename: Option, + pub(super) builder_rename: Entity, pub(super) server_name: Entity, pub(super) server_limit: Entity, pub(super) server_user_quota: Entity, @@ -150,55 +152,55 @@ pub struct Chat { pub(super) server_logins_per_minute: Entity, pub(super) server_registration_open: bool, pub(super) server_maintenance: bool, - pub(super) pending_admin_timeout: Option, - pub(super) admin_timeout: Entity, - pub(super) pending_admin_ban: Option, - pub(super) admin_ban_reason: Entity, - pub(super) admin_ban_ip: bool, - pub(super) admin_bans: Vec, - pub(super) admin_invites: Vec, + pub(super) pending_builder_timeout: Option, + pub(super) builder_timeout: Entity, + pub(super) pending_builder_ban: Option, + pub(super) builder_ban_reason: Entity, + pub(super) builder_ban_ip: bool, + pub(super) builder_bans: Vec, + pub(super) builder_invites: Vec, pub(super) invite_uses: Entity, pub(super) invite_hours: Entity, pub(super) pending_invite_delete: Option, pub(super) new_username: Entity, pub(super) new_password: Entity, - pub(super) admin_tab: AdminTab, - pub(super) admin_overview: Option, - pub(super) admin_logs: Vec, - pub(super) admin_stats: Vec, - pub(super) admin_log_actor: Entity, - pub(super) admin_log_target: Entity, - pub(super) admin_log_action: Entity>>, - pub(super) admin_log_from: Entity, - pub(super) admin_log_to: Entity, - pub(super) admin_search: Entity, - pub(super) admin_communities: Vec, - pub(super) admin_reports: Vec, + pub(super) builder_tab: BuilderTab, + pub(super) builder_overview: Option, + pub(super) builder_logs: Vec, + pub(super) builder_stats: Vec, + pub(super) builder_log_actor: Entity, + pub(super) builder_log_target: Entity, + pub(super) builder_log_action: Entity>>, + pub(super) builder_log_from: Entity, + pub(super) builder_log_to: Entity, + pub(super) builder_search: Entity, + pub(super) builder_communities: Vec, + pub(super) builder_reports: Vec, pub(super) report_filter: Option, pub(super) open_reports: usize, pub(super) report: Option, pub(super) report_reason: Entity, pub(super) pending_community_delete: Option, - pub(super) admin_message_text: Entity, - pub(super) admin_message_user: Entity, - pub(super) admin_message_community: Entity, - pub(super) admin_message_from: Entity, - pub(super) admin_message_to: Entity, - pub(super) admin_messages: Vec, - pub(super) admin_attachment_user: Entity, - pub(super) admin_attachment_community: Entity, - pub(super) admin_usage_users: Vec, - pub(super) admin_usage_communities: Vec, - pub(super) admin_attachments: Vec, + pub(super) builder_message_text: Entity, + pub(super) builder_message_user: Entity, + pub(super) builder_message_community: Entity, + pub(super) builder_message_from: Entity, + pub(super) builder_message_to: Entity, + pub(super) builder_messages: Vec, + pub(super) builder_attachment_user: Entity, + pub(super) builder_attachment_community: Entity, + pub(super) builder_usage_users: Vec, + pub(super) builder_usage_communities: Vec, + pub(super) builder_attachments: Vec, pub(super) pending_attachment_delete: Option, pub(super) pending_message_delete: Option, - pub(super) pending_admin_purge: Option, + pub(super) pending_builder_purge: Option, pub(super) transfer: Option, pub(super) voice: HashMap>, pub(super) voice_state: VoiceState, pub(super) speaking: HashSet, pub(super) server_muted: HashSet, - pub(super) admin_voice_rooms: Vec, + pub(super) builder_voice_rooms: Vec, pub(super) voice_task: Option>, pub(super) media: Media, } @@ -232,50 +234,54 @@ impl Chat { let ban_search = new_input("Search...", window, cx); let log_search = new_input("Search...", window, cx); - let admin_search = new_input("Search...", window, cx); - let admin_password = new_input("New password...", window, cx); - admin_password.update(cx, |input, cx| input.set_masked(true, window, cx)); - let admin_rename = new_input("New username...", window, cx); + let builder_search = new_input("Search...", window, cx); + let builder_password = new_input("New password...", window, cx); + builder_password.update(cx, |input, cx| input.set_masked(true, window, cx)); + let builder_rename = new_input("New username...", window, cx); let server_name = new_input("Server name...", window, cx); - let server_limit = new_input("Max attachment (MB)...", window, cx); - let server_user_quota = new_input("0 = off", window, cx); - let server_community_quota = new_input("0 = off", window, cx); - let server_message_retention = new_input("0 = off", window, cx); - let server_attachment_retention = new_input("0 = off", window, cx); + let server_limit = new_input("", window, cx); + let server_user_quota = new_input("", window, cx); + let server_community_quota = new_input("", window, cx); + let server_message_retention = new_input("", window, cx); + let server_attachment_retention = new_input("", window, cx); let server_announcement = new_input("Announcement...", window, cx); - let server_max_communities = new_input("0 = unlimited", window, cx); + let server_max_communities = new_input("", window, cx); let server_max_message_length = new_input("Max message length...", window, cx); - let server_max_avatar = new_input("Max avatar (KB)...", window, cx); - let server_messages_per_minute = new_input("0 = off", window, cx); - let server_logins_per_minute = new_input("0 = off", window, cx); - let admin_timeout = new_input("Minutes...", window, cx); - let admin_ban_reason = new_input("Reason...", window, cx); + let server_max_avatar = new_input("", window, cx); + let server_messages_per_minute = new_input("", window, cx); + let server_logins_per_minute = new_input("", window, cx); + let builder_timeout = new_input("Minutes...", window, cx); + let builder_ban_reason = new_input("Reason...", window, cx); let invite_uses = new_input("Uses...", window, cx); - let invite_hours = new_input("Hours (optional)...", window, cx); + let invite_hours = new_input("Hours", window, cx); let new_username = new_input("Username...", window, cx); let new_password = new_input("Password...", window, cx); let report_reason = new_input("Reason...", window, cx); - let admin_message_text = new_input("Text...", window, cx); - let admin_message_user = new_input("User...", window, cx); - let admin_message_community = new_input("Community...", window, cx); - let admin_message_from = new_input("From YYYY-MM-DD", window, cx); - let admin_message_to = new_input("To YYYY-MM-DD", window, cx); - let admin_attachment_user = new_input("User...", window, cx); - let admin_attachment_community = new_input("Community...", window, cx); - let admin_log_actor = new_input("Actor...", window, cx); - let admin_log_target = new_input("Target...", window, cx); - let admin_log_from = new_input("From YYYY-MM-DD", window, cx); - let admin_log_to = new_input("To YYYY-MM-DD", window, cx); - let admin_log_action = cx.new(|cx| { + let builder_message_text = new_input("Text...", window, cx); + let builder_message_user = new_input("User...", window, cx); + let builder_message_community = new_input("Community...", window, cx); + let builder_message_from = new_input("From YYYY-MM-DD", window, cx); + let builder_message_to = new_input("To YYYY-MM-DD", window, cx); + let builder_attachment_user = new_input("User...", window, cx); + let builder_attachment_community = new_input("Community...", window, cx); + let builder_log_actor = new_input("Actor...", window, cx); + let builder_log_target = new_input("Target...", window, cx); + let builder_log_from = new_input("From YYYY-MM-DD", window, cx); + let builder_log_to = new_input("To YYYY-MM-DD", window, cx); + let builder_log_action = cx.new(|cx| { SelectState::new( - SearchableVec::new(std::iter::once("All").chain(ACTION_NAMES).collect::>()), + SearchableVec::new( + std::iter::once("All") + .chain(ACTION_NAMES) + .collect::>(), + ), Some(IndexPath::new(0)), window, cx, ) }); new_password.update(cx, |input, cx| input.set_masked(true, window, cx)); - for search in [&ban_search, &log_search, &admin_search] { + for search in [&ban_search, &log_search, &builder_search] { cx.subscribe_in(search, window, |_, _, event, window, cx| { if matches!(event, InputEvent::Change) { window.refresh(); @@ -319,36 +325,36 @@ impl Chat { user_requests: HashSet::new(), delete_step: DeleteStep::Idle, pending_user_delete: None, - pending_admin_delete: None, - admin_users: vec![], - admin_tab: AdminTab::Overview, - admin_overview: None, - admin_logs: vec![], - admin_stats: vec![], - admin_log_actor, - admin_log_target, - admin_log_action, - admin_log_from, - admin_log_to, - admin_search, - admin_communities: vec![], + pending_builder_delete: None, + builder_users: vec![], + builder_tab: BuilderTab::Overview, + builder_overview: None, + builder_logs: vec![], + builder_stats: vec![], + builder_log_actor, + builder_log_target, + builder_log_action, + builder_log_from, + builder_log_to, + builder_search, + builder_communities: vec![], pending_community_delete: None, - admin_message_text, - admin_message_user, - admin_message_community, - admin_message_from, - admin_message_to, - admin_messages: vec![], - admin_attachment_user, - admin_attachment_community, - admin_usage_users: vec![], - admin_usage_communities: vec![], - admin_attachments: vec![], + builder_message_text, + builder_message_user, + builder_message_community, + builder_message_from, + builder_message_to, + builder_messages: vec![], + builder_attachment_user, + builder_attachment_community, + builder_usage_users: vec![], + builder_usage_communities: vec![], + builder_attachments: vec![], pending_attachment_delete: None, pending_message_delete: None, - pending_admin_purge: None, + pending_builder_purge: None, transfer: None, - admin_password, + builder_password, server_name, server_limit, server_user_quota, @@ -363,23 +369,23 @@ impl Chat { server_logins_per_minute, server_registration_open: true, server_maintenance: false, - pending_admin_timeout: None, - admin_timeout, - pending_admin_ban: None, - admin_ban_reason, - admin_ban_ip: false, - admin_bans: vec![], - admin_invites: vec![], + pending_builder_timeout: None, + builder_timeout, + pending_builder_ban: None, + builder_ban_reason, + builder_ban_ip: false, + builder_bans: vec![], + builder_invites: vec![], invite_uses, invite_hours, pending_invite_delete: None, new_username, new_password, - pending_admin_password: None, - admin_sessions: None, - pending_admin_rename: None, - admin_rename, - admin_reports: vec![], + pending_builder_password: None, + builder_sessions: None, + pending_builder_rename: None, + builder_rename, + builder_reports: vec![], report_filter: Some(ReportStatus::Open), open_reports: 0, report: None, @@ -388,7 +394,7 @@ impl Chat { voice_state: VoiceState::Off, speaking: HashSet::new(), server_muted: HashSet::new(), - admin_voice_rooms: Vec::new(), + builder_voice_rooms: Vec::new(), voice_task: None, media: Media::default(), composer: Composer::Compose { reply: None }, @@ -738,40 +744,40 @@ impl Chat { self.found = None; self.select(None); self.unread.clear(); - self.admin_users.clear(); - self.admin_tab = AdminTab::Overview; - self.admin_overview = None; - self.admin_logs.clear(); - self.admin_stats.clear(); - self.admin_communities.clear(); - self.admin_reports.clear(); + self.builder_users.clear(); + self.builder_tab = BuilderTab::Overview; + self.builder_overview = None; + self.builder_logs.clear(); + self.builder_stats.clear(); + self.builder_communities.clear(); + self.builder_reports.clear(); self.report_filter = Some(ReportStatus::Open); self.open_reports = 0; self.report = None; self.pending_community_delete = None; - self.admin_messages.clear(); - self.admin_usage_users.clear(); - self.admin_usage_communities.clear(); - self.admin_attachments.clear(); + self.builder_messages.clear(); + self.builder_usage_users.clear(); + self.builder_usage_communities.clear(); + self.builder_attachments.clear(); self.pending_attachment_delete = None; self.pending_message_delete = None; - self.pending_admin_purge = None; + self.pending_builder_purge = None; self.transfer = None; - self.pending_admin_delete = None; - self.pending_admin_password = None; - self.admin_sessions = None; - self.pending_admin_rename = None; - self.pending_admin_timeout = None; - self.pending_admin_ban = None; - self.admin_ban_ip = false; - self.admin_bans.clear(); - self.admin_invites.clear(); + self.pending_builder_delete = None; + self.pending_builder_password = None; + self.builder_sessions = None; + self.pending_builder_rename = None; + self.pending_builder_timeout = None; + self.pending_builder_ban = None; + self.builder_ban_ip = false; + self.builder_bans.clear(); + self.builder_invites.clear(); self.pending_invite_delete = None; self.view = View::Chat; self.delete_step = DeleteStep::Idle; self.voice.clear(); self.server_muted.clear(); - self.admin_voice_rooms.clear(); + self.builder_voice_rooms.clear(); self.set_voice_off(); } @@ -943,7 +949,7 @@ impl Yumush { .children(self.announcement_banner(entity, palette)) .map(|panel| match self.chat.view { View::Settings => panel.child(self.settings_page(entity, palette, cx)), - View::Admin => panel.child(self.admin_page(entity, palette, cx)), + View::Builder => panel.child(self.builder_page(entity, palette, cx)), View::CommunitySettings => { panel.child(self.community_settings_page(entity, palette, cx)) } @@ -971,12 +977,14 @@ impl Yumush { .bg(palette.accent) .text_color(palette.on_accent) .child(text.to_string()) - .child(clickable( - "dismiss_announcement", - palette, - entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)), - ) - .child("×")), + .child( + clickable( + "dismiss_announcement", + palette, + entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)), + ) + .child("×"), + ), ) } @@ -1396,7 +1404,7 @@ impl Yumush { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { - let muted = muted || yumush.is_server_muted() || yumush.chat.ghost; + let muted = muted || yumush.mic_locked(); yumush.network.set_muted(muted); yumush.chat.voice.insert(community_id.clone(), participants); yumush.chat.voice_state = VoiceState::In { @@ -1445,6 +1453,10 @@ impl Yumush { .is_some_and(|me| self.chat.server_muted.contains(&me.id)) } + pub(super) fn mic_locked(&self) -> bool { + self.is_server_muted() || self.chat.ghost + } + pub(super) fn force_mute(&mut self, cx: &mut Context) { if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { *muted = true; @@ -1454,7 +1466,7 @@ impl Yumush { } fn toggle_mute(&mut self, cx: &mut Context) { - if self.is_server_muted() || self.chat.ghost { + if self.mic_locked() { return; } if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { @@ -1841,7 +1853,7 @@ fn render_message( div() .text_size(text(12.)) .text_color(palette.muted) - .child(id_time(&message.id, "%H:%M")), + .child(id_time(&message.id, CLOCK)), ), ) }) diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index 6f00e48..93a6b7f 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -1,4 +1,5 @@ use super::text; +use crate::gui::STAMP; use std::{collections::HashMap, sync::Arc}; use common::{ @@ -656,7 +657,7 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap size_text(attachment.size), + None => storage(attachment.size), }; let controls = card(palette) .child(toggle) diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index 82228be..f1e977a 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -1,4 +1,5 @@ use super::text; +use crate::gui::DAY_YEAR; use std::{collections::HashMap, sync::Arc}; use common::{ @@ -202,7 +203,7 @@ impl Card { div() .text_size(text(12.)) .text_color(palette.muted) - .child(format!("Joined {}", id_time(&self.user.id, "%b %-d, %Y"))), + .child(format!("Joined {}", id_time(&self.user.id, DAY_YEAR))), ) .children( self.reporting @@ -223,16 +224,13 @@ impl Card { let user_id = self.user.id.clone(); let mut rows = Vec::new(); - for (rank, label) in [ - (Rank::Member, "Make member"), - (Rank::Moderator, "Make moderator"), - (Rank::Admin, "Make admin"), - ] { + for rank in [Rank::Member, Rank::Moderator, Rank::Admin] { if target != Some(rank) && permission::can_set_rank(actor, target, rank) { let user_id = user_id.clone(); + let label = format!("Make {}", rank.label().to_lowercase()); rows.push( menu_row( - label, + label.clone(), label, IconName::Shield, palette.text, diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 5d994b3..cbf749a 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -1,6 +1,6 @@ use super::text; use common::{ - model::{CommunityKind, Invitation, User}, + model::{CommunityKind, Invitation, Role, User}, permission, validate::validate_community_name, }; @@ -523,12 +523,12 @@ impl Yumush { ) .children(self.is_builder().then(|| { icon_button( - "admin_button".to_string(), + "builder_button".to_string(), palette, IconName::Shield, - "Admin", + Role::Builder.label(), entity_action(entity, |yumush, window, cx| { - yumush.show_view(View::Admin, window, cx) + yumush.show_view(View::Builder, window, cx) }), ) })) diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs index a1e9f77..254074d 100644 --- a/crates/client/src/gui/snippet.rs +++ b/crates/client/src/gui/snippet.rs @@ -1,4 +1,5 @@ use super::text; +use crate::gui::CLOCK; use common::model::{Message, Role, SnippetMessage, User}; use gpui_kit::{ Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px, @@ -84,7 +85,7 @@ fn snippet_row( div() .text_size(text(11.)) .text_color(palette.muted) - .child(id_time(&item.id, "%H:%M")), + .child(id_time(&item.id, CLOCK)), ), ) .when(!item.body.is_empty(), |this| { diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index d6af3a7..81e0fa8 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -2,7 +2,7 @@ use super::text; use std::{fmt::Display, future::Future}; use common::{ - model::{Community, CommunityKind}, + model::{Community, CommunityKind, Rank}, validate::validate_username, }; use gpui_kit::{ @@ -410,7 +410,7 @@ fn invite_result( div() .text_size(text(13.)) .text_color(palette.muted) - .child("Member"), + .child(Rank::Member.label()), ) .into_any_element(), ), diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index 59c5fca..8afe4d5 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -37,6 +37,8 @@ pub struct Scale(pub FontSize); impl Global for Scale {} impl FontSize { + const ALL: [Self; 3] = [FontSize::Small, FontSize::Medium, FontSize::Large]; + fn name(self) -> &'static str { match self { FontSize::Small => "small", @@ -46,12 +48,7 @@ impl FontSize { } fn parse(value: &str) -> Option { - match value { - "small" => Some(FontSize::Small), - "medium" => Some(FontSize::Medium), - "large" => Some(FontSize::Large), - _ => None, - } + Self::ALL.into_iter().find(|size| size.name() == value) } pub fn pixels(self) -> Pixels { @@ -64,6 +61,13 @@ impl FontSize { } impl ThemeChoice { + const ALL: [Self; 4] = [ + ThemeChoice::System, + ThemeChoice::Light, + ThemeChoice::Dark, + ThemeChoice::Black, + ]; + fn name(self) -> &'static str { match self { ThemeChoice::System => "system", @@ -74,13 +78,7 @@ impl ThemeChoice { } fn parse(value: &str) -> Option { - match value { - "system" => Some(ThemeChoice::System), - "light" => Some(ThemeChoice::Light), - "dark" => Some(ThemeChoice::Dark), - "black" => Some(ThemeChoice::Black), - _ => None, - } + Self::ALL.into_iter().find(|choice| choice.name() == value) } } diff --git a/crates/client/src/voice/audio.rs b/crates/client/src/voice/audio.rs index 9e1c3c5..c3899df 100644 --- a/crates/client/src/voice/audio.rs +++ b/crates/client/src/voice/audio.rs @@ -26,6 +26,8 @@ mod backend; const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); const STOP_CHECK: Duration = Duration::from_millis(100); +const BYTES_PER_FRAME: usize = size_of::<[f32; 2]>(); +const REPORT_FRAMES: usize = VOICE_SAMPLE_RATE as usize / VOICE_FRAME_SAMPLES; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Device { @@ -233,10 +235,10 @@ fn tone(capture: Option<&Capture>, playback: &Playback, stop: &AtomicBool) { energy += sample * sample }); frames += 1; - if frames == 50 { + if frames == REPORT_FRAMES { info!( "voice tone rms {:.3}", - (energy / (50 * VOICE_FRAME_SAMPLES) as f32).sqrt() + (energy / (REPORT_FRAMES * VOICE_FRAME_SAMPLES) as f32).sqrt() ); energy = 0.0; frames = 0; diff --git a/crates/client/src/voice/audio/pipewire.rs b/crates/client/src/voice/audio/pipewire.rs index e2acae8..89c2986 100644 --- a/crates/client/src/voice/audio/pipewire.rs +++ b/crates/client/src/voice/audio/pipewire.rs @@ -3,7 +3,6 @@ use std::{ error::Error, rc::Rc, sync::atomic::{AtomicBool, Ordering}, - time::Duration, }; use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; @@ -11,12 +10,12 @@ use pipewire as pw; use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType}; use spa::pod::Pod; -use super::{Choice, Device, Devices, Worker, play, record, stereo_bytes, supervise}; +use super::{ + BYTES_PER_FRAME, Choice, Device, Devices, STOP_CHECK, Worker, play, record, stereo_bytes, + supervise, +}; use crate::voice::{Capture, Playback}; -const STOP_CHECK: Duration = Duration::from_millis(100); -const BYTES_PER_FRAME: usize = 8; - pub struct Backend { _worker: Worker, } diff --git a/crates/client/src/voice/audio/wasapi.rs b/crates/client/src/voice/audio/wasapi.rs index 8ef9840..7867bf2 100644 --- a/crates/client/src/voice/audio/wasapi.rs +++ b/crates/client/src/voice/audio/wasapi.rs @@ -13,12 +13,11 @@ use wasapi::{ }; use super::{ - Choice, Device, Devices, Downmix, Worker, play, record, stereo_bytes, stereo_frame, supervise, + BYTES_PER_FRAME, Choice, Device, Devices, Downmix, STOP_CHECK, Worker, play, record, + stereo_bytes, stereo_frame, supervise, }; use crate::voice::{Capture, Playback}; -const WAIT_MS: u32 = 100; -const BYTES_PER_FRAME: usize = 8; const CHECK_DEFAULT_EVERY: Duration = Duration::from_secs(1); pub struct Backend { @@ -213,7 +212,7 @@ fn capture_frames( let mut downmix = Downmix::default(); let mut checked = Instant::now(); while !stop.load(Ordering::Relaxed) { - let _ = event.wait_for_event(WAIT_MS); + let _ = event.wait_for_event(STOP_CHECK.as_millis() as u32); while reader.get_next_packet_size()?.unwrap_or(0) > 0 { reader.read_from_device_to_deque(&mut bytes)?; } @@ -270,7 +269,7 @@ fn render_frames( let mut bytes: Vec = Vec::new(); let mut checked = Instant::now(); while !stop.load(Ordering::Relaxed) { - let _ = event.wait_for_event(WAIT_MS); + let _ = event.wait_for_event(STOP_CHECK.as_millis() as u32); let frames = client.get_available_space_in_frames()? as usize; bytes.resize(frames * BYTES_PER_FRAME, 0); let chunks = bytes.as_chunks_mut::().0; diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index 914a17f..15a9f19 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -15,16 +15,16 @@ use crate::settings::Profile; pub const SILENT_DB: f32 = -100.0; const JITTER_CAPACITY: usize = 10; -const FRAME_MS: f32 = 20.0; +const FRAME_MS: f32 = VOICE_FRAME_SAMPLES as f32 * 1000.0 / VOICE_SAMPLE_RATE as f32; const MIN_FRAMES: usize = 1; const MAX_FRAMES: usize = 6; const DRIFT_MARGIN: usize = 2; const QUIET: f32 = 0.01; const SPEAKING_WINDOW: Duration = Duration::from_millis(300); const RESTART_AFTER: Duration = Duration::from_secs(1); -const MAX_DECODE_SAMPLES: usize = 5760; +const MAX_DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000; const HANGOVER_FRAMES: u32 = 15; -const FADE_SAMPLES: usize = 240; +const FADE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 5 / 1000; const EXPECTED_LOSS_PERC: u8 = 10; fn rms(samples: &[f32]) -> f32 { diff --git a/crates/common/src/constant.rs b/crates/common/src/constant.rs index a1a5f81..fd795a0 100644 --- a/crates/common/src/constant.rs +++ b/crates/common/src/constant.rs @@ -7,6 +7,7 @@ pub const MINIMUM_MESSAGE_LENGTH: usize = 1; pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16; pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3; pub const MESSAGE_PAGE_LIMIT: usize = 50; +pub const LOG_PAGE_LIMIT: u32 = 500; pub const AVATAR_SIZE: u32 = 128; pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024; pub const MAXIMUM_ANNOUNCEMENT_LENGTH: usize = 500; @@ -27,3 +28,6 @@ pub const MAXIMUM_ATTACHMENT_NAME_LENGTH: usize = 128; pub const THUMBNAIL_SIZE: u32 = 400; pub const ATTACHMENT_CHUNK_BYTES: usize = 64 * 1024; pub const ATTACHMENT_HEAD_BYTES: usize = 64; +pub const DEFAULT_MAX_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024; +pub const DEFAULT_MESSAGES_PER_MINUTE: u32 = 30; +pub const DEFAULT_LOGINS_PER_MINUTE: u32 = 10; diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index 0a85b8c..465dfa1 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -1,5 +1,10 @@ use bitcode::{Decode, Encode}; +use crate::constant::{ + DEFAULT_LOGINS_PER_MINUTE, DEFAULT_MAX_ATTACHMENT_BYTES, DEFAULT_MESSAGES_PER_MINUTE, + MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH, +}; + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] pub enum Role { User, @@ -7,6 +12,8 @@ pub enum Role { } impl Role { + pub const ALL: [Self; 2] = [Role::User, Role::Builder]; + pub fn as_str(self) -> &'static str { match self { Role::User => "user", @@ -14,13 +21,16 @@ impl Role { } } - pub fn parse(text: &str) -> Option { - match text { - "user" => Some(Role::User), - "builder" => Some(Role::Builder), - _ => None, + pub fn label(self) -> &'static str { + match self { + Role::User => "User", + Role::Builder => "Builder", } } + + pub fn parse(text: &str) -> Option { + Self::ALL.into_iter().find(|role| role.as_str() == text) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)] @@ -33,6 +43,14 @@ pub enum Rank { } impl Rank { + pub const ALL: [Self; 5] = [ + Rank::Member, + Rank::Moderator, + Rank::Admin, + Rank::Owner, + Rank::Builder, + ]; + pub fn as_str(self) -> &'static str { match self { Rank::Member => "member", @@ -43,16 +61,19 @@ impl Rank { } } - pub fn parse(text: &str) -> Option { - match text { - "member" => Some(Rank::Member), - "moderator" => Some(Rank::Moderator), - "admin" => Some(Rank::Admin), - "owner" => Some(Rank::Owner), - "builder" => Some(Rank::Builder), - _ => None, + pub fn label(self) -> &'static str { + match self { + Rank::Member => "Member", + Rank::Moderator => "Moderator", + Rank::Admin => "Admin", + Rank::Owner => "Owner", + Rank::Builder => "Builder", } } + + pub fn parse(text: &str) -> Option { + Self::ALL.into_iter().find(|rank| rank.as_str() == text) + } } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -179,68 +200,157 @@ pub enum AdminAction { GhostVoice { seconds: u64 }, } -pub const ACTION_NAMES: [&str; 28] = [ - "role_changed", - "user_deleted", - "user_suspended", - "user_unsuspended", - "sessions_revoked", - "password_reset", - "profile_cleared", - "user_created", - "community_deleted", - "ownership_transferred", - "settings_changed", - "user_renamed", - "user_timed_out", - "user_banned", - "ban_removed", - "invite_created", - "invite_deleted", - "report_handled", - "message_deleted", - "user_purged", - "voice_kicked", - "voice_muted", - "community_voice_set", - "attachment_deleted", - "ghost_enabled", - "ghost_disabled", - "ghost_visit", - "ghost_voice", -]; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdminActionKind { + RoleChanged, + UserDeleted, + UserSuspended, + UserUnsuspended, + SessionsRevoked, + PasswordReset, + ProfileCleared, + UserCreated, + CommunityDeleted, + OwnershipTransferred, + SettingsChanged, + UserRenamed, + UserTimedOut, + UserBanned, + BanRemoved, + InviteCreated, + InviteDeleted, + ReportHandled, + MessageDeleted, + UserPurged, + VoiceKicked, + VoiceMuted, + CommunityVoiceSet, + AttachmentDeleted, + GhostEnabled, + GhostDisabled, + GhostVisit, + GhostVoice, +} + +impl AdminActionKind { + pub const ALL: [Self; 28] = [ + AdminActionKind::RoleChanged, + AdminActionKind::UserDeleted, + AdminActionKind::UserSuspended, + AdminActionKind::UserUnsuspended, + AdminActionKind::SessionsRevoked, + AdminActionKind::PasswordReset, + AdminActionKind::ProfileCleared, + AdminActionKind::UserCreated, + AdminActionKind::CommunityDeleted, + AdminActionKind::OwnershipTransferred, + AdminActionKind::SettingsChanged, + AdminActionKind::UserRenamed, + AdminActionKind::UserTimedOut, + AdminActionKind::UserBanned, + AdminActionKind::BanRemoved, + AdminActionKind::InviteCreated, + AdminActionKind::InviteDeleted, + AdminActionKind::ReportHandled, + AdminActionKind::MessageDeleted, + AdminActionKind::UserPurged, + AdminActionKind::VoiceKicked, + AdminActionKind::VoiceMuted, + AdminActionKind::CommunityVoiceSet, + AdminActionKind::AttachmentDeleted, + AdminActionKind::GhostEnabled, + AdminActionKind::GhostDisabled, + AdminActionKind::GhostVisit, + AdminActionKind::GhostVoice, + ]; + + pub const fn as_str(self) -> &'static str { + match self { + AdminActionKind::RoleChanged => "role_changed", + AdminActionKind::UserDeleted => "user_deleted", + AdminActionKind::UserSuspended => "user_suspended", + AdminActionKind::UserUnsuspended => "user_unsuspended", + AdminActionKind::SessionsRevoked => "sessions_revoked", + AdminActionKind::PasswordReset => "password_reset", + AdminActionKind::ProfileCleared => "profile_cleared", + AdminActionKind::UserCreated => "user_created", + AdminActionKind::CommunityDeleted => "community_deleted", + AdminActionKind::OwnershipTransferred => "ownership_transferred", + AdminActionKind::SettingsChanged => "settings_changed", + AdminActionKind::UserRenamed => "user_renamed", + AdminActionKind::UserTimedOut => "user_timed_out", + AdminActionKind::UserBanned => "user_banned", + AdminActionKind::BanRemoved => "ban_removed", + AdminActionKind::InviteCreated => "invite_created", + AdminActionKind::InviteDeleted => "invite_deleted", + AdminActionKind::ReportHandled => "report_handled", + AdminActionKind::MessageDeleted => "message_deleted", + AdminActionKind::UserPurged => "user_purged", + AdminActionKind::VoiceKicked => "voice_kicked", + AdminActionKind::VoiceMuted => "voice_muted", + AdminActionKind::CommunityVoiceSet => "community_voice_set", + AdminActionKind::AttachmentDeleted => "attachment_deleted", + AdminActionKind::GhostEnabled => "ghost_enabled", + AdminActionKind::GhostDisabled => "ghost_disabled", + AdminActionKind::GhostVisit => "ghost_visit", + AdminActionKind::GhostVoice => "ghost_voice", + } + } + + pub fn parse(text: &str) -> Option { + Self::ALL.into_iter().find(|kind| kind.as_str() == text) + } +} + +impl AdminAction { + pub fn kind(&self) -> AdminActionKind { + match self { + AdminAction::RoleChanged { .. } => AdminActionKind::RoleChanged, + AdminAction::UserDeleted => AdminActionKind::UserDeleted, + AdminAction::UserSuspended => AdminActionKind::UserSuspended, + AdminAction::UserUnsuspended => AdminActionKind::UserUnsuspended, + AdminAction::SessionsRevoked => AdminActionKind::SessionsRevoked, + AdminAction::PasswordReset => AdminActionKind::PasswordReset, + AdminAction::ProfileCleared => AdminActionKind::ProfileCleared, + AdminAction::UserCreated => AdminActionKind::UserCreated, + AdminAction::CommunityDeleted => AdminActionKind::CommunityDeleted, + AdminAction::OwnershipTransferred => AdminActionKind::OwnershipTransferred, + AdminAction::SettingsChanged => AdminActionKind::SettingsChanged, + AdminAction::UserRenamed { .. } => AdminActionKind::UserRenamed, + AdminAction::UserTimedOut { .. } => AdminActionKind::UserTimedOut, + AdminAction::UserBanned { .. } => AdminActionKind::UserBanned, + AdminAction::BanRemoved => AdminActionKind::BanRemoved, + AdminAction::InviteCreated => AdminActionKind::InviteCreated, + AdminAction::InviteDeleted => AdminActionKind::InviteDeleted, + AdminAction::ReportHandled { .. } => AdminActionKind::ReportHandled, + AdminAction::MessageDeleted => AdminActionKind::MessageDeleted, + AdminAction::UserPurged { .. } => AdminActionKind::UserPurged, + AdminAction::VoiceKicked => AdminActionKind::VoiceKicked, + AdminAction::VoiceMuted { .. } => AdminActionKind::VoiceMuted, + AdminAction::CommunityVoiceSet { .. } => AdminActionKind::CommunityVoiceSet, + AdminAction::AttachmentDeleted => AdminActionKind::AttachmentDeleted, + AdminAction::GhostEnabled => AdminActionKind::GhostEnabled, + AdminAction::GhostDisabled => AdminActionKind::GhostDisabled, + AdminAction::GhostVisit => AdminActionKind::GhostVisit, + AdminAction::GhostVoice { .. } => AdminActionKind::GhostVoice, + } + } +} -pub fn action_name(action: &AdminAction) -> &'static str { - match action { - AdminAction::RoleChanged { .. } => "role_changed", - AdminAction::UserDeleted => "user_deleted", - AdminAction::UserSuspended => "user_suspended", - AdminAction::UserUnsuspended => "user_unsuspended", - AdminAction::SessionsRevoked => "sessions_revoked", - AdminAction::PasswordReset => "password_reset", - AdminAction::ProfileCleared => "profile_cleared", - AdminAction::UserCreated => "user_created", - AdminAction::CommunityDeleted => "community_deleted", - AdminAction::OwnershipTransferred => "ownership_transferred", - AdminAction::SettingsChanged => "settings_changed", - AdminAction::UserRenamed { .. } => "user_renamed", - AdminAction::UserTimedOut { .. } => "user_timed_out", - AdminAction::UserBanned { .. } => "user_banned", - AdminAction::BanRemoved => "ban_removed", - AdminAction::InviteCreated => "invite_created", - AdminAction::InviteDeleted => "invite_deleted", - AdminAction::ReportHandled { .. } => "report_handled", - AdminAction::MessageDeleted => "message_deleted", - AdminAction::UserPurged { .. } => "user_purged", - AdminAction::VoiceKicked => "voice_kicked", - AdminAction::VoiceMuted { .. } => "voice_muted", - AdminAction::CommunityVoiceSet { .. } => "community_voice_set", - AdminAction::AttachmentDeleted => "attachment_deleted", - AdminAction::GhostEnabled => "ghost_enabled", - AdminAction::GhostDisabled => "ghost_disabled", - AdminAction::GhostVisit => "ghost_visit", - AdminAction::GhostVoice { .. } => "ghost_voice", +const fn action_names() -> [&'static str; 28] { + let mut names = [""; 28]; + let mut index = 0; + while index < 28 { + names[index] = AdminActionKind::ALL[index].as_str(); + index += 1; } + names +} + +pub const ACTION_NAMES: [&str; 28] = action_names(); + +pub fn action_name(action: &AdminAction) -> &'static str { + action.kind().as_str() } pub fn action_detail(action: &AdminAction) -> Option { @@ -275,6 +385,12 @@ pub enum ReportStatus { } impl ReportStatus { + pub const ALL: [Self; 3] = [ + ReportStatus::Open, + ReportStatus::Resolved, + ReportStatus::Dismissed, + ]; + pub fn as_str(self) -> &'static str { match self { ReportStatus::Open => "open", @@ -283,14 +399,17 @@ impl ReportStatus { } } - pub fn parse(text: &str) -> Option { - match text { - "open" => Some(ReportStatus::Open), - "resolved" => Some(ReportStatus::Resolved), - "dismissed" => Some(ReportStatus::Dismissed), - _ => None, + pub fn label(self) -> &'static str { + match self { + ReportStatus::Open => "Open", + ReportStatus::Resolved => "Resolved", + ReportStatus::Dismissed => "Dismissed", } } + + pub fn parse(text: &str) -> Option { + Self::ALL.into_iter().find(|status| status.as_str() == text) + } } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -325,6 +444,27 @@ pub struct ServerSettings { pub logins_per_minute: u32, } +impl Default for ServerSettings { + fn default() -> Self { + Self { + name: "yumush".to_string(), + registration_open: true, + max_attachment_bytes: DEFAULT_MAX_ATTACHMENT_BYTES, + maintenance: false, + user_quota_bytes: 0, + community_quota_bytes: 0, + message_retention_days: 0, + attachment_retention_days: 0, + announcement: String::new(), + max_communities_per_user: 0, + max_message_length: MAXIMUM_MESSAGE_LENGTH as u32, + max_avatar_bytes: MAXIMUM_AVATAR_BYTES as u64, + messages_per_minute: DEFAULT_MESSAGES_PER_MINUTE, + logins_per_minute: DEFAULT_LOGINS_PER_MINUTE, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct AttachmentInfo { pub attachment: Attachment, @@ -354,6 +494,8 @@ pub enum ServerBanKind { } impl ServerBanKind { + pub const ALL: [Self; 2] = [ServerBanKind::Username, ServerBanKind::Ip]; + pub fn as_str(self) -> &'static str { match self { ServerBanKind::Username => "username", @@ -362,11 +504,7 @@ impl ServerBanKind { } pub fn parse(text: &str) -> Option { - match text { - "username" => Some(ServerBanKind::Username), - "ip" => Some(ServerBanKind::Ip), - _ => None, - } + Self::ALL.into_iter().find(|kind| kind.as_str() == text) } } @@ -426,6 +564,13 @@ pub enum AttachmentKind { } impl AttachmentKind { + pub const ALL: [Self; 4] = [ + AttachmentKind::Image, + AttachmentKind::Video, + AttachmentKind::Audio, + AttachmentKind::File, + ]; + pub fn as_str(self) -> &'static str { match self { AttachmentKind::Image => "image", @@ -436,13 +581,7 @@ impl AttachmentKind { } pub fn parse(text: &str) -> Option { - match text { - "image" => Some(AttachmentKind::Image), - "video" => Some(AttachmentKind::Video), - "audio" => Some(AttachmentKind::Audio), - "file" => Some(AttachmentKind::File), - _ => None, - } + Self::ALL.into_iter().find(|kind| kind.as_str() == text) } } diff --git a/crates/common/src/permission.rs b/crates/common/src/permission.rs index 1b4e492..2422b60 100644 --- a/crates/common/src/permission.rs +++ b/crates/common/src/permission.rs @@ -1,5 +1,13 @@ use crate::model::{Rank, Role}; +pub fn is_builder(role: Role) -> bool { + role == Role::Builder +} + +pub fn bypasses_limits(role: Role) -> bool { + is_builder(role) +} + pub fn effective_rank(role: Role, rank: Option) -> Option { match role { Role::Builder => Some(Rank::Builder), @@ -20,7 +28,7 @@ pub fn can_post(actor: Option) -> bool { } pub fn can_join(role: Role, banned: bool) -> bool { - !banned || role == Role::Builder + !banned || is_builder(role) } pub fn can_edit_message(is_author: bool) -> bool { @@ -70,11 +78,11 @@ pub fn can_leave(actor: Option) -> bool { } pub fn can_set_role(actor: Role, is_self: bool) -> bool { - actor == Role::Builder && !is_self + is_builder(actor) && !is_self } pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool { - is_self || (actor == Role::Builder && target != Role::Builder) + is_self || can_manage_user(actor, false, target) } pub fn can_manage_voice(actor: Option) -> bool { @@ -82,7 +90,7 @@ pub fn can_manage_voice(actor: Option) -> bool { } pub fn can_manage_user(actor: Role, is_self: bool, target: Role) -> bool { - actor == Role::Builder && !is_self && target != Role::Builder + is_builder(actor) && !is_self && !is_builder(target) } #[cfg(test)] diff --git a/crates/server/src/admin_log.rs b/crates/server/src/admin_log.rs index ab4a42a..9bf68d8 100644 --- a/crates/server/src/admin_log.rs +++ b/crates/server/src/admin_log.rs @@ -1,57 +1,60 @@ use common::{ - model::{AdminAction, AdminLogEntry, ReportStatus, Role, action_detail, action_name}, + constant::LOG_PAGE_LIMIT, + model::{ + AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail, action_name, + }, time, }; use turso::Connection; -use crate::{database::new_id, error::Error, log::user_at}; +use crate::{database::new_id, error::Error, user}; fn action_of(text: &str, detail: Option) -> Option { - match text { - "role_changed" => Some(AdminAction::RoleChanged { + let kind = AdminActionKind::parse(text)?; + Some(match kind { + AdminActionKind::RoleChanged => AdminAction::RoleChanged { role: Role::parse(&detail?)?, - }), - "user_deleted" => Some(AdminAction::UserDeleted), - "user_suspended" => Some(AdminAction::UserSuspended), - "user_unsuspended" => Some(AdminAction::UserUnsuspended), - "sessions_revoked" => Some(AdminAction::SessionsRevoked), - "password_reset" => Some(AdminAction::PasswordReset), - "profile_cleared" => Some(AdminAction::ProfileCleared), - "user_created" => Some(AdminAction::UserCreated), - "community_deleted" => Some(AdminAction::CommunityDeleted), - "ownership_transferred" => Some(AdminAction::OwnershipTransferred), - "settings_changed" => Some(AdminAction::SettingsChanged), - "user_renamed" => Some(AdminAction::UserRenamed { from: detail? }), - "user_timed_out" => Some(AdminAction::UserTimedOut { + }, + AdminActionKind::UserDeleted => AdminAction::UserDeleted, + AdminActionKind::UserSuspended => AdminAction::UserSuspended, + AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended, + AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked, + AdminActionKind::PasswordReset => AdminAction::PasswordReset, + AdminActionKind::ProfileCleared => AdminAction::ProfileCleared, + AdminActionKind::UserCreated => AdminAction::UserCreated, + AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted, + AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred, + AdminActionKind::SettingsChanged => AdminAction::SettingsChanged, + AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? }, + AdminActionKind::UserTimedOut => AdminAction::UserTimedOut { minutes: detail?.parse().ok()?, - }), - "user_banned" => Some(AdminAction::UserBanned { reason: detail }), - "ban_removed" => Some(AdminAction::BanRemoved), - "invite_created" => Some(AdminAction::InviteCreated), - "invite_deleted" => Some(AdminAction::InviteDeleted), - "report_handled" => Some(AdminAction::ReportHandled { + }, + AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail }, + AdminActionKind::BanRemoved => AdminAction::BanRemoved, + AdminActionKind::InviteCreated => AdminAction::InviteCreated, + AdminActionKind::InviteDeleted => AdminAction::InviteDeleted, + AdminActionKind::ReportHandled => AdminAction::ReportHandled { status: ReportStatus::parse(&detail?)?, - }), - "message_deleted" => Some(AdminAction::MessageDeleted), - "user_purged" => Some(AdminAction::UserPurged { + }, + AdminActionKind::MessageDeleted => AdminAction::MessageDeleted, + AdminActionKind::UserPurged => AdminAction::UserPurged { messages: detail?.parse().ok()?, - }), - "voice_kicked" => Some(AdminAction::VoiceKicked), - "voice_muted" => Some(AdminAction::VoiceMuted { + }, + AdminActionKind::VoiceKicked => AdminAction::VoiceKicked, + AdminActionKind::VoiceMuted => AdminAction::VoiceMuted { muted: detail?.parse().ok()?, - }), - "community_voice_set" => Some(AdminAction::CommunityVoiceSet { + }, + AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet { enabled: detail?.parse().ok()?, - }), - "attachment_deleted" => Some(AdminAction::AttachmentDeleted), - "ghost_enabled" => Some(AdminAction::GhostEnabled), - "ghost_disabled" => Some(AdminAction::GhostDisabled), - "ghost_visit" => Some(AdminAction::GhostVisit), - "ghost_voice" => Some(AdminAction::GhostVoice { + }, + AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted, + AdminActionKind::GhostEnabled => AdminAction::GhostEnabled, + AdminActionKind::GhostDisabled => AdminAction::GhostDisabled, + AdminActionKind::GhostVisit => AdminAction::GhostVisit, + AdminActionKind::GhostVoice => AdminAction::GhostVoice { seconds: detail?.parse().ok()?, - }), - _ => None, - } + }, + }) } pub async fn record( @@ -89,7 +92,7 @@ pub async fn list( ) -> Result, Error> { let mut rows = conn .query( - "SELECT l.id, l.action, l.detail, a.id, a.username, a.role, a.status, a.avatar_id, t.id, t.username, t.role, t.status, t.avatar_id, l.community FROM admin_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.action = ?3) AND (?4 IS NULL OR l.id >= ?4) AND (?5 IS NULL OR l.id < ?5) ORDER BY l.id DESC LIMIT 500", + &format!("SELECT l.id, l.action, l.detail, {}, {}, l.community FROM admin_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.action = ?3) AND (?4 IS NULL OR l.id >= ?4) AND (?5 IS NULL OR l.id < ?5) ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")), ( actor_id, target_id, @@ -108,8 +111,8 @@ pub async fn list( }; entries.push(AdminLogEntry { id: row.get(0)?, - actor: user_at(&row, 3)?, - target: user_at(&row, 8)?, + actor: user::from_row_at(&row, 3)?, + target: user::from_row_at(&row, 8)?, community: row.get(13)?, action, }); diff --git a/crates/server/src/attachment.rs b/crates/server/src/attachment.rs index 465ab13..a790b7d 100644 --- a/crates/server/src/attachment.rs +++ b/crates/server/src/attachment.rs @@ -21,6 +21,7 @@ use common::{ permission, request::{DownloadRequest, UploadHeader}, response::Response, + time::HOUR_MILLIS, validate::{validate_attachment_name, validate_attachment_size}, }; use image::{ImageFormat, ImageReader, Limits}; @@ -37,13 +38,12 @@ use crate::{ community, database::{self, DB, new_id}, error::Error, - log::user_at, request::{actor_rank, ensure}, server_settings, user, }; const COLLECT_INTERVAL: Duration = Duration::from_secs(600); -const STALE_AGE: Duration = Duration::from_secs(3600); +const STALE_AGE: Duration = Duration::from_millis(HOUR_MILLIS); const MAXIMUM_IMAGE_SIDE: u32 = 16384; const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024; const LIST_LIMIT: i64 = 200; @@ -211,7 +211,7 @@ pub async fn all( ) -> Result, Error> { let mut rows = conn .query( - "SELECT a.id, a.name, a.size, a.kind, a.width, a.height, a.community_id, u.id, u.username, u.role, u.status, u.avatar_id FROM attachment a LEFT JOIN user u ON u.id = a.uploader_id WHERE (?1 IS NULL OR a.uploader_id = ?1) AND (?2 IS NULL OR a.community_id = ?2) ORDER BY a.size DESC LIMIT ?3", + &format!("SELECT a.id, a.name, a.size, a.kind, a.width, a.height, a.community_id, {} FROM attachment a LEFT JOIN user u ON u.id = a.uploader_id WHERE (?1 IS NULL OR a.uploader_id = ?1) AND (?2 IS NULL OR a.community_id = ?2) ORDER BY a.size DESC LIMIT ?3", user::user_columns("u")), (user_id, community_id, LIST_LIMIT), ) .await?; @@ -219,7 +219,7 @@ pub async fn all( let mut raw = Vec::new(); while let Some(row) = rows.next().await? { let community_id: String = row.get(6)?; - raw.push((from_row(&row)?, user_at(&row, 7)?, community_id)); + raw.push((from_row(&row)?, user::from_row_at(&row, 7)?, community_id)); } drop(rows); diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 7c8fde8..3223cc1 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -1,8 +1,8 @@ use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use common::{ error::Error as CommonError, - model::{Role, SessionInfo, User}, - time, + model::{SessionInfo, User}, + permission, time, validate::{validate_device, validate_password, validate_username}, }; use turso::Connection; @@ -176,7 +176,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> { if user::suspended(&user.id, conn).await? { return Err(CommonError::Suspended.into()); } - if user.role != Role::Builder && server_settings::read(conn).await?.maintenance { + if !permission::bypasses_limits(user.role) && server_settings::read(conn).await?.maintenance { return Err(CommonError::Maintenance.into()); } @@ -187,7 +187,7 @@ pub async fn resume(token: &str, conn: &Connection) -> Result { let user = { let mut rows = conn .query( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", + &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user::user_columns("user")), (token,), ) .await?; diff --git a/crates/server/src/community.rs b/crates/server/src/community.rs index 558cbdf..384cd7d 100644 --- a/crates/server/src/community.rs +++ b/crates/server/src/community.rs @@ -8,13 +8,15 @@ use turso::{Connection, Row}; use crate::{database::new_id, error::Error, user}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Kind { +pub enum Kind { Group, Direct, } impl Kind { - fn as_str(self) -> &'static str { + const ALL: [Self; 2] = [Kind::Group, Kind::Direct]; + + pub fn as_str(self) -> &'static str { match self { Kind::Group => "group", Kind::Direct => "direct", @@ -22,11 +24,7 @@ impl Kind { } fn parse(text: &str) -> Option { - match text { - "group" => Some(Kind::Group), - "direct" => Some(Kind::Direct), - _ => None, - } + Self::ALL.into_iter().find(|kind| kind.as_str() == text) } } @@ -49,7 +47,7 @@ fn raw_of(row: &Row) -> Result { async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM direct JOIN user ON user.id = CASE WHEN direct.user_a = ?2 THEN direct.user_b ELSE direct.user_a END WHERE direct.community_id = ?1", + &format!("SELECT {} FROM direct JOIN user ON user.id = CASE WHEN direct.user_a = ?2 THEN direct.user_b ELSE direct.user_a END WHERE direct.community_id = ?1", user::user_columns("user")), (community_id, viewer_id), ) .await?; @@ -282,8 +280,8 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result Result { let mut rows = conn .query( - "SELECT CASE WHEN kind = 'direct' THEN 'DM' ELSE name END FROM community WHERE id = ?1", - (community_id,), + "SELECT CASE WHEN kind = ?2 THEN 'DM' ELSE name END FROM community WHERE id = ?1", + (community_id, Kind::Direct.as_str()), ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; diff --git a/crates/server/src/friend.rs b/crates/server/src/friend.rs index bc670b9..4e7dd2c 100644 --- a/crates/server/src/friend.rs +++ b/crates/server/src/friend.rs @@ -73,19 +73,19 @@ async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error> pub async fn state(user_id: &str, conn: &Connection) -> Result { Ok(Friends { friends: users( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 ORDER BY user.id", + &format!("SELECT {} FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 ORDER BY user.id", user::user_columns("user")), user_id, conn, ) .await?, incoming: users( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM user JOIN friend_request ON friend_request.from_id = user.id WHERE friend_request.to_id = ?1 ORDER BY user.id", + &format!("SELECT {} FROM user JOIN friend_request ON friend_request.from_id = user.id WHERE friend_request.to_id = ?1 ORDER BY user.id", user::user_columns("user")), user_id, conn, ) .await?, outgoing: users( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM user JOIN friend_request ON friend_request.to_id = user.id WHERE friend_request.from_id = ?1 ORDER BY user.id", + &format!("SELECT {} FROM user JOIN friend_request ON friend_request.to_id = user.id WHERE friend_request.from_id = ?1 ORDER BY user.id", user::user_columns("user")), user_id, conn, ) diff --git a/crates/server/src/invite.rs b/crates/server/src/invite.rs index f9ea1d6..d6e97d3 100644 --- a/crates/server/src/invite.rs +++ b/crates/server/src/invite.rs @@ -5,7 +5,7 @@ use common::{ }; use turso::Connection; -use crate::{error::Error, log::user_at}; +use crate::{error::Error, user}; const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; const CODE_LENGTH: usize = 8; @@ -50,7 +50,7 @@ pub async fn create( pub async fn list(conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT c.code, c.uses_left, c.expires_at, u.id, u.username, u.role, u.status, u.avatar_id FROM invite_code c LEFT JOIN user u ON u.id = c.created_by", + &format!("SELECT c.code, c.uses_left, c.expires_at, {} FROM invite_code c LEFT JOIN user u ON u.id = c.created_by", user::user_columns("u")), (), ) .await?; @@ -63,7 +63,7 @@ pub async fn list(conn: &Connection) -> Result, Error> { code: row.get(0)?, uses_left: uses_left as u32, expires_at: expires_at.map(|millis| millis as u64), - created_by: user_at(&row, 3)?, + created_by: user::from_row_at(&row, 3)?, }); } diff --git a/crates/server/src/log.rs b/crates/server/src/log.rs index 467fcca..43fcd61 100644 --- a/crates/server/src/log.rs +++ b/crates/server/src/log.rs @@ -1,10 +1,10 @@ use common::{ - error::Error as CommonError, - model::{LogAction, LogEntry, Rank, Role, User}, + constant::LOG_PAGE_LIMIT, + model::{LogAction, LogEntry, Rank}, }; -use turso::{Connection, Row}; +use turso::Connection; -use crate::{database::new_id, error::Error}; +use crate::{database::new_id, error::Error, user}; fn parts(action: &LogAction) -> (&'static str, Option) { match action { @@ -43,21 +43,6 @@ fn action_of(text: &str, detail: Option) -> Option { } } -pub fn user_at(row: &Row, start: usize) -> Result, Error> { - let Some(id) = row.get::>(start)? else { - return Ok(None); - }; - let role: String = row.get(start + 2)?; - - Ok(Some(User { - id, - username: row.get(start + 1)?, - role: Role::parse(&role).ok_or(CommonError::Server)?, - status: row.get(start + 3)?, - avatar_id: row.get(start + 4)?, - })) -} - pub async fn record( community_id: &str, actor_id: Option<&str>, @@ -79,7 +64,7 @@ pub async fn record( pub async fn list(community_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT l.id, l.action, l.detail, a.id, a.username, a.role, a.status, a.avatar_id, t.id, t.username, t.role, t.status, t.avatar_id FROM community_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE l.community_id = ?1 ORDER BY l.id DESC LIMIT 500", + &format!("SELECT l.id, l.action, l.detail, {}, {} FROM community_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE l.community_id = ?1 ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")), (community_id,), ) .await?; @@ -92,8 +77,8 @@ pub async fn list(community_id: &str, conn: &Connection) -> Result }; entries.push(LogEntry { id: row.get(0)?, - actor: user_at(&row, 3)?, - target: user_at(&row, 8)?, + actor: user::from_row_at(&row, 3)?, + target: user::from_row_at(&row, 8)?, action, }); } diff --git a/crates/server/src/overview.rs b/crates/server/src/overview.rs index 5742c74..fd7d631 100644 --- a/crates/server/src/overview.rs +++ b/crates/server/src/overview.rs @@ -1,7 +1,7 @@ -use common::model::Overview; +use common::model::{Overview, Role}; use turso::Connection; -use crate::{error::Error, network::Presence, voice::Voice}; +use crate::{community::Kind, error::Error, network::Presence, voice::Voice}; pub async fn read( presence: &Presence, @@ -12,12 +12,12 @@ pub async fn read( .query( "SELECT (SELECT COUNT(*) FROM user), - (SELECT COUNT(*) FROM user WHERE role = 'builder'), - (SELECT COUNT(*) FROM community WHERE kind != 'direct'), + (SELECT COUNT(*) FROM user WHERE role = ?1), + (SELECT COUNT(*) FROM community WHERE kind != ?2), (SELECT COALESCE(SUM(size), 0) FROM attachment) + (SELECT COALESCE(SUM(length(data)), 0) FROM avatar) + (SELECT COALESCE(SUM(length(data)), 0) FROM community_avatar)", - (), + (Role::Builder.as_str(), Kind::Direct.as_str()), ) .await?; let row = rows diff --git a/crates/server/src/report.rs b/crates/server/src/report.rs index ec771d3..4b42f48 100644 --- a/crates/server/src/report.rs +++ b/crates/server/src/report.rs @@ -1,10 +1,11 @@ use common::{ + constant::LOG_PAGE_LIMIT, error::Error as CommonError, model::{Report, ReportStatus}, }; use turso::Connection; -use crate::{database::new_id, error::Error, log::user_at}; +use crate::{database::new_id, error::Error, user}; pub async fn is_open( reporter_id: &str, @@ -14,8 +15,8 @@ pub async fn is_open( ) -> Result { let mut rows = conn .query( - "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND COALESCE(message_id, '') = COALESCE(?3, '') AND status = 'open')", - (reporter_id, target_id, message_id), + "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND COALESCE(message_id, '') = COALESCE(?3, '') AND status = ?4)", + (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), ) .await?; let row = rows @@ -48,7 +49,7 @@ pub async fn insert( pub async fn list(status: Option, conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT r.id, rp.id, rp.username, rp.role, rp.status, rp.avatar_id, t.id, t.username, t.role, t.status, t.avatar_id, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, h.id, h.username, h.role, h.status, h.avatar_id FROM report r LEFT JOIN user rp ON rp.id = r.reporter_id LEFT JOIN user t ON t.id = r.target_id LEFT JOIN community c ON c.id = r.community_id LEFT JOIN user h ON h.id = r.handled_by WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT 500", + &format!("SELECT r.id, {}, {}, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, {} FROM report r LEFT JOIN user rp ON rp.id = r.reporter_id LEFT JOIN user t ON t.id = r.target_id LEFT JOIN community c ON c.id = r.community_id LEFT JOIN user h ON h.id = r.handled_by WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("rp"), user::user_columns("t"), user::user_columns("h")), (status.map(ReportStatus::as_str),), ) .await?; @@ -58,15 +59,15 @@ pub async fn list(status: Option, conn: &Connection) -> Result Result, Error> { let mut rows = conn .query( - "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = 'open' RETURNING target_id", - (report_id, status.as_str(), handled_by), + "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", + (report_id, status.as_str(), handled_by, ReportStatus::Open.as_str()), ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 0bff667..b1bc63a 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -8,7 +8,7 @@ use common::{ error::Error as CommonError, event::Event, model::{ - AdminAction, CommunityKind, CommunitySummary, LogAction, Member, Rank, ReportStatus, Role, + AdminAction, CommunityKind, CommunitySummary, LogAction, Member, Rank, ReportStatus, ServerBanKind, ServerSettings, User, VoiceRoom, }, permission, @@ -138,7 +138,7 @@ async fn dispatch( ), Request::UpdateServerSettings { settings } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; validate_server_settings(&settings)?; let previous = server_settings::read(&conn).await?; server_settings::update(&settings, &conn).await?; @@ -216,7 +216,7 @@ async fn dispatch( } Request::CreateUser { username, password } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; let user = authentication::create_account(&username, &password, &conn).await?; admin_log::record( Some(&me.id), @@ -230,7 +230,7 @@ async fn dispatch( } Request::Users => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; (Response::Users(user::all(&conn).await?), Vec::new()) } Request::AdminLogs { @@ -241,7 +241,7 @@ async fn dispatch( before_ms, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::AdminLogs( admin_log::list( @@ -259,7 +259,7 @@ async fn dispatch( } Request::DailyStats { days } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::DailyStats(stats::daily(days, &conn).await?), Vec::new(), @@ -267,7 +267,7 @@ async fn dispatch( } Request::Overview => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::Overview(overview::read(presence, voice, &conn).await?), Vec::new(), @@ -407,7 +407,7 @@ async fn dispatch( ))?; let tx = conn.transaction().await?; let mut broadcasts = Vec::new(); - if me.role == Role::Builder && me.id != user_id { + if permission::is_builder(me.role) && me.id != user_id { admin_log::record( Some(&me.id), Some(&user_id), @@ -514,7 +514,7 @@ async fn dispatch( let owned = user_community::rank(&me.id, &community_id, &tx).await? == Some(Rank::Owner); let deleted = community::delete(&community_id, &me.id, &tx).await?; - if me.role == Role::Builder && !owned { + if permission::is_builder(me.role) && !owned { admin_log::record( Some(&me.id), None, @@ -765,7 +765,7 @@ async fn dispatch( ) .await?; } - if me.role == Role::Builder && existing.user_id != me.id { + if permission::is_builder(me.role) && existing.user_id != me.id { let community = community::label(&deleted.community_id, &conn).await?; admin_log::record( Some(&me.id), @@ -789,7 +789,7 @@ async fn dispatch( actor_rank(&me, &community_id, &conn).await?, ))?; let visit = before.is_none() - && me.role == Role::Builder + && permission::is_builder(me.role) && user_community::rank(&me.id, &community_id, &conn) .await? .is_none() @@ -993,7 +993,7 @@ async fn dispatch( } Request::AllCommunities => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; let mut summaries = Vec::new(); for community in community::groups(&conn).await? { let members = user_community::members(&community.id, &conn).await?; @@ -1048,7 +1048,7 @@ async fn dispatch( &tx, ) .await?; - if me.role == Role::Builder { + if permission::is_builder(me.role) { let community = community::read(&community_id, &me.id, &tx).await?; admin_log::record( Some(&me.id), @@ -1127,7 +1127,7 @@ async fn dispatch( } Request::ServerBans => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::ServerBans(server_ban::list(&conn).await?), Vec::new(), @@ -1135,21 +1135,21 @@ async fn dispatch( } Request::RemoveServerBan { id } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; server_ban::remove(&id, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?; (Response::Done, Vec::new()) } Request::CreateInviteCode { uses, hours } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder && uses > 0)?; + ensure(permission::is_builder(me.role) && uses > 0)?; let code = invite::create(uses, hours, &me, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?; (Response::InviteCode(code), Vec::new()) } Request::InviteCodes => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::InviteCodes(invite::list(&conn).await?), Vec::new(), @@ -1157,7 +1157,7 @@ async fn dispatch( } Request::DeleteInviteCode { code } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; invite::delete(&code, &conn).await?; admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?; (Response::Done, Vec::new()) @@ -1194,7 +1194,7 @@ async fn dispatch( } Request::Reports { status } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::Reports(report::list(status, &conn).await?), Vec::new(), @@ -1202,7 +1202,7 @@ async fn dispatch( } Request::HandleReport { report_id, status } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder && status != ReportStatus::Open)?; + ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?; let target = report::handle(&report_id, status, &me.id, &conn).await?; admin_log::record( Some(&me.id), @@ -1222,7 +1222,7 @@ async fn dispatch( before_ms, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; let hits = message::search( text.as_deref(), user_id.as_deref(), @@ -1273,7 +1273,7 @@ async fn dispatch( community_id, } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::AttachmentInfos( attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?, @@ -1283,7 +1283,7 @@ async fn dispatch( } Request::DeleteAttachment { attachment_id } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; let stored = attachment::read(&attachment_id, &conn).await?; let community = community::label(&stored.community_id, &conn).await?; let tx = conn.transaction().await?; @@ -1308,13 +1308,13 @@ async fn dispatch( } Request::StorageUsage => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; let (users, communities) = attachment::usage(&conn).await?; (Response::StorageUsage { users, communities }, Vec::new()) } Request::VoiceRooms => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; ( Response::VoiceRooms(voice_rooms(voice, &conn).await?), Vec::new(), @@ -1376,7 +1376,7 @@ async fn dispatch( let tx = conn.transaction().await?; community::set_voice_enabled(&community_id, enabled, &tx).await?; let updated = community::read(&community_id, &me.id, &tx).await?; - if me.role == Role::Builder { + if permission::is_builder(me.role) { admin_log::record( Some(&me.id), None, @@ -1399,7 +1399,7 @@ async fn dispatch( } Request::SetGhost { enabled } => { let (me, _) = authenticated(state, &conn).await?; - ensure(me.role == Role::Builder)?; + ensure(permission::is_builder(me.role))?; user::set_ghost(&me.id, enabled, &conn).await?; let action = if enabled { AdminAction::GhostEnabled @@ -1524,7 +1524,7 @@ fn limit_messages( rate_limit: &RateLimit, settings: &ServerSettings, ) -> Result<(), Error> { - if me.role == Role::Builder { + if permission::bypasses_limits(me.role) { return Ok(()); } diff --git a/crates/server/src/retention.rs b/crates/server/src/retention.rs index a410166..2ad9177 100644 --- a/crates/server/src/retention.rs +++ b/crates/server/src/retention.rs @@ -14,7 +14,7 @@ use crate::{ message, server_settings, }; -const SWEEP_INTERVAL: Duration = Duration::from_secs(3600); +const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); const BATCH_SIZE: i64 = 500; pub async fn collect(db: DB, directory: PathBuf) { diff --git a/crates/server/src/server_ban.rs b/crates/server/src/server_ban.rs index be4d7a3..4a75e78 100644 --- a/crates/server/src/server_ban.rs +++ b/crates/server/src/server_ban.rs @@ -4,7 +4,7 @@ use common::{ }; use turso::Connection; -use crate::{database::new_id, error::Error, log::user_at}; +use crate::{database::new_id, error::Error, user}; pub async fn insert( kind: ServerBanKind, @@ -26,7 +26,7 @@ pub async fn insert( pub async fn list(conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT b.id, b.kind, b.value, b.reason, u.id, u.username, u.role, u.status, u.avatar_id FROM server_ban b LEFT JOIN user u ON u.id = b.created_by ORDER BY b.kind, b.value", + &format!("SELECT b.id, b.kind, b.value, b.reason, {} FROM server_ban b LEFT JOIN user u ON u.id = b.created_by ORDER BY b.kind, b.value", user::user_columns("u")), (), ) .await?; @@ -39,7 +39,7 @@ pub async fn list(conn: &Connection) -> Result, Error> { kind: ServerBanKind::parse(&text).ok_or(CommonError::Server)?, value: row.get(2)?, reason: row.get(3)?, - created_by: user_at(&row, 4)?, + created_by: user::from_row_at(&row, 4)?, }); } diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index 0ec5e71..61ac3dc 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -10,26 +10,33 @@ use turso::{Connection, Row}; use crate::{database::new_id, error::Error}; -pub fn from_row(row: &Row) -> Result { - Ok(User { - id: row.get(0)?, - username: row.get(1)?, - role: role_of(row)?, - status: row.get(3)?, - avatar_id: row.get(4)?, - }) +pub fn user_columns(alias: &str) -> String { + format!("{alias}.id, {alias}.username, {alias}.role, {alias}.status, {alias}.avatar_id") } -fn role_of(row: &Row) -> Result { - let text: String = row.get(2)?; +pub fn from_row_at(row: &Row, start: usize) -> Result, Error> { + let Some(id) = row.get::>(start)? else { + return Ok(None); + }; + let role: String = row.get(start + 2)?; + + Ok(Some(User { + id, + username: row.get(start + 1)?, + role: Role::parse(&role).ok_or(CommonError::Server)?, + status: row.get(start + 3)?, + avatar_id: row.get(start + 4)?, + })) +} - Ok(Role::parse(&text).ok_or(CommonError::Server)?) +pub fn from_row(row: &Row) -> Result { + Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?) } pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING id, username, role, status, avatar_id", + &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")), ( new_id(), username, @@ -47,7 +54,7 @@ pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> R pub async fn read(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "SELECT id, username, role, status, avatar_id FROM user WHERE id = ?1", + &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")), (user_id,), ) .await?; @@ -70,7 +77,7 @@ pub async fn any(conn: &Connection) -> Result { pub async fn by_username(username: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1 COLLATE NOCASE", + &format!("SELECT {} FROM user WHERE username = ?1 COLLATE NOCASE", user_columns("user")), (username,), ) .await?; @@ -84,7 +91,7 @@ pub async fn credentials( ) -> Result, Error> { let mut rows = conn .query( - "SELECT id, username, role, status, avatar_id, password_hash FROM user WHERE username = ?1", + &format!("SELECT {}, password_hash FROM user WHERE username = ?1", user_columns("user")), (username,), ) .await?; @@ -107,7 +114,7 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result< let mut rows = conn .query( - "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id", + &format!("UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), (user_id, username), ) .await?; @@ -121,7 +128,7 @@ pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Re let mut rows = conn .query( - "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id", + &format!("UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), (user_id, status), ) .await?; @@ -179,7 +186,7 @@ async fn set_avatar_id( ) -> Result { let mut rows = conn .query( - "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id", + &format!("UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), (user_id, avatar_id), ) .await?; @@ -203,7 +210,7 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result, Error pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result { let mut rows = conn .query( - "UPDATE user SET role = ?2 WHERE username = ?1 RETURNING id, username, role, status, avatar_id", + &format!("UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}", user_columns("user")), (username, role.as_str()), ) .await?; @@ -215,7 +222,7 @@ pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result Result { let mut rows = conn .query( - "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id", + &format!("UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}", user_columns("user")), (user_id, role.as_str()), ) .await?; @@ -270,7 +277,10 @@ pub async fn last_ip(user_id: &str, conn: &Connection) -> Result, pub async fn builder_ids(conn: &Connection) -> Result, Error> { let mut rows = conn - .query("SELECT id FROM user WHERE role = 'builder'", ()) + .query( + "SELECT id FROM user WHERE role = ?1", + (Role::Builder.as_str(),), + ) .await?; let mut ids = Vec::new(); while let Some(row) = rows.next().await? { @@ -349,7 +359,7 @@ pub async fn set_password_hash( pub async fn all(conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT id, username, role, status, avatar_id, suspended, last_seen, suspended_until, ghost FROM user ORDER BY username COLLATE NOCASE", + &format!("SELECT {}, suspended, last_seen, suspended_until, ghost FROM user ORDER BY username COLLATE NOCASE", user_columns("user")), (), ) .await?; @@ -374,7 +384,7 @@ pub async fn all(conn: &Connection) -> Result, Error> { pub async fn delete(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "DELETE FROM user WHERE id = ?1 RETURNING id, username, role, status, avatar_id", + &format!("DELETE FROM user WHERE id = ?1 RETURNING {}", user_columns("user")), (user_id,), ) .await?; diff --git a/crates/server/src/user_community.rs b/crates/server/src/user_community.rs index e00aa9b..9924293 100644 --- a/crates/server/src/user_community.rs +++ b/crates/server/src/user_community.rs @@ -74,7 +74,7 @@ pub async fn set_rank( pub async fn members(community_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id, user_community.rank FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", + &format!("SELECT {}, user_community.rank FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id", user::user_columns("user")), (community_id,), ) .await?; @@ -151,7 +151,7 @@ pub async fn is_banned( pub async fn bans(community_id: &str, conn: &Connection) -> Result, Error> { let mut rows = conn .query( - "SELECT user.id, user.username, user.role, user.status, user.avatar_id, ban.reason FROM user JOIN ban ON ban.user_id = user.id WHERE ban.community_id = ?1 ORDER BY ban.rowid DESC", + &format!("SELECT {}, ban.reason FROM user JOIN ban ON ban.user_id = user.id WHERE ban.community_id = ?1 ORDER BY ban.rowid DESC", user::user_columns("user")), (community_id,), ) .await?;