From 3950bc853afeffb8254d060622b8a3d49a5b5620 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 24 Nov 2026 22:40:09 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20add=20user=20admin,=20font?= =?UTF-8?q?=20size,=20music=20voice=20profile=20and=20adaptive=20jitter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Admin: staff get a users page with search and role changes through new Users and SetRole requests. The first account created becomes staff, and username lookup ignores case. Settings: a font size choice (small, medium, large) next to the theme. A voice profile picks Voice (Opus VoIP, 48 kb/s) or Music (Opus Audio, 96 kb/s). Voice: capture opens a mono stream instead of downmixing stereo. The jitter buffer sizes itself from measured arrival jitter, recovers lost packets with FEC or concealment, skips quiet frames to absorb drift and fades the gate in and out. New request and response variants are appended to keep wire indices stable. --- .gitignore | 2 + crates/client/src/gui.rs | 36 +++- crates/client/src/gui/admin.rs | 217 ++++++++++++++++++++ crates/client/src/gui/auth.rs | 60 +++--- crates/client/src/gui/chat.rs | 36 ++-- crates/client/src/gui/community_settings.rs | 23 ++- crates/client/src/gui/composer.rs | 5 +- crates/client/src/gui/forward.rs | 3 +- crates/client/src/gui/media_view.rs | 11 +- crates/client/src/gui/message_actions.rs | 5 +- crates/client/src/gui/profile.rs | 9 +- crates/client/src/gui/settings_page.rs | 121 +++++++---- crates/client/src/gui/sidebar.rs | 101 +++++---- crates/client/src/gui/snippet.rs | 7 +- crates/client/src/gui/social.rs | 7 +- crates/client/src/gui/voice_settings.rs | 18 +- crates/client/src/main.rs | 2 +- crates/client/src/network.rs | 23 ++- crates/client/src/settings.rs | 66 +++++- crates/client/src/voice/audio/pipewire.rs | 33 +-- crates/client/src/voice/engine.rs | 140 ++++++++++--- crates/client/src/voice/mod.rs | 1 + crates/common/src/constant.rs | 3 +- crates/common/src/permission.rs | 4 + crates/common/src/request.rs | 7 +- crates/common/src/response.rs | 1 + crates/server/src/request.rs | 119 ++++++----- crates/server/src/user.rs | 41 +++- 28 files changed, 837 insertions(+), 264 deletions(-) create mode 100644 crates/client/src/gui/admin.rs diff --git a/.gitignore b/.gitignore index 7eb3910..b765c78 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ /target Cargo.lock configs/server_config.toml +*.pem +yumush.db* diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index b821650..b61245e 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -13,7 +13,7 @@ use common::{ use gpui_kit::{ AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, - KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Render, RenderOnce, Stateful, + KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful, StatefulInteractiveElement, Styled, WeakEntity, Window, actions, base::Selectable, component::{ @@ -21,7 +21,7 @@ use gpui_kit::{ input::{Input, InputEvent, InputState}, notification::Notification, }, - div, hsla, img, px, rgb, + div, hsla, img, px, rems, rgb, }; use jiff::{Timestamp, tz::TimeZone}; use tokio::sync::mpsc; @@ -30,9 +30,10 @@ use uuid::Uuid; use crate::{ accounts::{self, Accounts}, network::{NetworkEvent, NetworkHandle}, - settings::{Look, Settings, ThemeChoice}, + settings::{Look, Scale, Settings, ThemeChoice}, }; +mod admin; mod auth; mod chat; mod community_settings; @@ -53,6 +54,12 @@ use voice_settings::VoiceControls; actions!(yumush, [FocusFind, CloseSettings]); +pub const BASE_FONT: f32 = 14.; + +pub fn text(size: f32) -> Rems { + rems(size / BASE_FONT) +} + const TINTS: [u32; 10] = [ 0x10b981, 0xa855f7, 0xf59e0b, 0xf97316, 0xec4899, 0x0ea5e9, 0x22c55e, 0xef4444, 0x06b6d4, 0xd946ef, @@ -159,6 +166,7 @@ pub fn sync_accent(accent: Hsla, cx: &mut App) { pub fn sync_theme(cx: &mut App) { let palette = palette(cx); + let font_size = cx.global::().0.pixels(); let theme = Theme::global_mut(cx); let colors = &mut theme.colors; @@ -185,7 +193,7 @@ pub fn sync_theme(cx: &mut App) { theme.tokens = (&theme.colors).into(); theme.radius = px(6.); theme.radius_lg = px(10.); - theme.font_size = px(14.); + theme.font_size = font_size; theme.focus_ring = false; } @@ -198,7 +206,7 @@ pub fn tint(id: &str) -> Hsla { rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into() } -pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Pixels) -> Div { +pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Rems) -> Div { let initial = name .chars() .next() @@ -223,7 +231,7 @@ pub fn avatar( palette: Palette, user: &User, size: Pixels, - font: Pixels, + font: Rems, avatars: &HashMap>, ) -> Div { let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else { @@ -249,7 +257,7 @@ pub fn community_icon( palette: Palette, community: &Community, size: Pixels, - font: Pixels, + font: Rems, avatars: &HashMap>, ) -> Div { match &community.kind { @@ -325,7 +333,7 @@ impl Render for Tip { .border_color(palette.border) .bg(palette.panel) .text_color(palette.text) - .text_size(px(12.)) + .text_size(text(12.)) .child(self.0) } } @@ -394,7 +402,7 @@ pub fn rank_tag(rank: Option, palette: Palette) -> Option
{ .py(px(1.)) .rounded(px(4.)) .bg(palette.hover) - .text_size(px(11.)) + .text_size(text(11.)) .text_color(color) .child(label), ) @@ -598,6 +606,9 @@ impl Yumush { .status_input .update(cx, |input, cx| input.set_value(status, window, cx)); } + if view == View::Admin { + self.load_users(window, cx); + } if view == View::CommunitySettings { let name = self .chat @@ -620,7 +631,7 @@ impl Yumush { pub fn themed(&self, cx: &App) -> Palette { let community = match self.chat.view { - View::Settings => None, + View::Settings | View::Admin => None, _ => self.chat.selected_community(), }; palette(cx).for_community(community, &self.chat.hues) @@ -673,6 +684,9 @@ impl Yumush { if self.is_me(&user.id) { self.user = Some(user.clone()); self.accounts.rename(user); + if !self.is_staff() && self.chat.view == View::Admin { + self.chat.view = View::Chat; + } } self.request_user_avatar(user, cx); } @@ -848,7 +862,7 @@ impl Render for Yumush { .size_full() .bg(palette.window) .text_color(palette.text) - .text_size(px(13.)) + .text_size(text(13.)) .track_focus(&self.focus) .on_action( cx.listener(|this, _: &FocusFind, window, cx| this.chat.focus_find(window, cx)), diff --git a/crates/client/src/gui/admin.rs b/crates/client/src/gui/admin.rs new file mode 100644 index 0000000..351a4d4 --- /dev/null +++ b/crates/client/src/gui/admin.rs @@ -0,0 +1,217 @@ +use super::text; +use common::{ + model::{Role, User}, + permission, +}; +use gpui_kit::{ + App, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, component::input::Input, + div, prelude::FluentBuilder as _, px, +}; + +use super::{ + Palette, Yumush, avatar, clickable, + community_settings::search_text, + entity_action, notify_error, + settings_page::{page, section}, +}; + +impl Yumush { + pub(super) fn is_staff(&self) -> bool { + self.user.as_ref().is_some_and(|me| me.role == Role::Staff) + } + + pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context) { + if !self.is_staff() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let users = match network.users().await { + Ok(users) => users, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + for user in &users { + yumush.request_user_avatar(user, cx); + } + yumush.chat.admin_users = users; + cx.notify(); + }); + }) + .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.id == user.id); + if let Some(index) = index { + yumush.chat.admin_users[index] = 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(|user| user.id != user_id); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn admin_page( + &self, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> impl IntoElement { + 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(|user| user.username.to_lowercase().contains(query.as_str())) + .map(|user| self.admin_row(user, me, entity, palette)) + .collect(), + None => Vec::new(), + }; + + page( + "admin_scroll", + entity, + palette, + "Admin", + vec![ + div() + .child(Input::new(&self.chat.admin_search)) + .into_any_element(), + section("Users", palette, rows).into_any_element(), + ], + ) + } + + fn admin_row(&self, user: &User, me: &User, entity: &Entity, palette: Palette) -> Div { + let is_self = user.id == me.id; + let staff = user.role == Role::Staff; + 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 next_role = if staff { Role::User } else { Role::Staff }; + + let role_button = clickable( + format!("role_{}", user.id), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_admin_role(&role_id, next_role, window, cx) + }), + ) + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_size(text(13.)) + .text_color(palette.muted) + .child(if staff { "Remove staff" } else { "Make staff" }); + + let delete_button = clickable( + format!("delete_user_{}", user.id), + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_admin_user(&delete_id, window, cx) + }), + ) + .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_delete, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) + .child(if pending_delete { "Confirm" } else { "Delete" }); + + 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(staff, |this| { + this.child( + div() + .text_size(text(11.)) + .text_color(palette.accent) + .child("Staff"), + ) + }), + ) + .children(permission::can_set_role(me.role, is_self).then_some(role_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/auth.rs b/crates/client/src/gui/auth.rs index 874b86c..8d0ada8 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -1,9 +1,11 @@ +use super::{ + settings_page::{segment, segment_track}, + text, +}; use gpui_kit::{ Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, component::input::{Input, InputEvent, InputState}, - div, - prelude::FluentBuilder as _, - px, + div, px, }; use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon}; @@ -75,6 +77,14 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { } pub(super) fn field(palette: Palette, input: &Entity) -> Div { + frame(palette, Input::new(input)) +} + +fn password_field(palette: Palette, input: &Entity) -> Div { + frame(palette, Input::new(input).mask_toggle()) +} + +fn frame(palette: Palette, input: Input) -> Div { div() .h(px(32.)) .flex() @@ -84,7 +94,7 @@ pub(super) fn field(palette: Palette, input: &Entity) -> Div { .border_color(palette.border) .bg(palette.field) .child( - Input::new(input) + input .appearance(false) .text_color(palette.text) .flex_1() @@ -113,12 +123,7 @@ impl Yumush { .font_weight(FontWeight::MEDIUM) .child(action_label); - let tabs = div() - .flex() - .p(px(3.)) - .gap(px(3.)) - .rounded(px(8.)) - .bg(palette.window) + let tabs = segment_track(palette) .child(tab(palette, &entity, Route::Login, "Log in", route)) .child(tab(palette, &entity, Route::Register, "Register", route)); @@ -141,14 +146,14 @@ impl Yumush { .bg(palette.panel) .child( div() - .text_size(px(18.)) + .text_size(text(18.)) .font_weight(FontWeight::SEMIBOLD) .child("yumush"), ) .children(self.saved_accounts(&entity, palette)) .child(tabs) .child(field(palette, &self.auth.username_input)) - .child(field(palette, &self.auth.password_input)) + .child(password_field(palette, &self.auth.password_input)) .child(action_button), ) } @@ -184,7 +189,7 @@ impl Yumush { &account.user_id, &account.username, px(22.), - px(11.), + text(11.), ) .rounded_full(), ) @@ -231,27 +236,14 @@ fn tab( route: Route, ) -> impl IntoElement { let entity = entity.clone(); - let active = route == target; - clickable(label, palette, move |window, cx| { - entity.update(cx, |this, cx| this.change_page(target, window, cx)); - }) + segment( + clickable(label, palette, move |window, cx| { + entity.update(cx, |this, cx| this.change_page(target, window, cx)); + }), + route == target, + palette, + ) .flex_1() - .flex() - .justify_center() - .py(px(4.)) - .rounded(px(6.)) - .text_size(px(12.)) - .when(active, |tab| { - tab.bg(palette.panel) - .border_1() - .border_color(palette.border) - .text_color(palette.text) - .font_weight(FontWeight::MEDIUM) - }) - .when(!active, |tab| { - tab.border_1() - .border_color(palette.window) - .text_color(palette.muted) - }) + .text_size(text(12.)) .child(label) } diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index b3d6d63..9aa9657 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,3 +1,4 @@ +use super::text; use std::{ collections::{HashMap, HashSet}, sync::Arc, @@ -46,6 +47,7 @@ pub enum View { Chat, Settings, CommunitySettings, + Admin, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -113,6 +115,9 @@ 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) admin_search: Entity, pub(super) voice: HashMap>, pub(super) voice_state: VoiceState, pub(super) speaking: HashSet, @@ -149,7 +154,8 @@ impl Chat { let ban_search = new_input("Search...", window, cx); let log_search = new_input("Search...", window, cx); - for search in [&ban_search, &log_search] { + let admin_search = new_input("Search...", window, cx); + for search in [&ban_search, &log_search, &admin_search] { cx.subscribe_in(search, window, |_, _, event, window, cx| { if matches!(event, InputEvent::Change) { window.refresh(); @@ -191,6 +197,9 @@ impl Chat { user_requests: HashSet::new(), delete_step: DeleteStep::Idle, pending_user_delete: None, + pending_admin_delete: None, + admin_users: vec![], + admin_search, voice: HashMap::new(), voice_state: VoiceState::Off, speaking: HashSet::new(), @@ -531,6 +540,8 @@ impl Chat { self.found = None; self.select(None); self.unread.clear(); + self.admin_users.clear(); + self.pending_admin_delete = None; self.view = View::Chat; self.delete_step = DeleteStep::Idle; self.voice.clear(); @@ -591,7 +602,7 @@ fn empty_state(palette: Palette) -> impl IntoElement { .rounded(px(4.)) .border_1() .border_color(palette.border) - .text_size(px(11.)) + .text_size(text(11.)) .child(FIND_HINT), ) .child("Find a user") @@ -648,7 +659,7 @@ impl RenderOnce for MembersTrigger { .take(3) .enumerate() .map(|(index, user)| { - avatar(palette, user, px(18.), px(9.), &self.avatars) + avatar(palette, user, px(18.), text(9.), &self.avatars) .border_2() .border_color(palette.panel) .when(index > 0, |this| this.ml(px(-6.))) @@ -663,7 +674,7 @@ impl RenderOnce for MembersTrigger { .items_center() .gap(px(6.)) .rounded(px(6.)) - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(div().flex().children(avatars)) .child(self.members.len().to_string()), @@ -702,6 +713,7 @@ impl Yumush { .bg(palette.panel) .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::CommunitySettings => { panel.child(self.community_settings_page(entity, palette, cx)) } @@ -731,7 +743,7 @@ impl Yumush { .border_b_2() .border_color(palette.accent) .children(community.map(|community| { - community_icon(palette, community, px(20.), px(10.), &self.chat.avatars) + community_icon(palette, community, px(20.), text(10.), &self.chat.avatars) })) .child( div() @@ -1295,7 +1307,7 @@ impl Yumush { Anchor::TopRight, user, entity, - avatar(palette, user, px(20.), px(10.), &self.chat.avatars) + avatar(palette, user, px(20.), text(10.), &self.chat.avatars) .border_2() .border_color(ring) .cursor_pointer() @@ -1422,7 +1434,7 @@ fn members_popover(entity: &Entity, chat: &Chat, palette: Palette) -> im .items_center() .gap(px(8.)) .rounded(px(6.)) - .child(avatar(palette, user, px(18.), px(9.), &avatars)) + .child(avatar(palette, user, px(18.), text(9.), &avatars)) .child( div() .flex_1() @@ -1445,7 +1457,7 @@ fn members_popover(entity: &Entity, chat: &Chat, palette: Palette) -> im ) .children((!user.status.is_empty()).then(|| { div() - .text_size(px(11.)) + .text_size(text(11.)) .text_color(palette.muted) .truncate() .child(user.status.clone()) @@ -1492,8 +1504,8 @@ fn render_message( .items_center() .gap(px(8.)) .child(match author { - Some(user) => avatar(palette, user, px(20.), px(10.), &chat.avatars), - None => badge(palette, &message.user_id, username, px(20.), px(10.)).rounded_full(), + Some(user) => avatar(palette, user, px(20.), text(10.), &chat.avatars), + None => badge(palette, &message.user_id, username, px(20.), text(10.)).rounded_full(), }) .child( div() @@ -1539,7 +1551,7 @@ fn render_message( .child(author) .child( div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(id_time(&message.id, "%H:%M")), ), @@ -1571,7 +1583,7 @@ fn render_message( .when(message.edited, |this| { this.child( div() - .text_size(px(11.)) + .text_size(text(11.)) .text_color(palette.muted) .child("(edited)"), ) diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index 8e0f6e6..c2d8b47 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -1,3 +1,4 @@ +use super::text; use std::{collections::HashMap, sync::Arc}; use common::{ @@ -98,7 +99,7 @@ impl Yumush { palette, community, px(64.), - px(24.), + text(24.), &self.chat.avatars, ), title: community.name.clone(), @@ -144,7 +145,7 @@ impl Yumush { .gap(px(8.)) .child( div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(bans_count.to_string()), ) @@ -435,7 +436,7 @@ fn view_control( .rounded(px(6.)) .border_1() .border_color(palette.border) - .text_size(px(13.)) + .text_size(text(13.)) .child("View") } @@ -469,7 +470,7 @@ fn sort_control( .flex() .items_center() .rounded(px(4.)) - .text_size(px(12.)) + .text_size(text(12.)) .text_color(if active { palette.text } else { palette.muted }) .when(active, |this| this.bg(palette.hover)) .child(label) @@ -486,7 +487,7 @@ fn moderation_body( ) -> impl IntoElement { let list = if rows.is_empty() { div() - .text_size(px(13.)) + .text_size(text(13.)) .text_color(palette.muted) .child(empty) .into_any_element() @@ -503,7 +504,7 @@ fn moderation_body( .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list)) } -fn search_text(input: &Entity, cx: &App) -> String { +pub(super) fn search_text(input: &Entity, cx: &App) -> String { input.read(cx).text().to_string().trim().to_lowercase() } @@ -577,13 +578,13 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap Div { .gap(px(6.)) .rounded(px(6.)) .bg(palette.hover) - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) } diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index 6185dca..225ef0c 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -1,3 +1,4 @@ +use super::text; use gpui_kit::{ AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, @@ -85,7 +86,7 @@ impl Render for Forward { palette, community, px(16.), - px(9.), + text(9.), &yumush.chat.avatars, )) .child( diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index dcb7910..7e3bcd3 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -1,3 +1,4 @@ +use super::text; use std::{ collections::{HashMap, HashSet}, path::PathBuf, @@ -568,7 +569,7 @@ fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl ) .child( div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(detail), ) @@ -731,7 +732,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { .bg(palette.panel) .children(embed.site.clone().map(|site| { div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(site) })) @@ -747,7 +748,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { })) .children(embed.description.clone().map(|description| { div() - .text_size(px(13.)) + .text_size(text(13.)) .text_color(palette.body) .line_clamp(3) .child(description) @@ -781,7 +782,7 @@ pub fn pending_row( .py(px(4.)) .rounded(px(6.)) .bg(palette.hover) - .text_size(px(12.)) + .text_size(text(12.)) .child( div() .max_w(px(180.)) @@ -812,7 +813,7 @@ pub fn pending_row( div() .px(px(10.)) .py(px(4.)) - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child("…"), ) diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index f9c592d..fc73ff2 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -1,3 +1,4 @@ +use super::text; use common::model::{Message, User}; use gpui_kit::{ Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window, @@ -26,9 +27,9 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option) { self.settings.theme = theme; - settings::apply(theme, cx); + settings::apply(theme, self.settings.font_size, cx); + self.commit_settings(cx); + } + + pub(super) fn set_font_size(&mut self, font_size: FontSize, cx: &mut Context) { + self.settings.font_size = font_size; + settings::apply(self.settings.theme, font_size, cx); self.commit_settings(cx); } @@ -346,7 +371,7 @@ fn card( .child( div() .px(px(2.)) - .text_size(px(12.)) + .text_size(text(12.)) .font_weight(FontWeight::MEDIUM) .text_color(title_color) .child(title), @@ -392,7 +417,7 @@ pub(super) fn text_row( .gap(px(6.)) .child( div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(editable.label), ) @@ -471,7 +496,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: P .gap(px(2.)) .child( div() - .text_size(px(16.)) + .text_size(text(16.)) .font_weight(FontWeight::SEMIBOLD) .truncate() .child(title), @@ -479,7 +504,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: P .when(!subtitle.is_empty(), |this| { this.child( div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .truncate() .child(subtitle), @@ -511,7 +536,7 @@ fn small_button( .flex() .items_center() .rounded(px(6.)) - .text_size(px(13.)) + .text_size(text(13.)) .text_color(color) } @@ -554,6 +579,35 @@ pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div { .child(control) } +pub(super) fn segment_track(palette: Palette) -> Div { + div() + .h(px(30.)) + .p(px(3.)) + .flex() + .gap(px(2.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.window) +} + +pub(super) fn segment(item: E, active: bool, palette: Palette) -> E { + let (background, border, text) = if active { + (palette.field, palette.border, palette.text) + } else { + (transparent_black(), transparent_black(), palette.muted) + }; + + item.flex() + .items_center() + .justify_center() + .rounded(px(5.)) + .border_1() + .border_color(border) + .bg(background) + .text_color(text) +} + pub(super) fn segmented( options: [(T, &'static str); N], selected: T, @@ -561,28 +615,17 @@ pub(super) fn segmented( palette: Palette, select: fn(&mut Yumush, T, &mut Context), ) -> impl IntoElement { - div() - .h(px(28.)) - .p(px(2.)) - .flex() - .gap(px(2.)) - .rounded(px(6.)) - .border_1() - .border_color(palette.border) - .bg(palette.field) - .children(options.map(|(choice, label)| { - let entity = entity.clone(); - let active = choice == selected; + segment_track(palette).children(options.map(|(choice, label)| { + let entity = entity.clone(); + segment( clickable(label, palette, move |_, cx| { entity.update(cx, |yumush, cx| select(yumush, choice, cx)); - }) - .px(px(10.)) - .flex() - .items_center() - .rounded(px(4.)) - .text_color(if active { palette.text } else { palette.muted }) - .when(active, |this| this.bg(palette.hover)) - .child(label) - })) + }), + choice == selected, + palette, + ) + .px(px(10.)) + .child(label) + })) } diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index d2feb7e..530d7b9 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -1,3 +1,4 @@ +use super::text; use common::{ model::{CommunityKind, Invitation, User}, permission, @@ -23,6 +24,7 @@ use super::{ clickable, community_icon, community_name, entity_action, hoverable, hoverable_with, input_dialog, profile::profile_popover, + settings_page::{segment, segment_track}, social::Relation, }; @@ -93,35 +95,23 @@ impl Yumush { ), ]; - div() + segment_track(palette) .flex_1() - .h(px(28.)) - .p(px(2.)) - .flex() - .gap(px(2.)) - .rounded(px(6.)) - .border_1() - .border_color(palette.border) - .bg(palette.field) .children(tabs.map(|(tab, label, alert)| { - let active = self.chat.tab == tab; - - let item = clickable( - label, + let item = segment( + clickable( + label, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_sidebar_tab(tab, window, cx) + }), + ), + self.chat.tab == tab, palette, - entity_action(entity, move |yumush, window, cx| { - yumush.set_sidebar_tab(tab, window, cx) - }), ) .flex_1() - .flex() - .items_center() - .justify_center() .gap(px(6.)) - .rounded(px(4.)) - .text_size(px(12.)) - .text_color(if active { palette.text } else { palette.muted }) - .when(active, |this| this.bg(palette.hover)) + .text_size(text(12.)) .child(label) .children(alert.then(|| dot(palette))); @@ -204,7 +194,7 @@ impl Yumush { palette, community, px(16.), - px(10.), + text(10.), &self.chat.avatars, ), community.name.clone(), @@ -264,7 +254,7 @@ impl Yumush { entry( themed, active, - community_icon(palette, community, px(20.), px(10.), &self.chat.avatars), + community_icon(palette, community, px(20.), text(10.), &self.chat.avatars), community_name(community).to_string(), alert.then(|| dot(palette).into_any_element()), ), @@ -297,7 +287,7 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), user.username.clone(), Vec::new(), ), @@ -360,7 +350,7 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), user.username.clone(), trailing, ) @@ -374,7 +364,7 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), user.username.clone(), [ icon_button( @@ -406,7 +396,7 @@ impl Yumush { entry( palette, false, - avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + avatar(palette, user, px(20.), text(10.), &self.chat.avatars), user.username.clone(), [icon_button( format!("cancel_friend_{}", user.id), @@ -432,7 +422,7 @@ impl Yumush { let decline_id = community.id.clone(); let label = div().flex().flex_col().child(community.name.clone()).child( div() - .text_size(px(11.)) + .text_size(text(11.)) .text_color(palette.muted) .child(format!("from {}", invitation.inviter.username)), ); @@ -440,7 +430,7 @@ impl Yumush { entry( palette, false, - community_icon(palette, community, px(16.), px(10.), &self.chat.avatars), + community_icon(palette, community, px(16.), text(10.), &self.chat.avatars), label, [ icon_button( @@ -476,12 +466,10 @@ impl Yumush { Some( div() - .h(px(32.)) - .pl(px(8.)) - .pr(px(4.)) + .h(px(36.)) .flex() .items_center() - .gap(px(8.)) + .gap(px(4.)) .child( profile_popover( "account_profile", @@ -493,10 +481,32 @@ impl Yumush { div() .flex() .items_center() + .h(px(36.)) .gap(px(8.)) - .px(px(4.)) + .px(px(6.)) .rounded(px(6.)) - .child(avatar(palette, user, px(20.), px(11.), &self.chat.avatars)) + .child( + div() + .relative() + .child(avatar( + palette, + user, + px(24.), + text(12.), + &self.chat.avatars, + )) + .child( + div() + .absolute() + .right(px(-2.)) + .bottom(px(-2.)) + .size(px(10.)) + .rounded_full() + .border_2() + .border_color(palette.window) + .bg(status), + ), + ) .child( div() .flex_1() @@ -510,7 +520,17 @@ impl Yumush { .flex_1() .min_w_0(), ) - .child(div().size(px(6.)).rounded_full().bg(status)) + .children(self.is_staff().then(|| { + icon_button( + "admin_button".to_string(), + palette, + IconName::Shield, + "Admin", + entity_action(entity, |yumush, window, cx| { + yumush.show_view(View::Admin, window, cx) + }), + ) + })) .children(self.voice_controls(entity, palette)), ) } @@ -641,7 +661,7 @@ fn group(title: &'static str, palette: Palette, rows: Vec) -> Option .child( div() .px(px(8.)) - .text_size(px(11.)) + .text_size(text(11.)) .text_color(palette.muted) .child(title), ) @@ -683,7 +703,8 @@ fn icon_button( ) -> AnyElement { clickable(id, palette, on_click) .tip(tip) - .size(px(24.)) + .size(px(26.)) + .flex_shrink_0() .flex() .items_center() .justify_center() diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs index 2857d13..a1e9f77 100644 --- a/crates/client/src/gui/snippet.rs +++ b/crates/client/src/gui/snippet.rs @@ -1,3 +1,4 @@ +use super::text; use common::model::{Message, Role, SnippetMessage, User}; use gpui_kit::{ Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px, @@ -30,7 +31,7 @@ pub fn snippet_card( .bg(palette.panel) .child( div() - .text_size(px(12.)) + .text_size(text(12.)) .text_color(palette.muted) .child(header), ) @@ -60,7 +61,7 @@ fn snippet_row( div() .flex() .gap(px(8.)) - .child(avatar(palette, &user, px(20.), px(10.), &chat.avatars)) + .child(avatar(palette, &user, px(20.), text(10.), &chat.avatars)) .child( div() .flex_1() @@ -81,7 +82,7 @@ fn snippet_row( ) .child( div() - .text_size(px(11.)) + .text_size(text(11.)) .text_color(palette.muted) .child(id_time(&item.id, "%H:%M")), ), diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index 51e2fb5..d6af3a7 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -1,3 +1,4 @@ +use super::text; use std::{fmt::Display, future::Future}; use common::{ @@ -398,7 +399,7 @@ fn invite_result( InviteLookup::Idle => None, InviteLookup::Missing => Some( div() - .text_size(px(13.)) + .text_size(text(13.)) .text_color(palette.muted) .child("No such user") .into_any_element(), @@ -407,7 +408,7 @@ fn invite_result( user_row(user, yumush, palette) .child( div() - .text_size(px(13.)) + .text_size(text(13.)) .text_color(palette.muted) .child("Member"), ) @@ -447,7 +448,7 @@ fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gp palette, user, px(32.), - px(14.), + text(14.), &yumush.chat.avatars, )) .child( diff --git a/crates/client/src/gui/voice_settings.rs b/crates/client/src/gui/voice_settings.rs index da7d13b..1cd5051 100644 --- a/crates/client/src/gui/voice_settings.rs +++ b/crates/client/src/gui/voice_settings.rs @@ -20,7 +20,7 @@ use super::{ settings_page::{row, segmented}, }; use crate::{ - settings::{Activation, SENSITIVITY_DB, VOLUME, VoiceSettings}, + settings::{Activation, Profile, SENSITIVITY_DB, VOLUME, VoiceSettings}, voice::audio::{self, Device, Devices}, }; @@ -29,6 +29,7 @@ const MODES: [(Activation, &str); 2] = [ (Activation::VoiceActivity, "Voice activity"), (Activation::PushToTalk, "Push to talk"), ]; +const PROFILES: [(Profile, &str); 2] = [(Profile::Voice, "Voice"), (Profile::Music, "Music")]; #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Side { @@ -249,6 +250,16 @@ impl Yumush { Yumush::set_voice_mode, ), ), + row( + "Profile", + segmented( + PROFILES, + voice.profile, + entity, + palette, + Yumush::set_voice_profile, + ), + ), ]; if self.chat.voice_community().is_none() { @@ -370,6 +381,11 @@ impl Yumush { self.commit_settings(cx); } + pub(super) fn set_voice_profile(&mut self, profile: Profile, cx: &mut Context) { + self.settings.voice.profile = profile; + self.commit_settings(cx); + } + pub(super) fn capture_key(&mut self, window: &mut Window, cx: &mut Context) { window.focus(&self.focus, cx); self.voice.key = KeyCapture::Waiting; diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 52949e2..9c6382c 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -28,7 +28,7 @@ fn main() { .with_assets(AllAssets) .run(move |cx: &mut App| { init(cx); - settings::apply(settings.theme, cx); + settings::apply(settings.theme, settings.font_size, cx); gui::bind_keys(cx); let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx); diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index fa27670..12cafad 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -9,7 +9,8 @@ use common::{ error::Error, event::Event, model::{ - Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, User, + Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, Role, + User, }, network::{ DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded, @@ -177,6 +178,26 @@ impl NetworkHandle { } } + pub async fn users(&self) -> Result, Error> { + match self.request(Request::Users).await? { + Response::Users(users) => Ok(users), + _ => Err(Error::Server), + } + } + + pub async fn set_role(&self, user_id: &str, role: Role) -> Result { + match self + .request(Request::SetRole { + user_id: user_id.to_string(), + role, + }) + .await? + { + Response::User(user) => Ok(user), + _ => Err(Error::Server), + } + } + pub async fn read_user(&self, user_id: &str) -> Result { match self .request(Request::ReadUser { diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index 7341050..59c5fca 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -2,8 +2,9 @@ use std::{fmt::Display, fs, ops::RangeInclusive, path::PathBuf}; use common::config::Config; use gpui_kit::{ - App, Global, + App, Global, Pixels, component::{Theme, ThemeMode}, + px, }; use tracing::warn; @@ -24,6 +25,44 @@ pub struct Look(pub ThemeChoice); impl Global for Look {} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FontSize { + Small, + Medium, + Large, +} + +pub struct Scale(pub FontSize); + +impl Global for Scale {} + +impl FontSize { + fn name(self) -> &'static str { + match self { + FontSize::Small => "small", + FontSize::Medium => "medium", + FontSize::Large => "large", + } + } + + fn parse(value: &str) -> Option { + match value { + "small" => Some(FontSize::Small), + "medium" => Some(FontSize::Medium), + "large" => Some(FontSize::Large), + _ => None, + } + } + + pub fn pixels(self) -> Pixels { + match self { + FontSize::Small => px(13.), + FontSize::Medium => px(14.), + FontSize::Large => px(16.), + } + } +} + impl ThemeChoice { fn name(self) -> &'static str { match self { @@ -51,6 +90,12 @@ pub enum Activation { PushToTalk, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Profile { + Voice, + Music, +} + #[derive(Debug, Clone, PartialEq)] pub struct VoiceSettings { pub sensitivity_db: f32, @@ -58,6 +103,7 @@ pub struct VoiceSettings { pub output_volume: f32, pub choice: Choice, pub activation: Activation, + pub profile: Profile, pub push_to_talk_key: String, } @@ -69,6 +115,7 @@ impl Default for VoiceSettings { output_volume: 100.0, choice: Choice::default(), activation: Activation::VoiceActivity, + profile: Profile::Voice, push_to_talk_key: String::new(), } } @@ -77,6 +124,7 @@ impl Default for VoiceSettings { #[derive(Debug, Clone, PartialEq)] pub struct Settings { pub theme: ThemeChoice, + pub font_size: FontSize, pub voice: VoiceSettings, } @@ -118,6 +166,10 @@ pub fn load() -> Settings { Some("push_to_talk") => Activation::PushToTalk, _ => Activation::VoiceActivity, }, + profile: match text("voice.profile").as_deref() { + Some("music") => Profile::Music, + _ => Profile::Voice, + }, push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), }; @@ -125,6 +177,9 @@ pub fn load() -> Settings { theme: text("theme") .and_then(|value| ThemeChoice::parse(&value)) .unwrap_or(ThemeChoice::Dark), + font_size: text("font_size") + .and_then(|value| FontSize::parse(&value)) + .unwrap_or(FontSize::Medium), voice, } } @@ -143,9 +198,14 @@ pub fn save(settings: &Settings) { Activation::VoiceActivity => "voice_activity", Activation::PushToTalk => "push_to_talk", }; + let profile = match voice.profile { + Profile::Voice => "voice", + Profile::Music => "music", + }; let key = voice.push_to_talk_key.as_str(); let content = [ line("theme", settings.theme.name()), + line("font_size", settings.font_size.name()), line("voice.sensitivity", voice.sensitivity_db), line("voice.input_volume", voice.input_volume), line("voice.output_volume", voice.output_volume), @@ -158,6 +218,7 @@ pub fn save(settings: &Settings) { voice.choice.output.as_deref().unwrap_or_default(), ), line("voice.activation", activation), + line("voice.profile", profile), line("voice.push_to_talk", key), ] .concat(); @@ -172,8 +233,9 @@ pub fn save(settings: &Settings) { } } -pub fn apply(choice: ThemeChoice, cx: &mut App) { +pub fn apply(choice: ThemeChoice, font_size: FontSize, cx: &mut App) { cx.set_global(Look(choice)); + cx.set_global(Scale(font_size)); match choice { ThemeChoice::System => Theme::sync_system_appearance(None, cx), ThemeChoice::Light => Theme::change(ThemeMode::Light, None, cx), diff --git a/crates/client/src/voice/audio/pipewire.rs b/crates/client/src/voice/audio/pipewire.rs index bf3663c..e2acae8 100644 --- a/crates/client/src/voice/audio/pipewire.rs +++ b/crates/client/src/voice/audio/pipewire.rs @@ -11,9 +11,7 @@ use pipewire as pw; use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType}; use spa::pod::Pod; -use super::{ - Choice, Device, Devices, Downmix, Worker, play, record, stereo_bytes, stereo_frame, supervise, -}; +use super::{Choice, Device, Devices, Worker, play, record, stereo_bytes, supervise}; use crate::voice::{Capture, Playback}; const STOP_CHECK: Duration = Duration::from_millis(100); @@ -133,14 +131,18 @@ fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::Pr props } -fn format_values() -> Option> { +fn format_values(channels: u32) -> Option> { let mut info = spa::param::audio::AudioInfoRaw::new(); info.set_format(spa::param::audio::AudioFormat::F32LE); info.set_rate(VOICE_SAMPLE_RATE); let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; - position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL; - position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR; - info.set_channels(2); + if channels == 1 { + position[0] = spa::sys::SPA_AUDIO_CHANNEL_MONO; + } else { + position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL; + position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR; + } + info.set_channels(channels); info.set_position(position); let object = spa::pod::Object { @@ -178,7 +180,8 @@ fn run( }) .register(); - let values = format_values().ok_or("pipewire format")?; + let capture_values = format_values(1).ok_or("pipewire format")?; + let playback_values = format_values(2).ok_or("pipewire format")?; let flags = pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS | pw::stream::StreamFlags::RT_PROCESS; @@ -190,7 +193,6 @@ fn run( )?; let capture = capture.cloned(); let connect_capture = capture.is_some(); - let mut downmix = Downmix::default(); let _capture_listener = capture_stream .add_local_listener_with_user_data(()) .state_changed(state_watch(&failed)) @@ -209,16 +211,17 @@ fn run( let Some(capture) = &capture else { return; }; - let frames = bytes - .as_chunks::() + let samples = bytes + .as_chunks::<4>() .0 .iter() - .map(stereo_frame); - record(capture, downmix.mix(frames)); + .copied() + .map(f32::from_le_bytes); + record(capture, samples); }) .register()?; if connect_capture { - let mut capture_params = [Pod::from_bytes(&values).ok_or("pipewire format")?]; + let mut capture_params = [Pod::from_bytes(&capture_values).ok_or("pipewire format")?]; capture_stream.connect( spa::utils::Direction::Input, None, @@ -262,7 +265,7 @@ fn run( *chunk.size_mut() = (frames * BYTES_PER_FRAME) as u32; }) .register()?; - let mut playback_params = [Pod::from_bytes(&values).ok_or("pipewire format")?]; + let mut playback_params = [Pod::from_bytes(&playback_values).ok_or("pipewire format")?]; playback_stream.connect( spa::utils::Direction::Output, None, diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index a44c3d3..914a17f 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -4,27 +4,61 @@ use std::{ }; use common::{ - constant::{VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE}, + constant::{ + MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, + }, voice::{decode_relay, encode_packet}, }; -use ec_opus::{Application, Decoder, Encoder}; +use ec_opus::{Application, Bandwidth, Decoder, Encoder}; + +use crate::settings::Profile; pub const SILENT_DB: f32 = -100.0; const JITTER_CAPACITY: usize = 10; -const START_FRAMES: usize = 2; +const FRAME_MS: f32 = 20.0; +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 HANGOVER_FRAMES: u32 = 15; +const FADE_SAMPLES: usize = 240; +const EXPECTED_LOSS_PERC: u8 = 10; fn rms(samples: &[f32]) -> f32 { (samples.iter().map(|sample| sample * sample).sum::() / samples.len() as f32).sqrt() } +fn soft_clip(sample: f32) -> f32 { + const KNEE: f32 = 0.8; + let magnitude = sample.abs(); + if magnitude <= KNEE { + return sample; + } + let over = (magnitude - KNEE) / (1.0 - KNEE); + sample.signum() * (KNEE + (1.0 - KNEE) * over.tanh()) +} + fn db(amplitude: f32) -> f32 { (20.0 * amplitude.log10()).max(SILENT_DB) } +fn encoder(profile: Profile) -> Encoder { + let (application, bitrate) = match profile { + Profile::Voice => (Application::Voip, VOICE_BITRATE), + Profile::Music => (Application::Audio, MUSIC_BITRATE), + }; + let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder"); + encoder.set_bitrate(bitrate as u32); + encoder.set_bandwidth(Some(Bandwidth::Full)); + encoder.set_analysis(true); + encoder.set_inband_fec(true); + encoder.set_packet_loss_perc(EXPECTED_LOSS_PERC); + encoder +} + struct Speaker { decoder: Decoder, scratch: Vec, @@ -33,6 +67,10 @@ struct Speaker { pending: VecDeque, last_heard: Instant, started: bool, + first_arrival: Instant, + first_sequence: u32, + previous_transit: Option, + jitter_ms: f32, } impl Speaker { @@ -45,23 +83,51 @@ impl Speaker { pending: VecDeque::new(), last_heard: now, started: false, + first_arrival: now, + first_sequence: sequence, + previous_transit: None, + jitter_ms: 0.0, } } - fn next_frame(&mut self) -> Option> { - if self.jitter.is_empty() { - return None; - } - let decoded = match self.jitter.remove(&self.next) { - Some(payload) => self.decoder.decode_float(&payload, &mut self.scratch), - None => self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch), + fn target(&self) -> usize { + ((self.jitter_ms * 2.0 / FRAME_MS).ceil() as usize + 1).clamp(MIN_FRAMES, MAX_FRAMES) + } + + fn decode_next(&mut self) -> (Vec, bool) { + let (decoded, real) = match ( + self.jitter.remove(&self.next), + self.jitter.get(&(self.next + 1)), + ) { + (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true), + (None, Some(following)) => ( + self.decoder + .decode_fec(following, VOICE_FRAME_SAMPLES, &mut self.scratch), + false, + ), + (None, None) => ( + self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch), + false, + ), }; self.next += 1; - Some(match decoded { + let samples = match decoded { Ok(samples) => self.scratch[..samples].to_vec(), Err(_) => vec![0.0; VOICE_FRAME_SAMPLES], - }) + }; + (samples, real) + } + + fn next_frame(&mut self) -> Option> { + if self.jitter.is_empty() { + return None; + } + let (mut frame, real) = self.decode_next(); + if real && self.jitter.len() > self.target() + DRIFT_MARGIN && rms(&frame) < QUIET { + (frame, _) = self.decode_next(); + } + Some(frame) } fn mix(&mut self, out: &mut [f32]) { @@ -69,6 +135,7 @@ impl Speaker { if self.pending.is_empty() { let Some(frame) = self.next_frame() else { self.started = false; + self.previous_transit = None; return; }; self.pending.extend(frame); @@ -80,6 +147,7 @@ impl Speaker { pub struct Engine { encoder: Encoder, + profile: Profile, capture_buffer: Vec, sequence: u32, muted: bool, @@ -90,6 +158,7 @@ pub struct Engine { push_to_talk: bool, talking: bool, hangover: u32, + sending: bool, level_db: f32, speakers: HashMap, } @@ -102,12 +171,9 @@ impl Default for Engine { impl Engine { pub fn new() -> Self { - let mut encoder = - Encoder::new(VOICE_SAMPLE_RATE, 1, Application::Voip).expect("opus encoder"); - encoder.set_bitrate(VOICE_BITRATE as u32); - Self { - encoder, + encoder: encoder(Profile::Voice), + profile: Profile::Voice, capture_buffer: Vec::new(), sequence: 0, muted: false, @@ -118,6 +184,7 @@ impl Engine { push_to_talk: false, talking: false, hangover: 0, + sending: false, level_db: SILENT_DB, speakers: HashMap::new(), } @@ -129,7 +196,7 @@ impl Engine { let full = self.capture_buffer.len() / VOICE_FRAME_SAMPLES * VOICE_FRAME_SAMPLES; let mut frames: Vec = self.capture_buffer.drain(..full).collect(); for sample in &mut frames { - *sample *= self.input_gain; + *sample = soft_clip(*sample * self.input_gain); } let mut packets = Vec::new(); @@ -139,20 +206,35 @@ impl Engine { if loud >= self.gate { self.hangover = HANGOVER_FRAMES; } - let speaking = if self.push_to_talk { + let talking = if self.push_to_talk { self.talking } else { self.hangover > 0 }; self.hangover = self.hangover.saturating_sub(1); - if self.muted || self.deafened || !speaking { + let speaking = talking && !self.muted && !self.deafened; + let was_sending = self.sending; + self.sending = speaking; + if !speaking && !was_sending { continue; } + let mut samples = *frame; + if speaking && !was_sending { + for (index, sample) in samples[..FADE_SAMPLES].iter_mut().enumerate() { + *sample *= index as f32 / FADE_SAMPLES as f32; + } + } + if !speaking { + for (index, sample) in samples.iter_mut().enumerate() { + *sample *= 1.0 - index as f32 / VOICE_FRAME_SAMPLES as f32; + } + } + let mut payload = [0u8; VOICE_MAX_PAYLOAD]; let Ok(length) = self .encoder - .encode_float(frame, VOICE_FRAME_SAMPLES, &mut payload) + .encode_float(&samples, VOICE_FRAME_SAMPLES, &mut payload) else { continue; }; @@ -187,11 +269,18 @@ impl Engine { return; } + let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0 + - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS; + if let Some(previous) = speaker.previous_transit { + speaker.jitter_ms += ((transit_ms - previous).abs() - speaker.jitter_ms) / 16.0; + } + speaker.previous_transit = Some(transit_ms); + speaker.jitter.insert(sequence, payload.to_vec()); while speaker.jitter.len() > JITTER_CAPACITY { speaker.jitter.pop_first(); } - if speaker.jitter.len() >= START_FRAMES { + if speaker.jitter.len() >= speaker.target() { speaker.started = true; } } @@ -209,7 +298,7 @@ impl Engine { } for sample in out.iter_mut() { - *sample = (*sample * self.output_gain).clamp(-1.0, 1.0); + *sample = soft_clip(*sample * self.output_gain); } } @@ -241,11 +330,16 @@ impl Engine { input_volume: f32, output_volume: f32, push_to_talk: bool, + profile: Profile, ) { self.gate = 10f32.powf(sensitivity_db / 20.0); self.input_gain = input_volume / 100.0; self.output_gain = output_volume / 100.0; self.push_to_talk = push_to_talk; + if profile != self.profile { + self.encoder = encoder(profile); + self.profile = profile; + } } pub fn set_talking(&mut self, talking: bool) { diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index f728132..8b12823 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -173,6 +173,7 @@ impl Voice { settings.input_volume, settings.output_volume, settings.activation == Activation::PushToTalk, + settings.profile, ); } } diff --git a/crates/common/src/constant.rs b/crates/common/src/constant.rs index f9e1fac..7b0149a 100644 --- a/crates/common/src/constant.rs +++ b/crates/common/src/constant.rs @@ -12,7 +12,8 @@ pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024; pub const MAXIMUM_STATUS_LENGTH: usize = 64; pub const VOICE_SAMPLE_RATE: u32 = 48_000; pub const VOICE_FRAME_SAMPLES: usize = 960; -pub const VOICE_BITRATE: i32 = 32_000; +pub const VOICE_BITRATE: i32 = 48_000; +pub const MUSIC_BITRATE: i32 = 96_000; pub const VOICE_MAX_PAYLOAD: usize = 1000; pub const MAXIMUM_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024; pub const MAXIMUM_ATTACHMENTS_PER_MESSAGE: usize = 10; diff --git a/crates/common/src/permission.rs b/crates/common/src/permission.rs index 909ca39..103a69d 100644 --- a/crates/common/src/permission.rs +++ b/crates/common/src/permission.rs @@ -65,6 +65,10 @@ pub fn can_leave(actor: Option) -> bool { actor.is_some() && actor != Some(Rank::Owner) } +pub fn can_set_role(actor: Role, is_self: bool) -> bool { + actor == Role::Staff && !is_self +} + pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool { is_self || (actor == Role::Staff && target != Role::Staff) } diff --git a/crates/common/src/request.rs b/crates/common/src/request.rs index 78869bf..13968de 100644 --- a/crates/common/src/request.rs +++ b/crates/common/src/request.rs @@ -1,6 +1,6 @@ use bitcode::{Decode, Encode}; -use crate::model::Rank; +use crate::model::{Rank, Role}; #[derive(Debug, Clone, Encode, Decode)] pub struct UploadHeader { @@ -154,4 +154,9 @@ pub enum Request { Logs { community_id: String, }, + Users, + SetRole { + user_id: String, + role: Role, + }, } diff --git a/crates/common/src/response.rs b/crates/common/src/response.rs index cfa8b73..864242d 100644 --- a/crates/common/src/response.rs +++ b/crates/common/src/response.rs @@ -23,4 +23,5 @@ pub enum Response { Done, Error(Error), Logs(Vec), + Users(Vec), } diff --git a/crates/server/src/request.rs b/crates/server/src/request.rs index 90dbbab..34442e0 100644 --- a/crates/server/src/request.rs +++ b/crates/server/src/request.rs @@ -3,7 +3,7 @@ use std::{collections::BTreeSet, path::Path, sync::Mutex}; use common::{ error::Error as CommonError, event::Event, - model::{CommunityKind, LogAction, Member, Rank, User}, + model::{CommunityKind, LogAction, Member, Rank, Role, User}, permission, request::Request, response::Response, @@ -70,27 +70,27 @@ async fn dispatch( sign_in(state, user, token, broadcasts) } Request::Detach => { - authenticated(state)?; + authenticated(state, &conn).await?; let broadcasts = leave_connection_voice(voice, connection, &conn).await?; set_state(state, State::Anonymous); (Response::Done, broadcasts) } Request::Logout => { - let (_, token) = authenticated(state)?; + let (_, token) = authenticated(state, &conn).await?; authentication::logout(&token, &conn).await?; let broadcasts = leave_connection_voice(voice, connection, &conn).await?; set_state(state, State::Anonymous); (Response::Done, broadcasts) } Request::ReadUser { user_id } => { - authenticated(state)?; + authenticated(state, &conn).await?; ( Response::User(user::read(&user_id, &conn).await?), Vec::new(), ) } Request::UpdateUser { username } => { - let (me, token) = authenticated(state)?; + let (me, token) = authenticated(state, &conn).await?; let user = user::update(&me.id, &username, &conn).await?; set_state( state, @@ -102,8 +102,20 @@ async fn dispatch( let broadcasts = user_updated(&user, &conn).await?; (Response::User(user), broadcasts) } + Request::Users => { + let (me, _) = authenticated(state, &conn).await?; + ensure(me.role == Role::Staff)?; + (Response::Users(user::all(&conn).await?), Vec::new()) + } + Request::SetRole { user_id, role } => { + let (me, _) = authenticated(state, &conn).await?; + ensure(permission::can_set_role(me.role, me.id == user_id))?; + let user = user::set_role_by_id(&user_id, role, &conn).await?; + let broadcasts = user_updated(&user, &conn).await?; + (Response::User(user), broadcasts) + } Request::UpdateStatus { status } => { - let (me, token) = authenticated(state)?; + let (me, token) = authenticated(state, &conn).await?; let user = user::update_status(&me.id, &status, &conn).await?; set_state( state, @@ -116,7 +128,7 @@ async fn dispatch( (Response::User(user), broadcasts) } Request::UpdateAvatar { image } => { - let (me, token) = authenticated(state)?; + let (me, token) = authenticated(state, &conn).await?; let user = user::set_avatar(&me.id, &image, &mut conn).await?; set_state( state, @@ -129,7 +141,7 @@ async fn dispatch( (Response::User(user), broadcasts) } Request::RemoveAvatar => { - let (me, token) = authenticated(state)?; + let (me, token) = authenticated(state, &conn).await?; let user = user::remove_avatar(&me.id, &mut conn).await?; set_state( state, @@ -142,14 +154,14 @@ async fn dispatch( (Response::User(user), broadcasts) } Request::ReadAvatar { avatar_id } => { - authenticated(state)?; + authenticated(state, &conn).await?; ( Response::Avatar(user::avatar(&avatar_id, &conn).await?), Vec::new(), ) } Request::DeleteUser { user_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_delete_user( me.role, @@ -184,7 +196,7 @@ async fn dispatch( (Response::User(deleted), broadcasts) } Request::CreateCommunity { name } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let tx = conn.transaction().await?; let community = community::create(&name, &tx).await?; user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?; @@ -193,14 +205,14 @@ async fn dispatch( (Response::Community(community), Vec::new()) } Request::ReadCommunity { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ( Response::Community(community::read(&community_id, &me.id, &conn).await?), Vec::new(), ) } Request::UpdateCommunity { community_id, name } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(!community::is_direct(&community_id, &conn).await?)?; ensure(permission::can_rename_community( actor_rank(&me, &community_id, &conn).await?, @@ -218,7 +230,7 @@ async fn dispatch( community_id, image, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(!community::is_direct(&community_id, &conn).await?)?; ensure(permission::can_rename_community( actor_rank(&me, &community_id, &conn).await?, @@ -236,7 +248,7 @@ async fn dispatch( (Response::Community(updated), broadcast(event, &members)) } Request::DeleteCommunity { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(!community::is_direct(&community_id, &conn).await?)?; ensure(permission::can_delete_community( actor_rank(&me, &community_id, &conn).await?, @@ -252,7 +264,7 @@ async fn dispatch( (Response::Community(deleted), broadcast(event, &members)) } Request::LeaveCommunity { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(!community::is_direct(&community_id, &conn).await?)?; ensure(permission::can_leave( actor_rank(&me, &community_id, &conn).await?, @@ -274,14 +286,14 @@ async fn dispatch( (Response::Done, broadcasts) } Request::Communities => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ( Response::Communities(community::communities_of(&me.id, &conn).await?), Vec::new(), ) } Request::Members { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_read( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -295,7 +307,7 @@ async fn dispatch( user_id, reason, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; remove_member( &me, Removal { @@ -314,7 +326,7 @@ async fn dispatch( user_id, reason, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; remove_member( &me, Removal { @@ -332,7 +344,7 @@ async fn dispatch( community_id, user_id, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_unban( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -348,7 +360,7 @@ async fn dispatch( (Response::Done, Vec::new()) } Request::Bans { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_unban( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -362,7 +374,7 @@ async fn dispatch( user_id, rank, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(!community::is_direct(&community_id, &conn).await?)?; let target = user::read(&user_id, &conn).await?; ensure(permission::can_set_rank( @@ -393,7 +405,7 @@ async fn dispatch( attachments, reply_to, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_post( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -417,7 +429,7 @@ async fn dispatch( community_id, snippet, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; validate_forward(message_ids.len())?; ensure(permission::can_post( actor_rank(&me, &community_id, &conn).await?, @@ -443,7 +455,7 @@ async fn dispatch( (Response::Messages(created), broadcasts) } Request::UpdateMessage { message_id, body } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; ensure(permission::can_edit_message(existing.user_id == me.id))?; let updated = message::update(&message_id, &body, &conn).await?; @@ -452,7 +464,7 @@ async fn dispatch( (Response::Message(updated), broadcast(event, &members)) } Request::DeleteMessage { message_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let existing = message::read(&message_id, &conn).await?; let author = user::read(&existing.user_id, &conn).await?; ensure(permission::can_delete_message( @@ -479,7 +491,7 @@ async fn dispatch( community_id, before, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_read( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -487,7 +499,7 @@ async fn dispatch( (Response::Messages(messages), Vec::new()) } Request::JoinVoice { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_join_voice( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -516,14 +528,14 @@ async fn dispatch( ) } Request::LeaveVoice => { - authenticated(state)?; + authenticated(state, &conn).await?; ( Response::Done, leave_connection_voice(voice, connection, &conn).await?, ) } Request::VoiceParticipants { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_read( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -533,14 +545,15 @@ async fn dispatch( ) } Request::FindUser { username } => { - authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let found = user::by_username(&username, &conn) .await? + .filter(|found| found.id != me.id) .ok_or(CommonError::NotFound)?; (Response::User(found), Vec::new()) } Request::OpenDirect { user_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?; let broadcasts = if created { let peer_view = community::read(&community.id, &user_id, &conn).await?; @@ -554,26 +567,26 @@ async fn dispatch( (Response::Community(community), broadcasts) } Request::Friends => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ( Response::Friends(friend::state(&me.id, &conn).await?), Vec::new(), ) } Request::AddFriend { user_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; friend::add(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) } Request::AcceptFriend { user_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; friend::accept(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) } Request::RemoveFriend { user_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; friend::remove(&me.id, &user_id, &mut conn).await?; let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?; (Response::Done, broadcasts) @@ -582,7 +595,7 @@ async fn dispatch( community_id, user_id, } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(!community::is_direct(&community_id, &conn).await?)?; ensure(permission::can_read( actor_rank(&me, &community_id, &conn).await?, @@ -612,14 +625,14 @@ async fn dispatch( (Response::Done, vec![broadcast]) } Request::Invitations => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ( Response::Invitations(invitation::of(&me.id, &conn).await?), Vec::new(), ) } Request::AcceptInvitation { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; let tx = conn.transaction().await?; invitation::take(&community_id, &me.id, &tx).await?; let banned = user_community::is_banned(&me.id, &community_id, &tx).await?; @@ -641,7 +654,7 @@ async fn dispatch( (Response::Community(community), broadcasts) } Request::DeclineInvitation { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; invitation::take(&community_id, &me.id, &conn).await?; ( Response::Done, @@ -649,7 +662,7 @@ async fn dispatch( ) } Request::Logs { community_id } => { - let (me, _) = authenticated(state)?; + let (me, _) = authenticated(state, &conn).await?; ensure(permission::can_read_logs( actor_rank(&me, &community_id, &conn).await?, ))?; @@ -725,7 +738,7 @@ async fn remove_member( } async fn user_updated(user: &User, conn: &Connection) -> Result, Error> { - let mut user_ids = BTreeSet::new(); + let mut user_ids = BTreeSet::from([user.id.clone()]); for community in community::communities_of(&user.id, conn).await? { for member in user_community::members(&community.id, conn).await? { user_ids.insert(member.user.id); @@ -831,11 +844,21 @@ fn set_state(state: &Mutex, new_state: State) { *state.lock().unwrap() = new_state; } -fn authenticated(state: &Mutex) -> Result<(User, String), Error> { - match state.lock().unwrap().clone() { - State::Anonymous => Err(CommonError::Unauthenticated.into()), - State::Authenticated { user, token } => Ok((user, token)), - } +async fn authenticated(state: &Mutex, conn: &Connection) -> Result<(User, String), Error> { + let (cached, token) = match state.lock().unwrap().clone() { + State::Anonymous => return Err(CommonError::Unauthenticated.into()), + State::Authenticated { user, token } => (user, token), + }; + let user = user::read(&cached.id, conn).await?; + set_state( + state, + State::Authenticated { + user: user.clone(), + token: token.clone(), + }, + ); + + Ok((user, token)) } pub async fn actor_rank( diff --git a/crates/server/src/user.rs b/crates/server/src/user.rs index ab5a540..00cfc55 100644 --- a/crates/server/src/user.rs +++ b/crates/server/src/user.rs @@ -28,8 +28,14 @@ fn role_of(row: &Row) -> Result { pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result { let mut rows = conn .query( - "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username, role, status, avatar_id", - (new_id(), username, password_hash), + "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", + ( + new_id(), + username, + password_hash, + Role::User.as_str(), + Role::Staff.as_str(), + ), ) .await?; let row = rows.next().await?.ok_or(CommonError::NotFound)?; @@ -52,7 +58,7 @@ pub async fn read(user_id: &str, 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", + "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1 COLLATE NOCASE", (username,), ) .await?; @@ -194,6 +200,33 @@ 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", + (user_id, role.as_str()), + ) + .await?; + let row = rows.next().await?.ok_or(CommonError::NotFound)?; + + from_row(&row) +} + +pub async fn all(conn: &Connection) -> Result, Error> { + let mut rows = conn + .query( + "SELECT id, username, role, status, avatar_id FROM user ORDER BY username COLLATE NOCASE", + (), + ) + .await?; + let mut users = Vec::new(); + while let Some(row) = rows.next().await? { + users.push(from_row(&row)?); + } + + Ok(users) +} + pub async fn delete(user_id: &str, conn: &Connection) -> Result { let mut rows = conn .query( @@ -274,7 +307,7 @@ mod tests { let created_user = user::create("Tahinli", "hash", &conn).await.unwrap(); let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap(); - let searched_user = user::by_username("Tahinli", &conn).await.unwrap(); + let searched_user = user::by_username("tahinli", &conn).await.unwrap(); assert_eq!(Some(created_user), searched_user); }