forge
Explore
Log in

Don't you dare go Hollow

Add user admin, font size, music voice profile and adaptive jitter

Browse files at this commit

3950bc853afeffb8254d060622b8a3d49a5b5620Ahmet Kaan GümüşParent: 0df2293
  • feat
    • add user admin, font size, music voice profile and adaptive jitter
Show full message
✨ feat: add user admin, font size, music voice profile and adaptive jitter

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.
.gitignoremodified+2 -0
@@ -1,3 +1,5 @@
1 /target1 /target
2 Cargo.lock2 Cargo.lock
3 configs/server_config.toml3 configs/server_config.toml
4+*.pem
5+yumush.db*
crates/client/src/gui.rsmodified+25 -11
@@ -13,7 +13,7 @@ use common::{
13 use gpui_kit::{13 use gpui_kit::{
14 AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight,14 AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight,
15 Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent,15 Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent,
16- KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Render, RenderOnce, Stateful,16+ KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful,
17 StatefulInteractiveElement, Styled, WeakEntity, Window, actions,17 StatefulInteractiveElement, Styled, WeakEntity, Window, actions,
18 base::Selectable,18 base::Selectable,
19 component::{19 component::{
@@ -21,7 +21,7 @@ use gpui_kit::{
21 input::{Input, InputEvent, InputState},21 input::{Input, InputEvent, InputState},
22 notification::Notification,22 notification::Notification,
23 },23 },
24- div, hsla, img, px, rgb,24+ div, hsla, img, px, rems, rgb,
25 };25 };
26 use jiff::{Timestamp, tz::TimeZone};26 use jiff::{Timestamp, tz::TimeZone};
27 use tokio::sync::mpsc;27 use tokio::sync::mpsc;
@@ -30,9 +30,10 @@ use uuid::Uuid;
30 use crate::{30 use crate::{
31 accounts::{self, Accounts},31 accounts::{self, Accounts},
32 network::{NetworkEvent, NetworkHandle},32 network::{NetworkEvent, NetworkHandle},
33- settings::{Look, Settings, ThemeChoice},33+ settings::{Look, Scale, Settings, ThemeChoice},
34 };34 };
35 35
36+mod admin;
36 mod auth;37 mod auth;
37 mod chat;38 mod chat;
38 mod community_settings;39 mod community_settings;
@@ -53,6 +54,12 @@ use voice_settings::VoiceControls;
53 54
54 actions!(yumush, [FocusFind, CloseSettings]);55 actions!(yumush, [FocusFind, CloseSettings]);
55 56
57+pub const BASE_FONT: f32 = 14.;
58+
59+pub fn text(size: f32) -> Rems {
60+ rems(size / BASE_FONT)
61+}
62+
56 const TINTS: [u32; 10] = [63 const TINTS: [u32; 10] = [
57 0x10b981, 0xa855f7, 0xf59e0b, 0xf97316, 0xec4899, 0x0ea5e9, 0x22c55e, 0xef4444, 0x06b6d4,64 0x10b981, 0xa855f7, 0xf59e0b, 0xf97316, 0xec4899, 0x0ea5e9, 0x22c55e, 0xef4444, 0x06b6d4,
58 0xd946ef,65 0xd946ef,
@@ -159,6 +166,7 @@ pub fn sync_accent(accent: Hsla, cx: &mut App) {
159 166
160 pub fn sync_theme(cx: &mut App) {167 pub fn sync_theme(cx: &mut App) {
161 let palette = palette(cx);168 let palette = palette(cx);
169+ let font_size = cx.global::<Scale>().0.pixels();
162 let theme = Theme::global_mut(cx);170 let theme = Theme::global_mut(cx);
163 let colors = &mut theme.colors;171 let colors = &mut theme.colors;
164 172
@@ -185,7 +193,7 @@ pub fn sync_theme(cx: &mut App) {
185 theme.tokens = (&theme.colors).into();193 theme.tokens = (&theme.colors).into();
186 theme.radius = px(6.);194 theme.radius = px(6.);
187 theme.radius_lg = px(10.);195 theme.radius_lg = px(10.);
188- theme.font_size = px(14.);196+ theme.font_size = font_size;
189 theme.focus_ring = false;197 theme.focus_ring = false;
190 }198 }
191 199
@@ -198,7 +206,7 @@ pub fn tint(id: &str) -> Hsla {
198 rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into()206 rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into()
199 }207 }
200 208
201-pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Pixels) -> Div {209+pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Rems) -> Div {
202 let initial = name210 let initial = name
203 .chars()211 .chars()
204 .next()212 .next()
@@ -223,7 +231,7 @@ pub fn avatar(
223 palette: Palette,231 palette: Palette,
224 user: &User,232 user: &User,
225 size: Pixels,233 size: Pixels,
226- font: Pixels,234+ font: Rems,
227 avatars: &HashMap<String, Arc<Image>>,235 avatars: &HashMap<String, Arc<Image>>,
228 ) -> Div {236 ) -> Div {
229 let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else {237 let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else {
@@ -249,7 +257,7 @@ pub fn community_icon(
249 palette: Palette,257 palette: Palette,
250 community: &Community,258 community: &Community,
251 size: Pixels,259 size: Pixels,
252- font: Pixels,260+ font: Rems,
253 avatars: &HashMap<String, Arc<Image>>,261 avatars: &HashMap<String, Arc<Image>>,
254 ) -> Div {262 ) -> Div {
255 match &community.kind {263 match &community.kind {
@@ -325,7 +333,7 @@ impl Render for Tip {
325 .border_color(palette.border)333 .border_color(palette.border)
326 .bg(palette.panel)334 .bg(palette.panel)
327 .text_color(palette.text)335 .text_color(palette.text)
328- .text_size(px(12.))336+ .text_size(text(12.))
329 .child(self.0)337 .child(self.0)
330 }338 }
331 }339 }
@@ -394,7 +402,7 @@ pub fn rank_tag(rank: Option<Rank>, palette: Palette) -> Option<Div> {
394 .py(px(1.))402 .py(px(1.))
395 .rounded(px(4.))403 .rounded(px(4.))
396 .bg(palette.hover)404 .bg(palette.hover)
397- .text_size(px(11.))405+ .text_size(text(11.))
398 .text_color(color)406 .text_color(color)
399 .child(label),407 .child(label),
400 )408 )
@@ -598,6 +606,9 @@ impl Yumush {
598 .status_input606 .status_input
599 .update(cx, |input, cx| input.set_value(status, window, cx));607 .update(cx, |input, cx| input.set_value(status, window, cx));
600 }608 }
609+ if view == View::Admin {
610+ self.load_users(window, cx);
611+ }
601 if view == View::CommunitySettings {612 if view == View::CommunitySettings {
602 let name = self613 let name = self
603 .chat614 .chat
@@ -620,7 +631,7 @@ impl Yumush {
620 631
621 pub fn themed(&self, cx: &App) -> Palette {632 pub fn themed(&self, cx: &App) -> Palette {
622 let community = match self.chat.view {633 let community = match self.chat.view {
623- View::Settings => None,634+ View::Settings | View::Admin => None,
624 _ => self.chat.selected_community(),635 _ => self.chat.selected_community(),
625 };636 };
626 palette(cx).for_community(community, &self.chat.hues)637 palette(cx).for_community(community, &self.chat.hues)
@@ -673,6 +684,9 @@ impl Yumush {
673 if self.is_me(&user.id) {684 if self.is_me(&user.id) {
674 self.user = Some(user.clone());685 self.user = Some(user.clone());
675 self.accounts.rename(user);686 self.accounts.rename(user);
687+ if !self.is_staff() && self.chat.view == View::Admin {
688+ self.chat.view = View::Chat;
689+ }
676 }690 }
677 self.request_user_avatar(user, cx);691 self.request_user_avatar(user, cx);
678 }692 }
@@ -848,7 +862,7 @@ impl Render for Yumush {
848 .size_full()862 .size_full()
849 .bg(palette.window)863 .bg(palette.window)
850 .text_color(palette.text)864 .text_color(palette.text)
851- .text_size(px(13.))865+ .text_size(text(13.))
852 .track_focus(&self.focus)866 .track_focus(&self.focus)
853 .on_action(867 .on_action(
854 cx.listener(|this, _: &FocusFind, window, cx| this.chat.focus_find(window, cx)),868 cx.listener(|this, _: &FocusFind, window, cx| this.chat.focus_find(window, cx)),
crates/client/src/gui/admin.rsadded+217 -0
@@ -0,0 +1,217 @@
1+use super::text;
2+use common::{
3+ model::{Role, User},
4+ permission,
5+};
6+use gpui_kit::{
7+ App, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, component::input::Input,
8+ div, prelude::FluentBuilder as _, px,
9+};
10+
11+use super::{
12+ Palette, Yumush, avatar, clickable,
13+ community_settings::search_text,
14+ entity_action, notify_error,
15+ settings_page::{page, section},
16+};
17+
18+impl Yumush {
19+ pub(super) fn is_staff(&self) -> bool {
20+ self.user.as_ref().is_some_and(|me| me.role == Role::Staff)
21+ }
22+
23+ pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context<Self>) {
24+ if !self.is_staff() {
25+ return;
26+ }
27+ let network = self.network.clone();
28+
29+ cx.spawn_in(window, async move |this, cx| {
30+ let users = match network.users().await {
31+ Ok(users) => users,
32+ Err(error) => {
33+ notify_error(&this, cx, error);
34+ return;
35+ }
36+ };
37+
38+ let _ = this.update(cx, |yumush, cx| {
39+ for user in &users {
40+ yumush.request_user_avatar(user, cx);
41+ }
42+ yumush.chat.admin_users = users;
43+ cx.notify();
44+ });
45+ })
46+ .detach();
47+ }
48+
49+ fn set_admin_role(
50+ &mut self,
51+ user_id: &str,
52+ role: Role,
53+ window: &mut Window,
54+ cx: &mut Context<Self>,
55+ ) {
56+ let network = self.network.clone();
57+ let user_id = user_id.to_string();
58+
59+ cx.spawn_in(window, async move |this, cx| {
60+ match network.set_role(&user_id, role).await {
61+ Ok(user) => {
62+ let _ = this.update(cx, |yumush, cx| {
63+ let index = yumush
64+ .chat
65+ .admin_users
66+ .iter()
67+ .position(|existing| existing.id == user.id);
68+ if let Some(index) = index {
69+ yumush.chat.admin_users[index] = user;
70+ }
71+ cx.notify();
72+ });
73+ }
74+ Err(error) => notify_error(&this, cx, error),
75+ }
76+ })
77+ .detach();
78+ }
79+
80+ fn delete_admin_user(&mut self, user_id: &str, window: &mut Window, cx: &mut Context<Self>) {
81+ if self.chat.pending_admin_delete.as_deref() != Some(user_id) {
82+ self.chat.pending_admin_delete = Some(user_id.to_string());
83+ cx.notify();
84+ return;
85+ }
86+ self.chat.pending_admin_delete = None;
87+ let network = self.network.clone();
88+ let user_id = user_id.to_string();
89+
90+ cx.spawn_in(window, async move |this, cx| {
91+ match network.delete_user(&user_id).await {
92+ Ok(()) => {
93+ let _ = this.update(cx, |yumush, cx| {
94+ yumush.chat.admin_users.retain(|user| user.id != user_id);
95+ cx.notify();
96+ });
97+ }
98+ Err(error) => notify_error(&this, cx, error),
99+ }
100+ })
101+ .detach();
102+ }
103+
104+ pub(super) fn admin_page(
105+ &self,
106+ entity: &Entity<Self>,
107+ palette: Palette,
108+ cx: &App,
109+ ) -> impl IntoElement {
110+ let query = search_text(&self.chat.admin_search, cx);
111+ let rows: Vec<Div> = match self.user.as_ref() {
112+ Some(me) => self
113+ .chat
114+ .admin_users
115+ .iter()
116+ .filter(|user| user.username.to_lowercase().contains(query.as_str()))
117+ .map(|user| self.admin_row(user, me, entity, palette))
118+ .collect(),
119+ None => Vec::new(),
120+ };
121+
122+ page(
123+ "admin_scroll",
124+ entity,
125+ palette,
126+ "Admin",
127+ vec![
128+ div()
129+ .child(Input::new(&self.chat.admin_search))
130+ .into_any_element(),
131+ section("Users", palette, rows).into_any_element(),
132+ ],
133+ )
134+ }
135+
136+ fn admin_row(&self, user: &User, me: &User, entity: &Entity<Self>, palette: Palette) -> Div {
137+ let is_self = user.id == me.id;
138+ let staff = user.role == Role::Staff;
139+ let pending_delete = self.chat.pending_admin_delete.as_deref() == Some(user.id.as_str());
140+ let role_id = user.id.clone();
141+ let delete_id = user.id.clone();
142+ let next_role = if staff { Role::User } else { Role::Staff };
143+
144+ let role_button = clickable(
145+ format!("role_{}", user.id),
146+ palette,
147+ entity_action(entity, move |yumush, window, cx| {
148+ yumush.set_admin_role(&role_id, next_role, window, cx)
149+ }),
150+ )
151+ .h(px(28.))
152+ .px(px(8.))
153+ .flex()
154+ .items_center()
155+ .rounded(px(6.))
156+ .text_size(text(13.))
157+ .text_color(palette.muted)
158+ .child(if staff { "Remove staff" } else { "Make staff" });
159+
160+ let delete_button = clickable(
161+ format!("delete_user_{}", user.id),
162+ palette,
163+ entity_action(entity, move |yumush, window, cx| {
164+ yumush.delete_admin_user(&delete_id, window, cx)
165+ }),
166+ )
167+ .h(px(28.))
168+ .px(px(8.))
169+ .flex()
170+ .items_center()
171+ .rounded(px(6.))
172+ .text_size(text(13.))
173+ .border_1()
174+ .border_color(palette.danger.opacity(0.5))
175+ .text_color(palette.danger)
176+ .when(pending_delete, |this| {
177+ this.bg(palette.danger).text_color(palette.on_accent)
178+ })
179+ .child(if pending_delete { "Confirm" } else { "Delete" });
180+
181+ div()
182+ .h(px(48.))
183+ .px(px(12.))
184+ .flex()
185+ .items_center()
186+ .gap(px(8.))
187+ .child(avatar(
188+ palette,
189+ user,
190+ px(20.),
191+ text(10.),
192+ &self.chat.avatars,
193+ ))
194+ .child(
195+ div()
196+ .flex_1()
197+ .min_w_0()
198+ .flex()
199+ .items_center()
200+ .gap(px(6.))
201+ .child(div().truncate().child(user.username.clone()))
202+ .when(staff, |this| {
203+ this.child(
204+ div()
205+ .text_size(text(11.))
206+ .text_color(palette.accent)
207+ .child("Staff"),
208+ )
209+ }),
210+ )
211+ .children(permission::can_set_role(me.role, is_self).then_some(role_button))
212+ .children(
213+ (!is_self && permission::can_delete_user(me.role, is_self, user.role))
214+ .then_some(delete_button),
215+ )
216+ }
217+}
crates/client/src/gui/auth.rsmodified+26 -34
@@ -1,9 +1,11 @@
1+use super::{
2+ settings_page::{segment, segment_track},
3+ text,
4+};
1 use gpui_kit::{5 use gpui_kit::{
2 Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,6 Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
3 component::input::{Input, InputEvent, InputState},7 component::input::{Input, InputEvent, InputState},
4- div,8+ div, px,
5- prelude::FluentBuilder as _,
6- px,
7 };9 };
8 10
9 use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon};11 use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon};
@@ -75,6 +77,14 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) {
75 }77 }
76 78
77 pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div {79 pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div {
80+ frame(palette, Input::new(input))
81+}
82+
83+fn password_field(palette: Palette, input: &Entity<InputState>) -> Div {
84+ frame(palette, Input::new(input).mask_toggle())
85+}
86+
87+fn frame(palette: Palette, input: Input) -> Div {
78 div()88 div()
79 .h(px(32.))89 .h(px(32.))
80 .flex()90 .flex()
@@ -84,7 +94,7 @@ pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div {
84 .border_color(palette.border)94 .border_color(palette.border)
85 .bg(palette.field)95 .bg(palette.field)
86 .child(96 .child(
87- Input::new(input)97+ input
88 .appearance(false)98 .appearance(false)
89 .text_color(palette.text)99 .text_color(palette.text)
90 .flex_1()100 .flex_1()
@@ -113,12 +123,7 @@ impl Yumush {
113 .font_weight(FontWeight::MEDIUM)123 .font_weight(FontWeight::MEDIUM)
114 .child(action_label);124 .child(action_label);
115 125
116- let tabs = div()126+ let tabs = segment_track(palette)
117- .flex()
118- .p(px(3.))
119- .gap(px(3.))
120- .rounded(px(8.))
121- .bg(palette.window)
122 .child(tab(palette, &entity, Route::Login, "Log in", route))127 .child(tab(palette, &entity, Route::Login, "Log in", route))
123 .child(tab(palette, &entity, Route::Register, "Register", route));128 .child(tab(palette, &entity, Route::Register, "Register", route));
124 129
@@ -141,14 +146,14 @@ impl Yumush {
141 .bg(palette.panel)146 .bg(palette.panel)
142 .child(147 .child(
143 div()148 div()
144- .text_size(px(18.))149+ .text_size(text(18.))
145 .font_weight(FontWeight::SEMIBOLD)150 .font_weight(FontWeight::SEMIBOLD)
146 .child("yumush"),151 .child("yumush"),
147 )152 )
148 .children(self.saved_accounts(&entity, palette))153 .children(self.saved_accounts(&entity, palette))
149 .child(tabs)154 .child(tabs)
150 .child(field(palette, &self.auth.username_input))155 .child(field(palette, &self.auth.username_input))
151- .child(field(palette, &self.auth.password_input))156+ .child(password_field(palette, &self.auth.password_input))
152 .child(action_button),157 .child(action_button),
153 )158 )
154 }159 }
@@ -184,7 +189,7 @@ impl Yumush {
184 &account.user_id,189 &account.user_id,
185 &account.username,190 &account.username,
186 px(22.),191 px(22.),
187- px(11.),192+ text(11.),
188 )193 )
189 .rounded_full(),194 .rounded_full(),
190 )195 )
@@ -231,27 +236,14 @@ fn tab(
231 route: Route,236 route: Route,
232 ) -> impl IntoElement {237 ) -> impl IntoElement {
233 let entity = entity.clone();238 let entity = entity.clone();
234- let active = route == target;239+ segment(
235- clickable(label, palette, move |window, cx| {240+ clickable(label, palette, move |window, cx| {
236- entity.update(cx, |this, cx| this.change_page(target, window, cx));241+ entity.update(cx, |this, cx| this.change_page(target, window, cx));
237- })242+ }),
243+ route == target,
244+ palette,
245+ )
238 .flex_1()246 .flex_1()
239- .flex()247+ .text_size(text(12.))
240- .justify_center()
241- .py(px(4.))
242- .rounded(px(6.))
243- .text_size(px(12.))
244- .when(active, |tab| {
245- tab.bg(palette.panel)
246- .border_1()
247- .border_color(palette.border)
248- .text_color(palette.text)
249- .font_weight(FontWeight::MEDIUM)
250- })
251- .when(!active, |tab| {
252- tab.border_1()
253- .border_color(palette.window)
254- .text_color(palette.muted)
255- })
256 .child(label)248 .child(label)
257 }249 }
crates/client/src/gui/chat.rsmodified+24 -12
@@ -1,3 +1,4 @@
1+use super::text;
1 use std::{2 use std::{
2 collections::{HashMap, HashSet},3 collections::{HashMap, HashSet},
3 sync::Arc,4 sync::Arc,
@@ -46,6 +47,7 @@ pub enum View {
46 Chat,47 Chat,
47 Settings,48 Settings,
48 CommunitySettings,49 CommunitySettings,
50+ Admin,
49 }51 }
50 52
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -113,6 +115,9 @@ pub struct Chat {
113 pub(super) friends: Friends,115 pub(super) friends: Friends,
114 pub(super) invitations: Vec<Invitation>,116 pub(super) invitations: Vec<Invitation>,
115 pub(super) pending_user_delete: Option<String>,117 pub(super) pending_user_delete: Option<String>,
118+ pub(super) pending_admin_delete: Option<String>,
119+ pub(super) admin_users: Vec<User>,
120+ pub(super) admin_search: Entity<InputState>,
116 pub(super) voice: HashMap<String, Vec<String>>,121 pub(super) voice: HashMap<String, Vec<String>>,
117 pub(super) voice_state: VoiceState,122 pub(super) voice_state: VoiceState,
118 pub(super) speaking: HashSet<String>,123 pub(super) speaking: HashSet<String>,
@@ -149,7 +154,8 @@ impl Chat {
149 154
150 let ban_search = new_input("Search...", window, cx);155 let ban_search = new_input("Search...", window, cx);
151 let log_search = new_input("Search...", window, cx);156 let log_search = new_input("Search...", window, cx);
152- for search in [&ban_search, &log_search] {157+ let admin_search = new_input("Search...", window, cx);
158+ for search in [&ban_search, &log_search, &admin_search] {
153 cx.subscribe_in(search, window, |_, _, event, window, cx| {159 cx.subscribe_in(search, window, |_, _, event, window, cx| {
154 if matches!(event, InputEvent::Change) {160 if matches!(event, InputEvent::Change) {
155 window.refresh();161 window.refresh();
@@ -191,6 +197,9 @@ impl Chat {
191 user_requests: HashSet::new(),197 user_requests: HashSet::new(),
192 delete_step: DeleteStep::Idle,198 delete_step: DeleteStep::Idle,
193 pending_user_delete: None,199 pending_user_delete: None,
200+ pending_admin_delete: None,
201+ admin_users: vec![],
202+ admin_search,
194 voice: HashMap::new(),203 voice: HashMap::new(),
195 voice_state: VoiceState::Off,204 voice_state: VoiceState::Off,
196 speaking: HashSet::new(),205 speaking: HashSet::new(),
@@ -531,6 +540,8 @@ impl Chat {
531 self.found = None;540 self.found = None;
532 self.select(None);541 self.select(None);
533 self.unread.clear();542 self.unread.clear();
543+ self.admin_users.clear();
544+ self.pending_admin_delete = None;
534 self.view = View::Chat;545 self.view = View::Chat;
535 self.delete_step = DeleteStep::Idle;546 self.delete_step = DeleteStep::Idle;
536 self.voice.clear();547 self.voice.clear();
@@ -591,7 +602,7 @@ fn empty_state(palette: Palette) -> impl IntoElement {
591 .rounded(px(4.))602 .rounded(px(4.))
592 .border_1()603 .border_1()
593 .border_color(palette.border)604 .border_color(palette.border)
594- .text_size(px(11.))605+ .text_size(text(11.))
595 .child(FIND_HINT),606 .child(FIND_HINT),
596 )607 )
597 .child("Find a user")608 .child("Find a user")
@@ -648,7 +659,7 @@ impl RenderOnce for MembersTrigger {
648 .take(3)659 .take(3)
649 .enumerate()660 .enumerate()
650 .map(|(index, user)| {661 .map(|(index, user)| {
651- avatar(palette, user, px(18.), px(9.), &self.avatars)662+ avatar(palette, user, px(18.), text(9.), &self.avatars)
652 .border_2()663 .border_2()
653 .border_color(palette.panel)664 .border_color(palette.panel)
654 .when(index > 0, |this| this.ml(px(-6.)))665 .when(index > 0, |this| this.ml(px(-6.)))
@@ -663,7 +674,7 @@ impl RenderOnce for MembersTrigger {
663 .items_center()674 .items_center()
664 .gap(px(6.))675 .gap(px(6.))
665 .rounded(px(6.))676 .rounded(px(6.))
666- .text_size(px(12.))677+ .text_size(text(12.))
667 .text_color(palette.muted)678 .text_color(palette.muted)
668 .child(div().flex().children(avatars))679 .child(div().flex().children(avatars))
669 .child(self.members.len().to_string()),680 .child(self.members.len().to_string()),
@@ -702,6 +713,7 @@ impl Yumush {
702 .bg(palette.panel)713 .bg(palette.panel)
703 .map(|panel| match self.chat.view {714 .map(|panel| match self.chat.view {
704 View::Settings => panel.child(self.settings_page(entity, palette, cx)),715 View::Settings => panel.child(self.settings_page(entity, palette, cx)),
716+ View::Admin => panel.child(self.admin_page(entity, palette, cx)),
705 View::CommunitySettings => {717 View::CommunitySettings => {
706 panel.child(self.community_settings_page(entity, palette, cx))718 panel.child(self.community_settings_page(entity, palette, cx))
707 }719 }
@@ -731,7 +743,7 @@ impl Yumush {
731 .border_b_2()743 .border_b_2()
732 .border_color(palette.accent)744 .border_color(palette.accent)
733 .children(community.map(|community| {745 .children(community.map(|community| {
734- community_icon(palette, community, px(20.), px(10.), &self.chat.avatars)746+ community_icon(palette, community, px(20.), text(10.), &self.chat.avatars)
735 }))747 }))
736 .child(748 .child(
737 div()749 div()
@@ -1295,7 +1307,7 @@ impl Yumush {
1295 Anchor::TopRight,1307 Anchor::TopRight,
1296 user,1308 user,
1297 entity,1309 entity,
1298- avatar(palette, user, px(20.), px(10.), &self.chat.avatars)1310+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars)
1299 .border_2()1311 .border_2()
1300 .border_color(ring)1312 .border_color(ring)
1301 .cursor_pointer()1313 .cursor_pointer()
@@ -1422,7 +1434,7 @@ fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> im
1422 .items_center()1434 .items_center()
1423 .gap(px(8.))1435 .gap(px(8.))
1424 .rounded(px(6.))1436 .rounded(px(6.))
1425- .child(avatar(palette, user, px(18.), px(9.), &avatars))1437+ .child(avatar(palette, user, px(18.), text(9.), &avatars))
1426 .child(1438 .child(
1427 div()1439 div()
1428 .flex_1()1440 .flex_1()
@@ -1445,7 +1457,7 @@ fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> im
1445 )1457 )
1446 .children((!user.status.is_empty()).then(|| {1458 .children((!user.status.is_empty()).then(|| {
1447 div()1459 div()
1448- .text_size(px(11.))1460+ .text_size(text(11.))
1449 .text_color(palette.muted)1461 .text_color(palette.muted)
1450 .truncate()1462 .truncate()
1451 .child(user.status.clone())1463 .child(user.status.clone())
@@ -1492,8 +1504,8 @@ fn render_message(
1492 .items_center()1504 .items_center()
1493 .gap(px(8.))1505 .gap(px(8.))
1494 .child(match author {1506 .child(match author {
1495- Some(user) => avatar(palette, user, px(20.), px(10.), &chat.avatars),1507+ Some(user) => avatar(palette, user, px(20.), text(10.), &chat.avatars),
1496- None => badge(palette, &message.user_id, username, px(20.), px(10.)).rounded_full(),1508+ None => badge(palette, &message.user_id, username, px(20.), text(10.)).rounded_full(),
1497 })1509 })
1498 .child(1510 .child(
1499 div()1511 div()
@@ -1539,7 +1551,7 @@ fn render_message(
1539 .child(author)1551 .child(author)
1540 .child(1552 .child(
1541 div()1553 div()
1542- .text_size(px(12.))1554+ .text_size(text(12.))
1543 .text_color(palette.muted)1555 .text_color(palette.muted)
1544 .child(id_time(&message.id, "%H:%M")),1556 .child(id_time(&message.id, "%H:%M")),
1545 ),1557 ),
@@ -1571,7 +1583,7 @@ fn render_message(
1571 .when(message.edited, |this| {1583 .when(message.edited, |this| {
1572 this.child(1584 this.child(
1573 div()1585 div()
1574- .text_size(px(11.))1586+ .text_size(text(11.))
1575 .text_color(palette.muted)1587 .text_color(palette.muted)
1576 .child("(edited)"),1588 .child("(edited)"),
1577 )1589 )
crates/client/src/gui/community_settings.rsmodified+12 -11
@@ -1,3 +1,4 @@
1+use super::text;
1 use std::{collections::HashMap, sync::Arc};2 use std::{collections::HashMap, sync::Arc};
2 3
3 use common::{4 use common::{
@@ -98,7 +99,7 @@ impl Yumush {
98 palette,99 palette,
99 community,100 community,
100 px(64.),101 px(64.),
101- px(24.),102+ text(24.),
102 &self.chat.avatars,103 &self.chat.avatars,
103 ),104 ),
104 title: community.name.clone(),105 title: community.name.clone(),
@@ -144,7 +145,7 @@ impl Yumush {
144 .gap(px(8.))145 .gap(px(8.))
145 .child(146 .child(
146 div()147 div()
147- .text_size(px(12.))148+ .text_size(text(12.))
148 .text_color(palette.muted)149 .text_color(palette.muted)
149 .child(bans_count.to_string()),150 .child(bans_count.to_string()),
150 )151 )
@@ -435,7 +436,7 @@ fn view_control(
435 .rounded(px(6.))436 .rounded(px(6.))
436 .border_1()437 .border_1()
437 .border_color(palette.border)438 .border_color(palette.border)
438- .text_size(px(13.))439+ .text_size(text(13.))
439 .child("View")440 .child("View")
440 }441 }
441 442
@@ -469,7 +470,7 @@ fn sort_control<T: Copy + PartialEq + 'static, const N: usize>(
469 .flex()470 .flex()
470 .items_center()471 .items_center()
471 .rounded(px(4.))472 .rounded(px(4.))
472- .text_size(px(12.))473+ .text_size(text(12.))
473 .text_color(if active { palette.text } else { palette.muted })474 .text_color(if active { palette.text } else { palette.muted })
474 .when(active, |this| this.bg(palette.hover))475 .when(active, |this| this.bg(palette.hover))
475 .child(label)476 .child(label)
@@ -486,7 +487,7 @@ fn moderation_body(
486 ) -> impl IntoElement {487 ) -> impl IntoElement {
487 let list = if rows.is_empty() {488 let list = if rows.is_empty() {
488 div()489 div()
489- .text_size(px(13.))490+ .text_size(text(13.))
490 .text_color(palette.muted)491 .text_color(palette.muted)
491 .child(empty)492 .child(empty)
492 .into_any_element()493 .into_any_element()
@@ -503,7 +504,7 @@ fn moderation_body(
503 .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list))504 .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list))
504 }505 }
505 506
506-fn search_text(input: &Entity<InputState>, cx: &App) -> String {507+pub(super) fn search_text(input: &Entity<InputState>, cx: &App) -> String {
507 input.read(cx).text().to_string().trim().to_lowercase()508 input.read(cx).text().to_string().trim().to_lowercase()
508 }509 }
509 510
@@ -577,13 +578,13 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap<String, Arc<Ima
577 entry578 entry
578 .actor579 .actor
579 .as_ref()580 .as_ref()
580- .map(|actor| avatar(palette, actor, px(20.), px(10.), avatars)),581+ .map(|actor| avatar(palette, actor, px(20.), text(10.), avatars)),
581 )582 )
582 .child(div().flex_1().min_w_0().truncate().child(log_text(entry)))583 .child(div().flex_1().min_w_0().truncate().child(log_text(entry)))
583 .child(584 .child(
584 div()585 div()
585 .flex_shrink_0()586 .flex_shrink_0()
586- .text_size(px(11.))587+ .text_size(text(11.))
587 .text_color(palette.muted)588 .text_color(palette.muted)
588 .child(id_time(&entry.id, "%b %-d, %H:%M")),589 .child(id_time(&entry.id, "%b %-d, %H:%M")),
589 )590 )
@@ -608,7 +609,7 @@ fn leave_control(
608 .rounded(px(6.))609 .rounded(px(6.))
609 .border_1()610 .border_1()
610 .border_color(palette.danger.opacity(0.5))611 .border_color(palette.danger.opacity(0.5))
611- .text_size(px(13.))612+ .text_size(text(13.))
612 .text_color(palette.danger)613 .text_color(palette.danger)
613 .child("Leave")614 .child("Leave")
614 }615 }
@@ -629,7 +630,7 @@ fn ban_row(
629 .flex()630 .flex()
630 .items_center()631 .items_center()
631 .gap(px(8.))632 .gap(px(8.))
632- .child(avatar(palette, user, px(20.), px(10.), avatars))633+ .child(avatar(palette, user, px(20.), text(10.), avatars))
633 .child(634 .child(
634 div()635 div()
635 .flex_1()636 .flex_1()
@@ -639,7 +640,7 @@ fn ban_row(
639 .child(user.username.clone())640 .child(user.username.clone())
640 .children(ban.reason.clone().map(|reason| {641 .children(ban.reason.clone().map(|reason| {
641 div()642 div()
642- .text_size(px(11.))643+ .text_size(text(11.))
643 .text_color(palette.muted)644 .text_color(palette.muted)
644 .truncate()645 .truncate()
645 .child(reason)646 .child(reason)
crates/client/src/gui/composer.rsmodified+3 -2
@@ -1,3 +1,4 @@
1+use super::text;
1 use common::{2 use common::{
2 constant::MAXIMUM_FORWARD_MESSAGES,3 constant::MAXIMUM_FORWARD_MESSAGES,
3 validate::{validate_message_body, validate_new_message},4 validate::{validate_message_body, validate_new_message},
@@ -59,7 +60,7 @@ pub fn selection_bar(
59 .flex()60 .flex()
60 .items_center()61 .items_center()
61 .rounded(px(6.))62 .rounded(px(6.))
62- .text_size(px(12.))63+ .text_size(text(12.))
63 .child("Forward"),64 .child("Forward"),
64 )65 )
65 .child(cancel_button(entity, palette))66 .child(cancel_button(entity, palette))
@@ -75,7 +76,7 @@ fn bar(palette: Palette) -> Div {
75 .gap(px(6.))76 .gap(px(6.))
76 .rounded(px(6.))77 .rounded(px(6.))
77 .bg(palette.hover)78 .bg(palette.hover)
78- .text_size(px(12.))79+ .text_size(text(12.))
79 .text_color(palette.muted)80 .text_color(palette.muted)
80 }81 }
81 82
crates/client/src/gui/forward.rsmodified+2 -1
@@ -1,3 +1,4 @@
1+use super::text;
1 use gpui_kit::{2 use gpui_kit::{
2 AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,3 AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,
3 StatefulInteractiveElement, Styled, Window,4 StatefulInteractiveElement, Styled, Window,
@@ -85,7 +86,7 @@ impl Render for Forward {
85 palette,86 palette,
86 community,87 community,
87 px(16.),88 px(16.),
88- px(9.),89+ text(9.),
89 &yumush.chat.avatars,90 &yumush.chat.avatars,
90 ))91 ))
91 .child(92 .child(
crates/client/src/gui/media_view.rsmodified+6 -5
@@ -1,3 +1,4 @@
1+use super::text;
1 use std::{2 use std::{
2 collections::{HashMap, HashSet},3 collections::{HashMap, HashSet},
3 path::PathBuf,4 path::PathBuf,
@@ -568,7 +569,7 @@ fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl
568 )569 )
569 .child(570 .child(
570 div()571 div()
571- .text_size(px(12.))572+ .text_size(text(12.))
572 .text_color(palette.muted)573 .text_color(palette.muted)
573 .child(detail),574 .child(detail),
574 )575 )
@@ -731,7 +732,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement {
731 .bg(palette.panel)732 .bg(palette.panel)
732 .children(embed.site.clone().map(|site| {733 .children(embed.site.clone().map(|site| {
733 div()734 div()
734- .text_size(px(12.))735+ .text_size(text(12.))
735 .text_color(palette.muted)736 .text_color(palette.muted)
736 .child(site)737 .child(site)
737 }))738 }))
@@ -747,7 +748,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement {
747 }))748 }))
748 .children(embed.description.clone().map(|description| {749 .children(embed.description.clone().map(|description| {
749 div()750 div()
750- .text_size(px(13.))751+ .text_size(text(13.))
751 .text_color(palette.body)752 .text_color(palette.body)
752 .line_clamp(3)753 .line_clamp(3)
753 .child(description)754 .child(description)
@@ -781,7 +782,7 @@ pub fn pending_row(
781 .py(px(4.))782 .py(px(4.))
782 .rounded(px(6.))783 .rounded(px(6.))
783 .bg(palette.hover)784 .bg(palette.hover)
784- .text_size(px(12.))785+ .text_size(text(12.))
785 .child(786 .child(
786 div()787 div()
787 .max_w(px(180.))788 .max_w(px(180.))
@@ -812,7 +813,7 @@ pub fn pending_row(
812 div()813 div()
813 .px(px(10.))814 .px(px(10.))
814 .py(px(4.))815 .py(px(4.))
815- .text_size(px(12.))816+ .text_size(text(12.))
816 .text_color(palette.muted)817 .text_color(palette.muted)
817 .child("…"),818 .child("…"),
818 )819 )
crates/client/src/gui/message_actions.rsmodified+3 -2
@@ -1,3 +1,4 @@
1+use super::text;
1 use common::model::{Message, User};2 use common::model::{Message, User};
2 use gpui_kit::{3 use gpui_kit::{
3 Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window,4 Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window,
@@ -26,9 +27,9 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<im
26 .pl(px(8.))27 .pl(px(8.))
27 .border_l_2()28 .border_l_2()
28 .border_color(palette.accent.opacity(0.6))29 .border_color(palette.accent.opacity(0.6))
29- .text_size(px(12.))30+ .text_size(text(12.))
30 .text_color(palette.muted)31 .text_color(palette.muted)
31- .children(author.map(|user| avatar(palette, user, px(14.), px(7.), &chat.avatars)))32+ .children(author.map(|user| avatar(palette, user, px(14.), text(7.), &chat.avatars)))
32 .children(author.map(|user| {33 .children(author.map(|user| {
33 div()34 div()
34 .flex_shrink_0()35 .flex_shrink_0()
crates/client/src/gui/profile.rsmodified+5 -4
@@ -1,3 +1,4 @@
1+use super::text;
1 use std::{collections::HashMap, sync::Arc};2 use std::{collections::HashMap, sync::Arc};
2 3
3 use common::{4 use common::{
@@ -155,7 +156,7 @@ impl Card {
155 .border_1()156 .border_1()
156 .border_color(palette.border)157 .border_color(palette.border)
157 .bg(palette.panel)158 .bg(palette.panel)
158- .child(avatar(palette, &self.user, px(48.), px(18.), avatars))159+ .child(avatar(palette, &self.user, px(48.), text(18.), avatars))
159 .child(160 .child(
160 div()161 div()
161 .flex()162 .flex()
@@ -163,7 +164,7 @@ impl Card {
163 .gap(px(6.))164 .gap(px(6.))
164 .child(165 .child(
165 div()166 div()
166- .text_size(px(15.))167+ .text_size(text(15.))
167 .font_weight(FontWeight::SEMIBOLD)168 .font_weight(FontWeight::SEMIBOLD)
168 .child(self.user.username.clone()),169 .child(self.user.username.clone()),
169 )170 )
@@ -171,13 +172,13 @@ impl Card {
171 )172 )
172 .children((!self.user.status.is_empty()).then(|| {173 .children((!self.user.status.is_empty()).then(|| {
173 div()174 div()
174- .text_size(px(12.))175+ .text_size(text(12.))
175 .text_color(palette.muted)176 .text_color(palette.muted)
176 .child(self.user.status.clone())177 .child(self.user.status.clone())
177 }))178 }))
178 .child(179 .child(
179 div()180 div()
180- .text_size(px(12.))181+ .text_size(text(12.))
181 .text_color(palette.muted)182 .text_color(palette.muted)
182 .child(format!("Joined {}", id_time(&self.user.id, "%b %-d, %Y"))),183 .child(format!("Joined {}", id_time(&self.user.id, "%b %-d, %Y"))),
183 )184 )
crates/client/src/gui/settings_page.rsmodified+82 -39
@@ -1,3 +1,4 @@
1+use super::text;
1 use std::path::Path;2 use std::path::Path;
2 3
3 use common::{error::Error, model::User};4 use common::{error::Error, model::User};
@@ -8,14 +9,14 @@ use gpui_kit::{
8 component::{Icon, input::InputState},9 component::{Icon, input::InputState},
9 div,10 div,
10 prelude::FluentBuilder as _,11 prelude::FluentBuilder as _,
11- px,12+ px, transparent_black,
12 };13 };
13 14
14 use super::{15 use super::{
15 Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable,16 Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable,
16 notify_error, primary_button,17 notify_error, primary_button,
17 };18 };
18-use crate::settings::{self, ThemeChoice};19+use crate::settings::{self, FontSize, ThemeChoice};
19 20
20 const THEMES: [(ThemeChoice, &str); 4] = [21 const THEMES: [(ThemeChoice, &str); 4] = [
21 (ThemeChoice::System, "System"),22 (ThemeChoice::System, "System"),
@@ -24,6 +25,12 @@ const THEMES: [(ThemeChoice, &str); 4] = [
24 (ThemeChoice::Black, "Black"),25 (ThemeChoice::Black, "Black"),
25 ];26 ];
26 27
28+const FONT_SIZES: [(FontSize, &str); 3] = [
29+ (FontSize::Small, "Small"),
30+ (FontSize::Medium, "Medium"),
31+ (FontSize::Large, "Large"),
32+];
33+
27 impl Yumush {34 impl Yumush {
28 pub(super) fn settings_page(35 pub(super) fn settings_page(
29 &self,36 &self,
@@ -37,7 +44,7 @@ impl Yumush {
37 picture_card(44 picture_card(
38 Picture {45 Picture {
39 id: "avatar_picker",46 id: "avatar_picker",
40- image: avatar(palette, user, px(64.), px(24.), &self.chat.avatars),47+ image: avatar(palette, user, px(64.), text(24.), &self.chat.avatars),
41 title: user.username.clone(),48 title: user.username.clone(),
42 subtitle: user.status.clone(),49 subtitle: user.status.clone(),
43 removable: user.avatar_id.is_some(),50 removable: user.avatar_id.is_some(),
@@ -90,16 +97,28 @@ impl Yumush {
90 section(97 section(
91 "Appearance",98 "Appearance",
92 palette,99 palette,
93- vec![row(100+ vec![
94- "Theme",101+ row(
95- segmented(102+ "Theme",
96- THEMES,103+ segmented(
97- self.settings.theme,104+ THEMES,
98- entity,105+ self.settings.theme,
99- palette,106+ entity,
100- Yumush::set_theme,107+ palette,
108+ Yumush::set_theme,
109+ ),
101 ),110 ),
102- )],111+ row(
112+ "Font size",
113+ segmented(
114+ FONT_SIZES,
115+ self.settings.font_size,
116+ entity,
117+ palette,
118+ Yumush::set_font_size,
119+ ),
120+ ),
121+ ],
103 )122 )
104 .into_any_element(),123 .into_any_element(),
105 );124 );
@@ -241,7 +260,13 @@ impl Yumush {
241 260
242 pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context<Self>) {261 pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context<Self>) {
243 self.settings.theme = theme;262 self.settings.theme = theme;
244- settings::apply(theme, cx);263+ settings::apply(theme, self.settings.font_size, cx);
264+ self.commit_settings(cx);
265+ }
266+
267+ pub(super) fn set_font_size(&mut self, font_size: FontSize, cx: &mut Context<Self>) {
268+ self.settings.font_size = font_size;
269+ settings::apply(self.settings.theme, font_size, cx);
245 self.commit_settings(cx);270 self.commit_settings(cx);
246 }271 }
247 272
@@ -346,7 +371,7 @@ fn card(
346 .child(371 .child(
347 div()372 div()
348 .px(px(2.))373 .px(px(2.))
349- .text_size(px(12.))374+ .text_size(text(12.))
350 .font_weight(FontWeight::MEDIUM)375 .font_weight(FontWeight::MEDIUM)
351 .text_color(title_color)376 .text_color(title_color)
352 .child(title),377 .child(title),
@@ -392,7 +417,7 @@ pub(super) fn text_row(
392 .gap(px(6.))417 .gap(px(6.))
393 .child(418 .child(
394 div()419 div()
395- .text_size(px(12.))420+ .text_size(text(12.))
396 .text_color(palette.muted)421 .text_color(palette.muted)
397 .child(editable.label),422 .child(editable.label),
398 )423 )
@@ -471,7 +496,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity<Yumush>, palette: P
471 .gap(px(2.))496 .gap(px(2.))
472 .child(497 .child(
473 div()498 div()
474- .text_size(px(16.))499+ .text_size(text(16.))
475 .font_weight(FontWeight::SEMIBOLD)500 .font_weight(FontWeight::SEMIBOLD)
476 .truncate()501 .truncate()
477 .child(title),502 .child(title),
@@ -479,7 +504,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity<Yumush>, palette: P
479 .when(!subtitle.is_empty(), |this| {504 .when(!subtitle.is_empty(), |this| {
480 this.child(505 this.child(
481 div()506 div()
482- .text_size(px(12.))507+ .text_size(text(12.))
483 .text_color(palette.muted)508 .text_color(palette.muted)
484 .truncate()509 .truncate()
485 .child(subtitle),510 .child(subtitle),
@@ -511,7 +536,7 @@ fn small_button(
511 .flex()536 .flex()
512 .items_center()537 .items_center()
513 .rounded(px(6.))538 .rounded(px(6.))
514- .text_size(px(13.))539+ .text_size(text(13.))
515 .text_color(color)540 .text_color(color)
516 }541 }
517 542
@@ -554,6 +579,35 @@ pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div {
554 .child(control)579 .child(control)
555 }580 }
556 581
582+pub(super) fn segment_track(palette: Palette) -> Div {
583+ div()
584+ .h(px(30.))
585+ .p(px(3.))
586+ .flex()
587+ .gap(px(2.))
588+ .rounded(px(8.))
589+ .border_1()
590+ .border_color(palette.border)
591+ .bg(palette.window)
592+}
593+
594+pub(super) fn segment<E: Styled>(item: E, active: bool, palette: Palette) -> E {
595+ let (background, border, text) = if active {
596+ (palette.field, palette.border, palette.text)
597+ } else {
598+ (transparent_black(), transparent_black(), palette.muted)
599+ };
600+
601+ item.flex()
602+ .items_center()
603+ .justify_center()
604+ .rounded(px(5.))
605+ .border_1()
606+ .border_color(border)
607+ .bg(background)
608+ .text_color(text)
609+}
610+
557 pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>(611 pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>(
558 options: [(T, &'static str); N],612 options: [(T, &'static str); N],
559 selected: T,613 selected: T,
@@ -561,28 +615,17 @@ pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>(
561 palette: Palette,615 palette: Palette,
562 select: fn(&mut Yumush, T, &mut Context<Yumush>),616 select: fn(&mut Yumush, T, &mut Context<Yumush>),
563 ) -> impl IntoElement {617 ) -> impl IntoElement {
564- div()618+ segment_track(palette).children(options.map(|(choice, label)| {
565- .h(px(28.))619+ let entity = entity.clone();
566- .p(px(2.))
567- .flex()
568- .gap(px(2.))
569- .rounded(px(6.))
570- .border_1()
571- .border_color(palette.border)
572- .bg(palette.field)
573- .children(options.map(|(choice, label)| {
574- let entity = entity.clone();
575- let active = choice == selected;
576 620
621+ segment(
577 clickable(label, palette, move |_, cx| {622 clickable(label, palette, move |_, cx| {
578 entity.update(cx, |yumush, cx| select(yumush, choice, cx));623 entity.update(cx, |yumush, cx| select(yumush, choice, cx));
579- })624+ }),
580- .px(px(10.))625+ choice == selected,
581- .flex()626+ palette,
582- .items_center()627+ )
583- .rounded(px(4.))628+ .px(px(10.))
584- .text_color(if active { palette.text } else { palette.muted })629+ .child(label)
585- .when(active, |this| this.bg(palette.hover))630+ }))
586- .child(label)
587- }))
588 }631 }
crates/client/src/gui/sidebar.rsmodified+61 -40
@@ -1,3 +1,4 @@
1+use super::text;
1 use common::{2 use common::{
2 model::{CommunityKind, Invitation, User},3 model::{CommunityKind, Invitation, User},
3 permission,4 permission,
@@ -23,6 +24,7 @@ use super::{
23 clickable, community_icon, community_name, entity_action, hoverable, hoverable_with,24 clickable, community_icon, community_name, entity_action, hoverable, hoverable_with,
24 input_dialog,25 input_dialog,
25 profile::profile_popover,26 profile::profile_popover,
27+ settings_page::{segment, segment_track},
26 social::Relation,28 social::Relation,
27 };29 };
28 30
@@ -93,35 +95,23 @@ impl Yumush {
93 ),95 ),
94 ];96 ];
95 97
96- div()98+ segment_track(palette)
97 .flex_1()99 .flex_1()
98- .h(px(28.))
99- .p(px(2.))
100- .flex()
101- .gap(px(2.))
102- .rounded(px(6.))
103- .border_1()
104- .border_color(palette.border)
105- .bg(palette.field)
106 .children(tabs.map(|(tab, label, alert)| {100 .children(tabs.map(|(tab, label, alert)| {
107- let active = self.chat.tab == tab;101+ let item = segment(
108-102+ clickable(
109- let item = clickable(103+ label,
110- label,104+ palette,
105+ entity_action(entity, move |yumush, window, cx| {
106+ yumush.set_sidebar_tab(tab, window, cx)
107+ }),
108+ ),
109+ self.chat.tab == tab,
111 palette,110 palette,
112- entity_action(entity, move |yumush, window, cx| {
113- yumush.set_sidebar_tab(tab, window, cx)
114- }),
115 )111 )
116 .flex_1()112 .flex_1()
117- .flex()
118- .items_center()
119- .justify_center()
120 .gap(px(6.))113 .gap(px(6.))
121- .rounded(px(4.))114+ .text_size(text(12.))
122- .text_size(px(12.))
123- .text_color(if active { palette.text } else { palette.muted })
124- .when(active, |this| this.bg(palette.hover))
125 .child(label)115 .child(label)
126 .children(alert.then(|| dot(palette)));116 .children(alert.then(|| dot(palette)));
127 117
@@ -204,7 +194,7 @@ impl Yumush {
204 palette,194 palette,
205 community,195 community,
206 px(16.),196 px(16.),
207- px(10.),197+ text(10.),
208 &self.chat.avatars,198 &self.chat.avatars,
209 ),199 ),
210 community.name.clone(),200 community.name.clone(),
@@ -264,7 +254,7 @@ impl Yumush {
264 entry(254 entry(
265 themed,255 themed,
266 active,256 active,
267- community_icon(palette, community, px(20.), px(10.), &self.chat.avatars),257+ community_icon(palette, community, px(20.), text(10.), &self.chat.avatars),
268 community_name(community).to_string(),258 community_name(community).to_string(),
269 alert.then(|| dot(palette).into_any_element()),259 alert.then(|| dot(palette).into_any_element()),
270 ),260 ),
@@ -297,7 +287,7 @@ impl Yumush {
297 entry(287 entry(
298 palette,288 palette,
299 false,289 false,
300- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),290+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
301 user.username.clone(),291 user.username.clone(),
302 Vec::new(),292 Vec::new(),
303 ),293 ),
@@ -360,7 +350,7 @@ impl Yumush {
360 entry(350 entry(
361 palette,351 palette,
362 false,352 false,
363- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),353+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
364 user.username.clone(),354 user.username.clone(),
365 trailing,355 trailing,
366 )356 )
@@ -374,7 +364,7 @@ impl Yumush {
374 entry(364 entry(
375 palette,365 palette,
376 false,366 false,
377- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),367+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
378 user.username.clone(),368 user.username.clone(),
379 [369 [
380 icon_button(370 icon_button(
@@ -406,7 +396,7 @@ impl Yumush {
406 entry(396 entry(
407 palette,397 palette,
408 false,398 false,
409- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),399+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
410 user.username.clone(),400 user.username.clone(),
411 [icon_button(401 [icon_button(
412 format!("cancel_friend_{}", user.id),402 format!("cancel_friend_{}", user.id),
@@ -432,7 +422,7 @@ impl Yumush {
432 let decline_id = community.id.clone();422 let decline_id = community.id.clone();
433 let label = div().flex().flex_col().child(community.name.clone()).child(423 let label = div().flex().flex_col().child(community.name.clone()).child(
434 div()424 div()
435- .text_size(px(11.))425+ .text_size(text(11.))
436 .text_color(palette.muted)426 .text_color(palette.muted)
437 .child(format!("from {}", invitation.inviter.username)),427 .child(format!("from {}", invitation.inviter.username)),
438 );428 );
@@ -440,7 +430,7 @@ impl Yumush {
440 entry(430 entry(
441 palette,431 palette,
442 false,432 false,
443- community_icon(palette, community, px(16.), px(10.), &self.chat.avatars),433+ community_icon(palette, community, px(16.), text(10.), &self.chat.avatars),
444 label,434 label,
445 [435 [
446 icon_button(436 icon_button(
@@ -476,12 +466,10 @@ impl Yumush {
476 466
477 Some(467 Some(
478 div()468 div()
479- .h(px(32.))469+ .h(px(36.))
480- .pl(px(8.))
481- .pr(px(4.))
482 .flex()470 .flex()
483 .items_center()471 .items_center()
484- .gap(px(8.))472+ .gap(px(4.))
485 .child(473 .child(
486 profile_popover(474 profile_popover(
487 "account_profile",475 "account_profile",
@@ -493,10 +481,32 @@ impl Yumush {
493 div()481 div()
494 .flex()482 .flex()
495 .items_center()483 .items_center()
484+ .h(px(36.))
496 .gap(px(8.))485 .gap(px(8.))
497- .px(px(4.))486+ .px(px(6.))
498 .rounded(px(6.))487 .rounded(px(6.))
499- .child(avatar(palette, user, px(20.), px(11.), &self.chat.avatars))488+ .child(
489+ div()
490+ .relative()
491+ .child(avatar(
492+ palette,
493+ user,
494+ px(24.),
495+ text(12.),
496+ &self.chat.avatars,
497+ ))
498+ .child(
499+ div()
500+ .absolute()
501+ .right(px(-2.))
502+ .bottom(px(-2.))
503+ .size(px(10.))
504+ .rounded_full()
505+ .border_2()
506+ .border_color(palette.window)
507+ .bg(status),
508+ ),
509+ )
500 .child(510 .child(
501 div()511 div()
502 .flex_1()512 .flex_1()
@@ -510,7 +520,17 @@ impl Yumush {
510 .flex_1()520 .flex_1()
511 .min_w_0(),521 .min_w_0(),
512 )522 )
513- .child(div().size(px(6.)).rounded_full().bg(status))523+ .children(self.is_staff().then(|| {
524+ icon_button(
525+ "admin_button".to_string(),
526+ palette,
527+ IconName::Shield,
528+ "Admin",
529+ entity_action(entity, |yumush, window, cx| {
530+ yumush.show_view(View::Admin, window, cx)
531+ }),
532+ )
533+ }))
514 .children(self.voice_controls(entity, palette)),534 .children(self.voice_controls(entity, palette)),
515 )535 )
516 }536 }
@@ -641,7 +661,7 @@ fn group(title: &'static str, palette: Palette, rows: Vec<AnyElement>) -> Option
641 .child(661 .child(
642 div()662 div()
643 .px(px(8.))663 .px(px(8.))
644- .text_size(px(11.))664+ .text_size(text(11.))
645 .text_color(palette.muted)665 .text_color(palette.muted)
646 .child(title),666 .child(title),
647 )667 )
@@ -683,7 +703,8 @@ fn icon_button(
683 ) -> AnyElement {703 ) -> AnyElement {
684 clickable(id, palette, on_click)704 clickable(id, palette, on_click)
685 .tip(tip)705 .tip(tip)
686- .size(px(24.))706+ .size(px(26.))
707+ .flex_shrink_0()
687 .flex()708 .flex()
688 .items_center()709 .items_center()
689 .justify_center()710 .justify_center()
crates/client/src/gui/snippet.rsmodified+4 -3
@@ -1,3 +1,4 @@
1+use super::text;
1 use common::model::{Message, Role, SnippetMessage, User};2 use common::model::{Message, Role, SnippetMessage, User};
2 use gpui_kit::{3 use gpui_kit::{
3 Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px,4 Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px,
@@ -30,7 +31,7 @@ pub fn snippet_card(
30 .bg(palette.panel)31 .bg(palette.panel)
31 .child(32 .child(
32 div()33 div()
33- .text_size(px(12.))34+ .text_size(text(12.))
34 .text_color(palette.muted)35 .text_color(palette.muted)
35 .child(header),36 .child(header),
36 )37 )
@@ -60,7 +61,7 @@ fn snippet_row(
60 div()61 div()
61 .flex()62 .flex()
62 .gap(px(8.))63 .gap(px(8.))
63- .child(avatar(palette, &user, px(20.), px(10.), &chat.avatars))64+ .child(avatar(palette, &user, px(20.), text(10.), &chat.avatars))
64 .child(65 .child(
65 div()66 div()
66 .flex_1()67 .flex_1()
@@ -81,7 +82,7 @@ fn snippet_row(
81 )82 )
82 .child(83 .child(
83 div()84 div()
84- .text_size(px(11.))85+ .text_size(text(11.))
85 .text_color(palette.muted)86 .text_color(palette.muted)
86 .child(id_time(&item.id, "%H:%M")),87 .child(id_time(&item.id, "%H:%M")),
87 ),88 ),
crates/client/src/gui/social.rsmodified+4 -3
@@ -1,3 +1,4 @@
1+use super::text;
1 use std::{fmt::Display, future::Future};2 use std::{fmt::Display, future::Future};
2 3
3 use common::{4 use common::{
@@ -398,7 +399,7 @@ fn invite_result(
398 InviteLookup::Idle => None,399 InviteLookup::Idle => None,
399 InviteLookup::Missing => Some(400 InviteLookup::Missing => Some(
400 div()401 div()
401- .text_size(px(13.))402+ .text_size(text(13.))
402 .text_color(palette.muted)403 .text_color(palette.muted)
403 .child("No such user")404 .child("No such user")
404 .into_any_element(),405 .into_any_element(),
@@ -407,7 +408,7 @@ fn invite_result(
407 user_row(user, yumush, palette)408 user_row(user, yumush, palette)
408 .child(409 .child(
409 div()410 div()
410- .text_size(px(13.))411+ .text_size(text(13.))
411 .text_color(palette.muted)412 .text_color(palette.muted)
412 .child("Member"),413 .child("Member"),
413 )414 )
@@ -447,7 +448,7 @@ fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gp
447 palette,448 palette,
448 user,449 user,
449 px(32.),450 px(32.),
450- px(14.),451+ text(14.),
451 &yumush.chat.avatars,452 &yumush.chat.avatars,
452 ))453 ))
453 .child(454 .child(
crates/client/src/gui/voice_settings.rsmodified+17 -1
@@ -20,7 +20,7 @@ use super::{
20 settings_page::{row, segmented},20 settings_page::{row, segmented},
21 };21 };
22 use crate::{22 use crate::{
23- settings::{Activation, SENSITIVITY_DB, VOLUME, VoiceSettings},23+ settings::{Activation, Profile, SENSITIVITY_DB, VOLUME, VoiceSettings},
24 voice::audio::{self, Device, Devices},24 voice::audio::{self, Device, Devices},
25 };25 };
26 26
@@ -29,6 +29,7 @@ const MODES: [(Activation, &str); 2] = [
29 (Activation::VoiceActivity, "Voice activity"),29 (Activation::VoiceActivity, "Voice activity"),
30 (Activation::PushToTalk, "Push to talk"),30 (Activation::PushToTalk, "Push to talk"),
31 ];31 ];
32+const PROFILES: [(Profile, &str); 2] = [(Profile::Voice, "Voice"), (Profile::Music, "Music")];
32 33
33 #[derive(Clone, Copy, PartialEq, Eq)]34 #[derive(Clone, Copy, PartialEq, Eq)]
34 pub(super) enum Side {35 pub(super) enum Side {
@@ -249,6 +250,16 @@ impl Yumush {
249 Yumush::set_voice_mode,250 Yumush::set_voice_mode,
250 ),251 ),
251 ),252 ),
253+ row(
254+ "Profile",
255+ segmented(
256+ PROFILES,
257+ voice.profile,
258+ entity,
259+ palette,
260+ Yumush::set_voice_profile,
261+ ),
262+ ),
252 ];263 ];
253 264
254 if self.chat.voice_community().is_none() {265 if self.chat.voice_community().is_none() {
@@ -370,6 +381,11 @@ impl Yumush {
370 self.commit_settings(cx);381 self.commit_settings(cx);
371 }382 }
372 383
384+ pub(super) fn set_voice_profile(&mut self, profile: Profile, cx: &mut Context<Self>) {
385+ self.settings.voice.profile = profile;
386+ self.commit_settings(cx);
387+ }
388+
373 pub(super) fn capture_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {389 pub(super) fn capture_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
374 window.focus(&self.focus, cx);390 window.focus(&self.focus, cx);
375 self.voice.key = KeyCapture::Waiting;391 self.voice.key = KeyCapture::Waiting;
crates/client/src/main.rsmodified+1 -1
@@ -28,7 +28,7 @@ fn main() {
28 .with_assets(AllAssets)28 .with_assets(AllAssets)
29 .run(move |cx: &mut App| {29 .run(move |cx: &mut App| {
30 init(cx);30 init(cx);
31- settings::apply(settings.theme, cx);31+ settings::apply(settings.theme, settings.font_size, cx);
32 gui::bind_keys(cx);32 gui::bind_keys(cx);
33 33
34 let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx);34 let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx);
crates/client/src/network.rsmodified+22 -1
@@ -9,7 +9,8 @@ use common::{
9 error::Error,9 error::Error,
10 event::Event,10 event::Event,
11 model::{11 model::{
12- Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, User,12+ Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, Role,
13+ User,
13 },14 },
14 network::{15 network::{
15 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,16 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,
@@ -177,6 +178,26 @@ impl NetworkHandle {
177 }178 }
178 }179 }
179 180
181+ pub async fn users(&self) -> Result<Vec<User>, Error> {
182+ match self.request(Request::Users).await? {
183+ Response::Users(users) => Ok(users),
184+ _ => Err(Error::Server),
185+ }
186+ }
187+
188+ pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Error> {
189+ match self
190+ .request(Request::SetRole {
191+ user_id: user_id.to_string(),
192+ role,
193+ })
194+ .await?
195+ {
196+ Response::User(user) => Ok(user),
197+ _ => Err(Error::Server),
198+ }
199+ }
200+
180 pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {201 pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {
181 match self202 match self
182 .request(Request::ReadUser {203 .request(Request::ReadUser {
crates/client/src/settings.rsmodified+64 -2
@@ -2,8 +2,9 @@ use std::{fmt::Display, fs, ops::RangeInclusive, path::PathBuf};
2 2
3 use common::config::Config;3 use common::config::Config;
4 use gpui_kit::{4 use gpui_kit::{
5- App, Global,5+ App, Global, Pixels,
6 component::{Theme, ThemeMode},6 component::{Theme, ThemeMode},
7+ px,
7 };8 };
8 use tracing::warn;9 use tracing::warn;
9 10
@@ -24,6 +25,44 @@ pub struct Look(pub ThemeChoice);
24 25
25 impl Global for Look {}26 impl Global for Look {}
26 27
28+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29+pub enum FontSize {
30+ Small,
31+ Medium,
32+ Large,
33+}
34+
35+pub struct Scale(pub FontSize);
36+
37+impl Global for Scale {}
38+
39+impl FontSize {
40+ fn name(self) -> &'static str {
41+ match self {
42+ FontSize::Small => "small",
43+ FontSize::Medium => "medium",
44+ FontSize::Large => "large",
45+ }
46+ }
47+
48+ fn parse(value: &str) -> Option<Self> {
49+ match value {
50+ "small" => Some(FontSize::Small),
51+ "medium" => Some(FontSize::Medium),
52+ "large" => Some(FontSize::Large),
53+ _ => None,
54+ }
55+ }
56+
57+ pub fn pixels(self) -> Pixels {
58+ match self {
59+ FontSize::Small => px(13.),
60+ FontSize::Medium => px(14.),
61+ FontSize::Large => px(16.),
62+ }
63+ }
64+}
65+
27 impl ThemeChoice {66 impl ThemeChoice {
28 fn name(self) -> &'static str {67 fn name(self) -> &'static str {
29 match self {68 match self {
@@ -51,6 +90,12 @@ pub enum Activation {
51 PushToTalk,90 PushToTalk,
52 }91 }
53 92
93+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94+pub enum Profile {
95+ Voice,
96+ Music,
97+}
98+
54 #[derive(Debug, Clone, PartialEq)]99 #[derive(Debug, Clone, PartialEq)]
55 pub struct VoiceSettings {100 pub struct VoiceSettings {
56 pub sensitivity_db: f32,101 pub sensitivity_db: f32,
@@ -58,6 +103,7 @@ pub struct VoiceSettings {
58 pub output_volume: f32,103 pub output_volume: f32,
59 pub choice: Choice,104 pub choice: Choice,
60 pub activation: Activation,105 pub activation: Activation,
106+ pub profile: Profile,
61 pub push_to_talk_key: String,107 pub push_to_talk_key: String,
62 }108 }
63 109
@@ -69,6 +115,7 @@ impl Default for VoiceSettings {
69 output_volume: 100.0,115 output_volume: 100.0,
70 choice: Choice::default(),116 choice: Choice::default(),
71 activation: Activation::VoiceActivity,117 activation: Activation::VoiceActivity,
118+ profile: Profile::Voice,
72 push_to_talk_key: String::new(),119 push_to_talk_key: String::new(),
73 }120 }
74 }121 }
@@ -77,6 +124,7 @@ impl Default for VoiceSettings {
77 #[derive(Debug, Clone, PartialEq)]124 #[derive(Debug, Clone, PartialEq)]
78 pub struct Settings {125 pub struct Settings {
79 pub theme: ThemeChoice,126 pub theme: ThemeChoice,
127+ pub font_size: FontSize,
80 pub voice: VoiceSettings,128 pub voice: VoiceSettings,
81 }129 }
82 130
@@ -118,6 +166,10 @@ pub fn load() -> Settings {
118 Some("push_to_talk") => Activation::PushToTalk,166 Some("push_to_talk") => Activation::PushToTalk,
119 _ => Activation::VoiceActivity,167 _ => Activation::VoiceActivity,
120 },168 },
169+ profile: match text("voice.profile").as_deref() {
170+ Some("music") => Profile::Music,
171+ _ => Profile::Voice,
172+ },
121 push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(),173 push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(),
122 };174 };
123 175
@@ -125,6 +177,9 @@ pub fn load() -> Settings {
125 theme: text("theme")177 theme: text("theme")
126 .and_then(|value| ThemeChoice::parse(&value))178 .and_then(|value| ThemeChoice::parse(&value))
127 .unwrap_or(ThemeChoice::Dark),179 .unwrap_or(ThemeChoice::Dark),
180+ font_size: text("font_size")
181+ .and_then(|value| FontSize::parse(&value))
182+ .unwrap_or(FontSize::Medium),
128 voice,183 voice,
129 }184 }
130 }185 }
@@ -143,9 +198,14 @@ pub fn save(settings: &Settings) {
143 Activation::VoiceActivity => "voice_activity",198 Activation::VoiceActivity => "voice_activity",
144 Activation::PushToTalk => "push_to_talk",199 Activation::PushToTalk => "push_to_talk",
145 };200 };
201+ let profile = match voice.profile {
202+ Profile::Voice => "voice",
203+ Profile::Music => "music",
204+ };
146 let key = voice.push_to_talk_key.as_str();205 let key = voice.push_to_talk_key.as_str();
147 let content = [206 let content = [
148 line("theme", settings.theme.name()),207 line("theme", settings.theme.name()),
208+ line("font_size", settings.font_size.name()),
149 line("voice.sensitivity", voice.sensitivity_db),209 line("voice.sensitivity", voice.sensitivity_db),
150 line("voice.input_volume", voice.input_volume),210 line("voice.input_volume", voice.input_volume),
151 line("voice.output_volume", voice.output_volume),211 line("voice.output_volume", voice.output_volume),
@@ -158,6 +218,7 @@ pub fn save(settings: &Settings) {
158 voice.choice.output.as_deref().unwrap_or_default(),218 voice.choice.output.as_deref().unwrap_or_default(),
159 ),219 ),
160 line("voice.activation", activation),220 line("voice.activation", activation),
221+ line("voice.profile", profile),
161 line("voice.push_to_talk", key),222 line("voice.push_to_talk", key),
162 ]223 ]
163 .concat();224 .concat();
@@ -172,8 +233,9 @@ pub fn save(settings: &Settings) {
172 }233 }
173 }234 }
174 235
175-pub fn apply(choice: ThemeChoice, cx: &mut App) {236+pub fn apply(choice: ThemeChoice, font_size: FontSize, cx: &mut App) {
176 cx.set_global(Look(choice));237 cx.set_global(Look(choice));
238+ cx.set_global(Scale(font_size));
177 match choice {239 match choice {
178 ThemeChoice::System => Theme::sync_system_appearance(None, cx),240 ThemeChoice::System => Theme::sync_system_appearance(None, cx),
179 ThemeChoice::Light => Theme::change(ThemeMode::Light, None, cx),241 ThemeChoice::Light => Theme::change(ThemeMode::Light, None, cx),
crates/client/src/voice/audio/pipewire.rsmodified+18 -15
@@ -11,9 +11,7 @@ use pipewire as pw;
11 use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType};11 use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType};
12 use spa::pod::Pod;12 use spa::pod::Pod;
13 13
14-use super::{14+use super::{Choice, Device, Devices, Worker, play, record, stereo_bytes, supervise};
15- Choice, Device, Devices, Downmix, Worker, play, record, stereo_bytes, stereo_frame, supervise,
16-};
17 use crate::voice::{Capture, Playback};15 use crate::voice::{Capture, Playback};
18 16
19 const STOP_CHECK: Duration = Duration::from_millis(100);17 const STOP_CHECK: Duration = Duration::from_millis(100);
@@ -133,14 +131,18 @@ fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::Pr
133 props131 props
134 }132 }
135 133
136-fn format_values() -> Option<Vec<u8>> {134+fn format_values(channels: u32) -> Option<Vec<u8>> {
137 let mut info = spa::param::audio::AudioInfoRaw::new();135 let mut info = spa::param::audio::AudioInfoRaw::new();
138 info.set_format(spa::param::audio::AudioFormat::F32LE);136 info.set_format(spa::param::audio::AudioFormat::F32LE);
139 info.set_rate(VOICE_SAMPLE_RATE);137 info.set_rate(VOICE_SAMPLE_RATE);
140 let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize];138 let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize];
141- position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL;139+ if channels == 1 {
142- position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR;140+ position[0] = spa::sys::SPA_AUDIO_CHANNEL_MONO;
143- info.set_channels(2);141+ } else {
142+ position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL;
143+ position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR;
144+ }
145+ info.set_channels(channels);
144 info.set_position(position);146 info.set_position(position);
145 147
146 let object = spa::pod::Object {148 let object = spa::pod::Object {
@@ -178,7 +180,8 @@ fn run(
178 })180 })
179 .register();181 .register();
180 182
181- let values = format_values().ok_or("pipewire format")?;183+ let capture_values = format_values(1).ok_or("pipewire format")?;
184+ let playback_values = format_values(2).ok_or("pipewire format")?;
182 let flags = pw::stream::StreamFlags::AUTOCONNECT185 let flags = pw::stream::StreamFlags::AUTOCONNECT
183 | pw::stream::StreamFlags::MAP_BUFFERS186 | pw::stream::StreamFlags::MAP_BUFFERS
184 | pw::stream::StreamFlags::RT_PROCESS;187 | pw::stream::StreamFlags::RT_PROCESS;
@@ -190,7 +193,6 @@ fn run(
190 )?;193 )?;
191 let capture = capture.cloned();194 let capture = capture.cloned();
192 let connect_capture = capture.is_some();195 let connect_capture = capture.is_some();
193- let mut downmix = Downmix::default();
194 let _capture_listener = capture_stream196 let _capture_listener = capture_stream
195 .add_local_listener_with_user_data(())197 .add_local_listener_with_user_data(())
196 .state_changed(state_watch(&failed))198 .state_changed(state_watch(&failed))
@@ -209,16 +211,17 @@ fn run(
209 let Some(capture) = &capture else {211 let Some(capture) = &capture else {
210 return;212 return;
211 };213 };
212- let frames = bytes214+ let samples = bytes
213- .as_chunks::<BYTES_PER_FRAME>()215+ .as_chunks::<4>()
214 .0216 .0
215 .iter()217 .iter()
216- .map(stereo_frame);218+ .copied()
217- record(capture, downmix.mix(frames));219+ .map(f32::from_le_bytes);
220+ record(capture, samples);
218 })221 })
219 .register()?;222 .register()?;
220 if connect_capture {223 if connect_capture {
221- let mut capture_params = [Pod::from_bytes(&values).ok_or("pipewire format")?];224+ let mut capture_params = [Pod::from_bytes(&capture_values).ok_or("pipewire format")?];
222 capture_stream.connect(225 capture_stream.connect(
223 spa::utils::Direction::Input,226 spa::utils::Direction::Input,
224 None,227 None,
@@ -262,7 +265,7 @@ fn run(
262 *chunk.size_mut() = (frames * BYTES_PER_FRAME) as u32;265 *chunk.size_mut() = (frames * BYTES_PER_FRAME) as u32;
263 })266 })
264 .register()?;267 .register()?;
265- let mut playback_params = [Pod::from_bytes(&values).ok_or("pipewire format")?];268+ let mut playback_params = [Pod::from_bytes(&playback_values).ok_or("pipewire format")?];
266 playback_stream.connect(269 playback_stream.connect(
267 spa::utils::Direction::Output,270 spa::utils::Direction::Output,
268 None,271 None,
crates/client/src/voice/engine.rsmodified+117 -23
@@ -4,27 +4,61 @@ use std::{
4 };4 };
5 5
6 use common::{6 use common::{
7- constant::{VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE},7+ constant::{
8+ MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE,
9+ },
8 voice::{decode_relay, encode_packet},10 voice::{decode_relay, encode_packet},
9 };11 };
10-use ec_opus::{Application, Decoder, Encoder};12+use ec_opus::{Application, Bandwidth, Decoder, Encoder};
13+
14+use crate::settings::Profile;
11 15
12 pub const SILENT_DB: f32 = -100.0;16 pub const SILENT_DB: f32 = -100.0;
13 const JITTER_CAPACITY: usize = 10;17 const JITTER_CAPACITY: usize = 10;
14-const START_FRAMES: usize = 2;18+const FRAME_MS: f32 = 20.0;
19+const MIN_FRAMES: usize = 1;
20+const MAX_FRAMES: usize = 6;
21+const DRIFT_MARGIN: usize = 2;
22+const QUIET: f32 = 0.01;
15 const SPEAKING_WINDOW: Duration = Duration::from_millis(300);23 const SPEAKING_WINDOW: Duration = Duration::from_millis(300);
16 const RESTART_AFTER: Duration = Duration::from_secs(1);24 const RESTART_AFTER: Duration = Duration::from_secs(1);
17 const MAX_DECODE_SAMPLES: usize = 5760;25 const MAX_DECODE_SAMPLES: usize = 5760;
18 const HANGOVER_FRAMES: u32 = 15;26 const HANGOVER_FRAMES: u32 = 15;
27+const FADE_SAMPLES: usize = 240;
28+const EXPECTED_LOSS_PERC: u8 = 10;
19 29
20 fn rms(samples: &[f32]) -> f32 {30 fn rms(samples: &[f32]) -> f32 {
21 (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()31 (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()
22 }32 }
23 33
34+fn soft_clip(sample: f32) -> f32 {
35+ const KNEE: f32 = 0.8;
36+ let magnitude = sample.abs();
37+ if magnitude <= KNEE {
38+ return sample;
39+ }
40+ let over = (magnitude - KNEE) / (1.0 - KNEE);
41+ sample.signum() * (KNEE + (1.0 - KNEE) * over.tanh())
42+}
43+
24 fn db(amplitude: f32) -> f32 {44 fn db(amplitude: f32) -> f32 {
25 (20.0 * amplitude.log10()).max(SILENT_DB)45 (20.0 * amplitude.log10()).max(SILENT_DB)
26 }46 }
27 47
48+fn encoder(profile: Profile) -> Encoder {
49+ let (application, bitrate) = match profile {
50+ Profile::Voice => (Application::Voip, VOICE_BITRATE),
51+ Profile::Music => (Application::Audio, MUSIC_BITRATE),
52+ };
53+ let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder");
54+ encoder.set_bitrate(bitrate as u32);
55+ encoder.set_bandwidth(Some(Bandwidth::Full));
56+ encoder.set_analysis(true);
57+ encoder.set_inband_fec(true);
58+ encoder.set_packet_loss_perc(EXPECTED_LOSS_PERC);
59+ encoder
60+}
61+
28 struct Speaker {62 struct Speaker {
29 decoder: Decoder,63 decoder: Decoder,
30 scratch: Vec<f32>,64 scratch: Vec<f32>,
@@ -33,6 +67,10 @@ struct Speaker {
33 pending: VecDeque<f32>,67 pending: VecDeque<f32>,
34 last_heard: Instant,68 last_heard: Instant,
35 started: bool,69 started: bool,
70+ first_arrival: Instant,
71+ first_sequence: u32,
72+ previous_transit: Option<f32>,
73+ jitter_ms: f32,
36 }74 }
37 75
38 impl Speaker {76 impl Speaker {
@@ -45,23 +83,51 @@ impl Speaker {
45 pending: VecDeque::new(),83 pending: VecDeque::new(),
46 last_heard: now,84 last_heard: now,
47 started: false,85 started: false,
86+ first_arrival: now,
87+ first_sequence: sequence,
88+ previous_transit: None,
89+ jitter_ms: 0.0,
48 }90 }
49 }91 }
50 92
51- fn next_frame(&mut self) -> Option<Vec<f32>> {93+ fn target(&self) -> usize {
52- if self.jitter.is_empty() {94+ ((self.jitter_ms * 2.0 / FRAME_MS).ceil() as usize + 1).clamp(MIN_FRAMES, MAX_FRAMES)
53- return None;95+ }
54- }96+
55- let decoded = match self.jitter.remove(&self.next) {97+ fn decode_next(&mut self) -> (Vec<f32>, bool) {
56- Some(payload) => self.decoder.decode_float(&payload, &mut self.scratch),98+ let (decoded, real) = match (
57- None => self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch),99+ self.jitter.remove(&self.next),
100+ self.jitter.get(&(self.next + 1)),
101+ ) {
102+ (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true),
103+ (None, Some(following)) => (
104+ self.decoder
105+ .decode_fec(following, VOICE_FRAME_SAMPLES, &mut self.scratch),
106+ false,
107+ ),
108+ (None, None) => (
109+ self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch),
110+ false,
111+ ),
58 };112 };
59 self.next += 1;113 self.next += 1;
60 114
61- Some(match decoded {115+ let samples = match decoded {
62 Ok(samples) => self.scratch[..samples].to_vec(),116 Ok(samples) => self.scratch[..samples].to_vec(),
63 Err(_) => vec![0.0; VOICE_FRAME_SAMPLES],117 Err(_) => vec![0.0; VOICE_FRAME_SAMPLES],
64- })118+ };
119+ (samples, real)
120+ }
121+
122+ fn next_frame(&mut self) -> Option<Vec<f32>> {
123+ if self.jitter.is_empty() {
124+ return None;
125+ }
126+ let (mut frame, real) = self.decode_next();
127+ if real && self.jitter.len() > self.target() + DRIFT_MARGIN && rms(&frame) < QUIET {
128+ (frame, _) = self.decode_next();
129+ }
130+ Some(frame)
65 }131 }
66 132
67 fn mix(&mut self, out: &mut [f32]) {133 fn mix(&mut self, out: &mut [f32]) {
@@ -69,6 +135,7 @@ impl Speaker {
69 if self.pending.is_empty() {135 if self.pending.is_empty() {
70 let Some(frame) = self.next_frame() else {136 let Some(frame) = self.next_frame() else {
71 self.started = false;137 self.started = false;
138+ self.previous_transit = None;
72 return;139 return;
73 };140 };
74 self.pending.extend(frame);141 self.pending.extend(frame);
@@ -80,6 +147,7 @@ impl Speaker {
80 147
81 pub struct Engine {148 pub struct Engine {
82 encoder: Encoder,149 encoder: Encoder,
150+ profile: Profile,
83 capture_buffer: Vec<f32>,151 capture_buffer: Vec<f32>,
84 sequence: u32,152 sequence: u32,
85 muted: bool,153 muted: bool,
@@ -90,6 +158,7 @@ pub struct Engine {
90 push_to_talk: bool,158 push_to_talk: bool,
91 talking: bool,159 talking: bool,
92 hangover: u32,160 hangover: u32,
161+ sending: bool,
93 level_db: f32,162 level_db: f32,
94 speakers: HashMap<String, Speaker>,163 speakers: HashMap<String, Speaker>,
95 }164 }
@@ -102,12 +171,9 @@ impl Default for Engine {
102 171
103 impl Engine {172 impl Engine {
104 pub fn new() -> Self {173 pub fn new() -> Self {
105- let mut encoder =
106- Encoder::new(VOICE_SAMPLE_RATE, 1, Application::Voip).expect("opus encoder");
107- encoder.set_bitrate(VOICE_BITRATE as u32);
108-
109 Self {174 Self {
110- encoder,175+ encoder: encoder(Profile::Voice),
176+ profile: Profile::Voice,
111 capture_buffer: Vec::new(),177 capture_buffer: Vec::new(),
112 sequence: 0,178 sequence: 0,
113 muted: false,179 muted: false,
@@ -118,6 +184,7 @@ impl Engine {
118 push_to_talk: false,184 push_to_talk: false,
119 talking: false,185 talking: false,
120 hangover: 0,186 hangover: 0,
187+ sending: false,
121 level_db: SILENT_DB,188 level_db: SILENT_DB,
122 speakers: HashMap::new(),189 speakers: HashMap::new(),
123 }190 }
@@ -129,7 +196,7 @@ impl Engine {
129 let full = self.capture_buffer.len() / VOICE_FRAME_SAMPLES * VOICE_FRAME_SAMPLES;196 let full = self.capture_buffer.len() / VOICE_FRAME_SAMPLES * VOICE_FRAME_SAMPLES;
130 let mut frames: Vec<f32> = self.capture_buffer.drain(..full).collect();197 let mut frames: Vec<f32> = self.capture_buffer.drain(..full).collect();
131 for sample in &mut frames {198 for sample in &mut frames {
132- *sample *= self.input_gain;199+ *sample = soft_clip(*sample * self.input_gain);
133 }200 }
134 201
135 let mut packets = Vec::new();202 let mut packets = Vec::new();
@@ -139,20 +206,35 @@ impl Engine {
139 if loud >= self.gate {206 if loud >= self.gate {
140 self.hangover = HANGOVER_FRAMES;207 self.hangover = HANGOVER_FRAMES;
141 }208 }
142- let speaking = if self.push_to_talk {209+ let talking = if self.push_to_talk {
143 self.talking210 self.talking
144 } else {211 } else {
145 self.hangover > 0212 self.hangover > 0
146 };213 };
147 self.hangover = self.hangover.saturating_sub(1);214 self.hangover = self.hangover.saturating_sub(1);
148- if self.muted || self.deafened || !speaking {215+ let speaking = talking && !self.muted && !self.deafened;
216+ let was_sending = self.sending;
217+ self.sending = speaking;
218+ if !speaking && !was_sending {
149 continue;219 continue;
150 }220 }
151 221
222+ let mut samples = *frame;
223+ if speaking && !was_sending {
224+ for (index, sample) in samples[..FADE_SAMPLES].iter_mut().enumerate() {
225+ *sample *= index as f32 / FADE_SAMPLES as f32;
226+ }
227+ }
228+ if !speaking {
229+ for (index, sample) in samples.iter_mut().enumerate() {
230+ *sample *= 1.0 - index as f32 / VOICE_FRAME_SAMPLES as f32;
231+ }
232+ }
233+
152 let mut payload = [0u8; VOICE_MAX_PAYLOAD];234 let mut payload = [0u8; VOICE_MAX_PAYLOAD];
153 let Ok(length) = self235 let Ok(length) = self
154 .encoder236 .encoder
155- .encode_float(frame, VOICE_FRAME_SAMPLES, &mut payload)237+ .encode_float(&samples, VOICE_FRAME_SAMPLES, &mut payload)
156 else {238 else {
157 continue;239 continue;
158 };240 };
@@ -187,11 +269,18 @@ impl Engine {
187 return;269 return;
188 }270 }
189 271
272+ let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0
273+ - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS;
274+ if let Some(previous) = speaker.previous_transit {
275+ speaker.jitter_ms += ((transit_ms - previous).abs() - speaker.jitter_ms) / 16.0;
276+ }
277+ speaker.previous_transit = Some(transit_ms);
278+
190 speaker.jitter.insert(sequence, payload.to_vec());279 speaker.jitter.insert(sequence, payload.to_vec());
191 while speaker.jitter.len() > JITTER_CAPACITY {280 while speaker.jitter.len() > JITTER_CAPACITY {
192 speaker.jitter.pop_first();281 speaker.jitter.pop_first();
193 }282 }
194- if speaker.jitter.len() >= START_FRAMES {283+ if speaker.jitter.len() >= speaker.target() {
195 speaker.started = true;284 speaker.started = true;
196 }285 }
197 }286 }
@@ -209,7 +298,7 @@ impl Engine {
209 }298 }
210 299
211 for sample in out.iter_mut() {300 for sample in out.iter_mut() {
212- *sample = (*sample * self.output_gain).clamp(-1.0, 1.0);301+ *sample = soft_clip(*sample * self.output_gain);
213 }302 }
214 }303 }
215 304
@@ -241,11 +330,16 @@ impl Engine {
241 input_volume: f32,330 input_volume: f32,
242 output_volume: f32,331 output_volume: f32,
243 push_to_talk: bool,332 push_to_talk: bool,
333+ profile: Profile,
244 ) {334 ) {
245 self.gate = 10f32.powf(sensitivity_db / 20.0);335 self.gate = 10f32.powf(sensitivity_db / 20.0);
246 self.input_gain = input_volume / 100.0;336 self.input_gain = input_volume / 100.0;
247 self.output_gain = output_volume / 100.0;337 self.output_gain = output_volume / 100.0;
248 self.push_to_talk = push_to_talk;338 self.push_to_talk = push_to_talk;
339+ if profile != self.profile {
340+ self.encoder = encoder(profile);
341+ self.profile = profile;
342+ }
249 }343 }
250 344
251 pub fn set_talking(&mut self, talking: bool) {345 pub fn set_talking(&mut self, talking: bool) {
crates/client/src/voice/mod.rsmodified+1 -0
@@ -173,6 +173,7 @@ impl Voice {
173 settings.input_volume,173 settings.input_volume,
174 settings.output_volume,174 settings.output_volume,
175 settings.activation == Activation::PushToTalk,175 settings.activation == Activation::PushToTalk,
176+ settings.profile,
176 );177 );
177 }178 }
178 }179 }
crates/common/src/constant.rsmodified+2 -1
@@ -12,7 +12,8 @@ pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024;
12 pub const MAXIMUM_STATUS_LENGTH: usize = 64;12 pub const MAXIMUM_STATUS_LENGTH: usize = 64;
13 pub const VOICE_SAMPLE_RATE: u32 = 48_000;13 pub const VOICE_SAMPLE_RATE: u32 = 48_000;
14 pub const VOICE_FRAME_SAMPLES: usize = 960;14 pub const VOICE_FRAME_SAMPLES: usize = 960;
15-pub const VOICE_BITRATE: i32 = 32_000;15+pub const VOICE_BITRATE: i32 = 48_000;
16+pub const MUSIC_BITRATE: i32 = 96_000;
16 pub const VOICE_MAX_PAYLOAD: usize = 1000;17 pub const VOICE_MAX_PAYLOAD: usize = 1000;
17 pub const MAXIMUM_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;18 pub const MAXIMUM_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;
18 pub const MAXIMUM_ATTACHMENTS_PER_MESSAGE: usize = 10;19 pub const MAXIMUM_ATTACHMENTS_PER_MESSAGE: usize = 10;
crates/common/src/permission.rsmodified+4 -0
@@ -65,6 +65,10 @@ pub fn can_leave(actor: Option<Rank>) -> bool {
65 actor.is_some() && actor != Some(Rank::Owner)65 actor.is_some() && actor != Some(Rank::Owner)
66 }66 }
67 67
68+pub fn can_set_role(actor: Role, is_self: bool) -> bool {
69+ actor == Role::Staff && !is_self
70+}
71+
68 pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool {72 pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool {
69 is_self || (actor == Role::Staff && target != Role::Staff)73 is_self || (actor == Role::Staff && target != Role::Staff)
70 }74 }
crates/common/src/request.rsmodified+6 -1
@@ -1,6 +1,6 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::model::Rank;3+use crate::model::{Rank, Role};
4 4
5 #[derive(Debug, Clone, Encode, Decode)]5 #[derive(Debug, Clone, Encode, Decode)]
6 pub struct UploadHeader {6 pub struct UploadHeader {
@@ -154,4 +154,9 @@ pub enum Request {
154 Logs {154 Logs {
155 community_id: String,155 community_id: String,
156 },156 },
157+ Users,
158+ SetRole {
159+ user_id: String,
160+ role: Role,
161+ },
157 }162 }
crates/common/src/response.rsmodified+1 -0
@@ -23,4 +23,5 @@ pub enum Response {
23 Done,23 Done,
24 Error(Error),24 Error(Error),
25 Logs(Vec<LogEntry>),25 Logs(Vec<LogEntry>),
26+ Users(Vec<User>),
26 }27 }
crates/server/src/request.rsmodified+71 -48
@@ -3,7 +3,7 @@ use std::{collections::BTreeSet, path::Path, sync::Mutex};
3 use common::{3 use common::{
4 error::Error as CommonError,4 error::Error as CommonError,
5 event::Event,5 event::Event,
6- model::{CommunityKind, LogAction, Member, Rank, User},6+ model::{CommunityKind, LogAction, Member, Rank, Role, User},
7 permission,7 permission,
8 request::Request,8 request::Request,
9 response::Response,9 response::Response,
@@ -70,27 +70,27 @@ async fn dispatch(
70 sign_in(state, user, token, broadcasts)70 sign_in(state, user, token, broadcasts)
71 }71 }
72 Request::Detach => {72 Request::Detach => {
73- authenticated(state)?;73+ authenticated(state, &conn).await?;
74 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;74 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
75 set_state(state, State::Anonymous);75 set_state(state, State::Anonymous);
76 (Response::Done, broadcasts)76 (Response::Done, broadcasts)
77 }77 }
78 Request::Logout => {78 Request::Logout => {
79- let (_, token) = authenticated(state)?;79+ let (_, token) = authenticated(state, &conn).await?;
80 authentication::logout(&token, &conn).await?;80 authentication::logout(&token, &conn).await?;
81 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;81 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
82 set_state(state, State::Anonymous);82 set_state(state, State::Anonymous);
83 (Response::Done, broadcasts)83 (Response::Done, broadcasts)
84 }84 }
85 Request::ReadUser { user_id } => {85 Request::ReadUser { user_id } => {
86- authenticated(state)?;86+ authenticated(state, &conn).await?;
87 (87 (
88 Response::User(user::read(&user_id, &conn).await?),88 Response::User(user::read(&user_id, &conn).await?),
89 Vec::new(),89 Vec::new(),
90 )90 )
91 }91 }
92 Request::UpdateUser { username } => {92 Request::UpdateUser { username } => {
93- let (me, token) = authenticated(state)?;93+ let (me, token) = authenticated(state, &conn).await?;
94 let user = user::update(&me.id, &username, &conn).await?;94 let user = user::update(&me.id, &username, &conn).await?;
95 set_state(95 set_state(
96 state,96 state,
@@ -102,8 +102,20 @@ async fn dispatch(
102 let broadcasts = user_updated(&user, &conn).await?;102 let broadcasts = user_updated(&user, &conn).await?;
103 (Response::User(user), broadcasts)103 (Response::User(user), broadcasts)
104 }104 }
105+ Request::Users => {
106+ let (me, _) = authenticated(state, &conn).await?;
107+ ensure(me.role == Role::Staff)?;
108+ (Response::Users(user::all(&conn).await?), Vec::new())
109+ }
110+ Request::SetRole { user_id, role } => {
111+ let (me, _) = authenticated(state, &conn).await?;
112+ ensure(permission::can_set_role(me.role, me.id == user_id))?;
113+ let user = user::set_role_by_id(&user_id, role, &conn).await?;
114+ let broadcasts = user_updated(&user, &conn).await?;
115+ (Response::User(user), broadcasts)
116+ }
105 Request::UpdateStatus { status } => {117 Request::UpdateStatus { status } => {
106- let (me, token) = authenticated(state)?;118+ let (me, token) = authenticated(state, &conn).await?;
107 let user = user::update_status(&me.id, &status, &conn).await?;119 let user = user::update_status(&me.id, &status, &conn).await?;
108 set_state(120 set_state(
109 state,121 state,
@@ -116,7 +128,7 @@ async fn dispatch(
116 (Response::User(user), broadcasts)128 (Response::User(user), broadcasts)
117 }129 }
118 Request::UpdateAvatar { image } => {130 Request::UpdateAvatar { image } => {
119- let (me, token) = authenticated(state)?;131+ let (me, token) = authenticated(state, &conn).await?;
120 let user = user::set_avatar(&me.id, &image, &mut conn).await?;132 let user = user::set_avatar(&me.id, &image, &mut conn).await?;
121 set_state(133 set_state(
122 state,134 state,
@@ -129,7 +141,7 @@ async fn dispatch(
129 (Response::User(user), broadcasts)141 (Response::User(user), broadcasts)
130 }142 }
131 Request::RemoveAvatar => {143 Request::RemoveAvatar => {
132- let (me, token) = authenticated(state)?;144+ let (me, token) = authenticated(state, &conn).await?;
133 let user = user::remove_avatar(&me.id, &mut conn).await?;145 let user = user::remove_avatar(&me.id, &mut conn).await?;
134 set_state(146 set_state(
135 state,147 state,
@@ -142,14 +154,14 @@ async fn dispatch(
142 (Response::User(user), broadcasts)154 (Response::User(user), broadcasts)
143 }155 }
144 Request::ReadAvatar { avatar_id } => {156 Request::ReadAvatar { avatar_id } => {
145- authenticated(state)?;157+ authenticated(state, &conn).await?;
146 (158 (
147 Response::Avatar(user::avatar(&avatar_id, &conn).await?),159 Response::Avatar(user::avatar(&avatar_id, &conn).await?),
148 Vec::new(),160 Vec::new(),
149 )161 )
150 }162 }
151 Request::DeleteUser { user_id } => {163 Request::DeleteUser { user_id } => {
152- let (me, _) = authenticated(state)?;164+ let (me, _) = authenticated(state, &conn).await?;
153 let target = user::read(&user_id, &conn).await?;165 let target = user::read(&user_id, &conn).await?;
154 ensure(permission::can_delete_user(166 ensure(permission::can_delete_user(
155 me.role,167 me.role,
@@ -184,7 +196,7 @@ async fn dispatch(
184 (Response::User(deleted), broadcasts)196 (Response::User(deleted), broadcasts)
185 }197 }
186 Request::CreateCommunity { name } => {198 Request::CreateCommunity { name } => {
187- let (me, _) = authenticated(state)?;199+ let (me, _) = authenticated(state, &conn).await?;
188 let tx = conn.transaction().await?;200 let tx = conn.transaction().await?;
189 let community = community::create(&name, &tx).await?;201 let community = community::create(&name, &tx).await?;
190 user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?;202 user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?;
@@ -193,14 +205,14 @@ async fn dispatch(
193 (Response::Community(community), Vec::new())205 (Response::Community(community), Vec::new())
194 }206 }
195 Request::ReadCommunity { community_id } => {207 Request::ReadCommunity { community_id } => {
196- let (me, _) = authenticated(state)?;208+ let (me, _) = authenticated(state, &conn).await?;
197 (209 (
198 Response::Community(community::read(&community_id, &me.id, &conn).await?),210 Response::Community(community::read(&community_id, &me.id, &conn).await?),
199 Vec::new(),211 Vec::new(),
200 )212 )
201 }213 }
202 Request::UpdateCommunity { community_id, name } => {214 Request::UpdateCommunity { community_id, name } => {
203- let (me, _) = authenticated(state)?;215+ let (me, _) = authenticated(state, &conn).await?;
204 ensure(!community::is_direct(&community_id, &conn).await?)?;216 ensure(!community::is_direct(&community_id, &conn).await?)?;
205 ensure(permission::can_rename_community(217 ensure(permission::can_rename_community(
206 actor_rank(&me, &community_id, &conn).await?,218 actor_rank(&me, &community_id, &conn).await?,
@@ -218,7 +230,7 @@ async fn dispatch(
218 community_id,230 community_id,
219 image,231 image,
220 } => {232 } => {
221- let (me, _) = authenticated(state)?;233+ let (me, _) = authenticated(state, &conn).await?;
222 ensure(!community::is_direct(&community_id, &conn).await?)?;234 ensure(!community::is_direct(&community_id, &conn).await?)?;
223 ensure(permission::can_rename_community(235 ensure(permission::can_rename_community(
224 actor_rank(&me, &community_id, &conn).await?,236 actor_rank(&me, &community_id, &conn).await?,
@@ -236,7 +248,7 @@ async fn dispatch(
236 (Response::Community(updated), broadcast(event, &members))248 (Response::Community(updated), broadcast(event, &members))
237 }249 }
238 Request::DeleteCommunity { community_id } => {250 Request::DeleteCommunity { community_id } => {
239- let (me, _) = authenticated(state)?;251+ let (me, _) = authenticated(state, &conn).await?;
240 ensure(!community::is_direct(&community_id, &conn).await?)?;252 ensure(!community::is_direct(&community_id, &conn).await?)?;
241 ensure(permission::can_delete_community(253 ensure(permission::can_delete_community(
242 actor_rank(&me, &community_id, &conn).await?,254 actor_rank(&me, &community_id, &conn).await?,
@@ -252,7 +264,7 @@ async fn dispatch(
252 (Response::Community(deleted), broadcast(event, &members))264 (Response::Community(deleted), broadcast(event, &members))
253 }265 }
254 Request::LeaveCommunity { community_id } => {266 Request::LeaveCommunity { community_id } => {
255- let (me, _) = authenticated(state)?;267+ let (me, _) = authenticated(state, &conn).await?;
256 ensure(!community::is_direct(&community_id, &conn).await?)?;268 ensure(!community::is_direct(&community_id, &conn).await?)?;
257 ensure(permission::can_leave(269 ensure(permission::can_leave(
258 actor_rank(&me, &community_id, &conn).await?,270 actor_rank(&me, &community_id, &conn).await?,
@@ -274,14 +286,14 @@ async fn dispatch(
274 (Response::Done, broadcasts)286 (Response::Done, broadcasts)
275 }287 }
276 Request::Communities => {288 Request::Communities => {
277- let (me, _) = authenticated(state)?;289+ let (me, _) = authenticated(state, &conn).await?;
278 (290 (
279 Response::Communities(community::communities_of(&me.id, &conn).await?),291 Response::Communities(community::communities_of(&me.id, &conn).await?),
280 Vec::new(),292 Vec::new(),
281 )293 )
282 }294 }
283 Request::Members { community_id } => {295 Request::Members { community_id } => {
284- let (me, _) = authenticated(state)?;296+ let (me, _) = authenticated(state, &conn).await?;
285 ensure(permission::can_read(297 ensure(permission::can_read(
286 actor_rank(&me, &community_id, &conn).await?,298 actor_rank(&me, &community_id, &conn).await?,
287 ))?;299 ))?;
@@ -295,7 +307,7 @@ async fn dispatch(
295 user_id,307 user_id,
296 reason,308 reason,
297 } => {309 } => {
298- let (me, _) = authenticated(state)?;310+ let (me, _) = authenticated(state, &conn).await?;
299 remove_member(311 remove_member(
300 &me,312 &me,
301 Removal {313 Removal {
@@ -314,7 +326,7 @@ async fn dispatch(
314 user_id,326 user_id,
315 reason,327 reason,
316 } => {328 } => {
317- let (me, _) = authenticated(state)?;329+ let (me, _) = authenticated(state, &conn).await?;
318 remove_member(330 remove_member(
319 &me,331 &me,
320 Removal {332 Removal {
@@ -332,7 +344,7 @@ async fn dispatch(
332 community_id,344 community_id,
333 user_id,345 user_id,
334 } => {346 } => {
335- let (me, _) = authenticated(state)?;347+ let (me, _) = authenticated(state, &conn).await?;
336 ensure(permission::can_unban(348 ensure(permission::can_unban(
337 actor_rank(&me, &community_id, &conn).await?,349 actor_rank(&me, &community_id, &conn).await?,
338 ))?;350 ))?;
@@ -348,7 +360,7 @@ async fn dispatch(
348 (Response::Done, Vec::new())360 (Response::Done, Vec::new())
349 }361 }
350 Request::Bans { community_id } => {362 Request::Bans { community_id } => {
351- let (me, _) = authenticated(state)?;363+ let (me, _) = authenticated(state, &conn).await?;
352 ensure(permission::can_unban(364 ensure(permission::can_unban(
353 actor_rank(&me, &community_id, &conn).await?,365 actor_rank(&me, &community_id, &conn).await?,
354 ))?;366 ))?;
@@ -362,7 +374,7 @@ async fn dispatch(
362 user_id,374 user_id,
363 rank,375 rank,
364 } => {376 } => {
365- let (me, _) = authenticated(state)?;377+ let (me, _) = authenticated(state, &conn).await?;
366 ensure(!community::is_direct(&community_id, &conn).await?)?;378 ensure(!community::is_direct(&community_id, &conn).await?)?;
367 let target = user::read(&user_id, &conn).await?;379 let target = user::read(&user_id, &conn).await?;
368 ensure(permission::can_set_rank(380 ensure(permission::can_set_rank(
@@ -393,7 +405,7 @@ async fn dispatch(
393 attachments,405 attachments,
394 reply_to,406 reply_to,
395 } => {407 } => {
396- let (me, _) = authenticated(state)?;408+ let (me, _) = authenticated(state, &conn).await?;
397 ensure(permission::can_post(409 ensure(permission::can_post(
398 actor_rank(&me, &community_id, &conn).await?,410 actor_rank(&me, &community_id, &conn).await?,
399 ))?;411 ))?;
@@ -417,7 +429,7 @@ async fn dispatch(
417 community_id,429 community_id,
418 snippet,430 snippet,
419 } => {431 } => {
420- let (me, _) = authenticated(state)?;432+ let (me, _) = authenticated(state, &conn).await?;
421 validate_forward(message_ids.len())?;433 validate_forward(message_ids.len())?;
422 ensure(permission::can_post(434 ensure(permission::can_post(
423 actor_rank(&me, &community_id, &conn).await?,435 actor_rank(&me, &community_id, &conn).await?,
@@ -443,7 +455,7 @@ async fn dispatch(
443 (Response::Messages(created), broadcasts)455 (Response::Messages(created), broadcasts)
444 }456 }
445 Request::UpdateMessage { message_id, body } => {457 Request::UpdateMessage { message_id, body } => {
446- let (me, _) = authenticated(state)?;458+ let (me, _) = authenticated(state, &conn).await?;
447 let existing = message::read(&message_id, &conn).await?;459 let existing = message::read(&message_id, &conn).await?;
448 ensure(permission::can_edit_message(existing.user_id == me.id))?;460 ensure(permission::can_edit_message(existing.user_id == me.id))?;
449 let updated = message::update(&message_id, &body, &conn).await?;461 let updated = message::update(&message_id, &body, &conn).await?;
@@ -452,7 +464,7 @@ async fn dispatch(
452 (Response::Message(updated), broadcast(event, &members))464 (Response::Message(updated), broadcast(event, &members))
453 }465 }
454 Request::DeleteMessage { message_id } => {466 Request::DeleteMessage { message_id } => {
455- let (me, _) = authenticated(state)?;467+ let (me, _) = authenticated(state, &conn).await?;
456 let existing = message::read(&message_id, &conn).await?;468 let existing = message::read(&message_id, &conn).await?;
457 let author = user::read(&existing.user_id, &conn).await?;469 let author = user::read(&existing.user_id, &conn).await?;
458 ensure(permission::can_delete_message(470 ensure(permission::can_delete_message(
@@ -479,7 +491,7 @@ async fn dispatch(
479 community_id,491 community_id,
480 before,492 before,
481 } => {493 } => {
482- let (me, _) = authenticated(state)?;494+ let (me, _) = authenticated(state, &conn).await?;
483 ensure(permission::can_read(495 ensure(permission::can_read(
484 actor_rank(&me, &community_id, &conn).await?,496 actor_rank(&me, &community_id, &conn).await?,
485 ))?;497 ))?;
@@ -487,7 +499,7 @@ async fn dispatch(
487 (Response::Messages(messages), Vec::new())499 (Response::Messages(messages), Vec::new())
488 }500 }
489 Request::JoinVoice { community_id } => {501 Request::JoinVoice { community_id } => {
490- let (me, _) = authenticated(state)?;502+ let (me, _) = authenticated(state, &conn).await?;
491 ensure(permission::can_join_voice(503 ensure(permission::can_join_voice(
492 actor_rank(&me, &community_id, &conn).await?,504 actor_rank(&me, &community_id, &conn).await?,
493 ))?;505 ))?;
@@ -516,14 +528,14 @@ async fn dispatch(
516 )528 )
517 }529 }
518 Request::LeaveVoice => {530 Request::LeaveVoice => {
519- authenticated(state)?;531+ authenticated(state, &conn).await?;
520 (532 (
521 Response::Done,533 Response::Done,
522 leave_connection_voice(voice, connection, &conn).await?,534 leave_connection_voice(voice, connection, &conn).await?,
523 )535 )
524 }536 }
525 Request::VoiceParticipants { community_id } => {537 Request::VoiceParticipants { community_id } => {
526- let (me, _) = authenticated(state)?;538+ let (me, _) = authenticated(state, &conn).await?;
527 ensure(permission::can_read(539 ensure(permission::can_read(
528 actor_rank(&me, &community_id, &conn).await?,540 actor_rank(&me, &community_id, &conn).await?,
529 ))?;541 ))?;
@@ -533,14 +545,15 @@ async fn dispatch(
533 )545 )
534 }546 }
535 Request::FindUser { username } => {547 Request::FindUser { username } => {
536- authenticated(state)?;548+ let (me, _) = authenticated(state, &conn).await?;
537 let found = user::by_username(&username, &conn)549 let found = user::by_username(&username, &conn)
538 .await?550 .await?
551+ .filter(|found| found.id != me.id)
539 .ok_or(CommonError::NotFound)?;552 .ok_or(CommonError::NotFound)?;
540 (Response::User(found), Vec::new())553 (Response::User(found), Vec::new())
541 }554 }
542 Request::OpenDirect { user_id } => {555 Request::OpenDirect { user_id } => {
543- let (me, _) = authenticated(state)?;556+ let (me, _) = authenticated(state, &conn).await?;
544 let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?;557 let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?;
545 let broadcasts = if created {558 let broadcasts = if created {
546 let peer_view = community::read(&community.id, &user_id, &conn).await?;559 let peer_view = community::read(&community.id, &user_id, &conn).await?;
@@ -554,26 +567,26 @@ async fn dispatch(
554 (Response::Community(community), broadcasts)567 (Response::Community(community), broadcasts)
555 }568 }
556 Request::Friends => {569 Request::Friends => {
557- let (me, _) = authenticated(state)?;570+ let (me, _) = authenticated(state, &conn).await?;
558 (571 (
559 Response::Friends(friend::state(&me.id, &conn).await?),572 Response::Friends(friend::state(&me.id, &conn).await?),
560 Vec::new(),573 Vec::new(),
561 )574 )
562 }575 }
563 Request::AddFriend { user_id } => {576 Request::AddFriend { user_id } => {
564- let (me, _) = authenticated(state)?;577+ let (me, _) = authenticated(state, &conn).await?;
565 friend::add(&me.id, &user_id, &mut conn).await?;578 friend::add(&me.id, &user_id, &mut conn).await?;
566 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;579 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
567 (Response::Done, broadcasts)580 (Response::Done, broadcasts)
568 }581 }
569 Request::AcceptFriend { user_id } => {582 Request::AcceptFriend { user_id } => {
570- let (me, _) = authenticated(state)?;583+ let (me, _) = authenticated(state, &conn).await?;
571 friend::accept(&me.id, &user_id, &mut conn).await?;584 friend::accept(&me.id, &user_id, &mut conn).await?;
572 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;585 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
573 (Response::Done, broadcasts)586 (Response::Done, broadcasts)
574 }587 }
575 Request::RemoveFriend { user_id } => {588 Request::RemoveFriend { user_id } => {
576- let (me, _) = authenticated(state)?;589+ let (me, _) = authenticated(state, &conn).await?;
577 friend::remove(&me.id, &user_id, &mut conn).await?;590 friend::remove(&me.id, &user_id, &mut conn).await?;
578 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;591 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
579 (Response::Done, broadcasts)592 (Response::Done, broadcasts)
@@ -582,7 +595,7 @@ async fn dispatch(
582 community_id,595 community_id,
583 user_id,596 user_id,
584 } => {597 } => {
585- let (me, _) = authenticated(state)?;598+ let (me, _) = authenticated(state, &conn).await?;
586 ensure(!community::is_direct(&community_id, &conn).await?)?;599 ensure(!community::is_direct(&community_id, &conn).await?)?;
587 ensure(permission::can_read(600 ensure(permission::can_read(
588 actor_rank(&me, &community_id, &conn).await?,601 actor_rank(&me, &community_id, &conn).await?,
@@ -612,14 +625,14 @@ async fn dispatch(
612 (Response::Done, vec![broadcast])625 (Response::Done, vec![broadcast])
613 }626 }
614 Request::Invitations => {627 Request::Invitations => {
615- let (me, _) = authenticated(state)?;628+ let (me, _) = authenticated(state, &conn).await?;
616 (629 (
617 Response::Invitations(invitation::of(&me.id, &conn).await?),630 Response::Invitations(invitation::of(&me.id, &conn).await?),
618 Vec::new(),631 Vec::new(),
619 )632 )
620 }633 }
621 Request::AcceptInvitation { community_id } => {634 Request::AcceptInvitation { community_id } => {
622- let (me, _) = authenticated(state)?;635+ let (me, _) = authenticated(state, &conn).await?;
623 let tx = conn.transaction().await?;636 let tx = conn.transaction().await?;
624 invitation::take(&community_id, &me.id, &tx).await?;637 invitation::take(&community_id, &me.id, &tx).await?;
625 let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;638 let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;
@@ -641,7 +654,7 @@ async fn dispatch(
641 (Response::Community(community), broadcasts)654 (Response::Community(community), broadcasts)
642 }655 }
643 Request::DeclineInvitation { community_id } => {656 Request::DeclineInvitation { community_id } => {
644- let (me, _) = authenticated(state)?;657+ let (me, _) = authenticated(state, &conn).await?;
645 invitation::take(&community_id, &me.id, &conn).await?;658 invitation::take(&community_id, &me.id, &conn).await?;
646 (659 (
647 Response::Done,660 Response::Done,
@@ -649,7 +662,7 @@ async fn dispatch(
649 )662 )
650 }663 }
651 Request::Logs { community_id } => {664 Request::Logs { community_id } => {
652- let (me, _) = authenticated(state)?;665+ let (me, _) = authenticated(state, &conn).await?;
653 ensure(permission::can_read_logs(666 ensure(permission::can_read_logs(
654 actor_rank(&me, &community_id, &conn).await?,667 actor_rank(&me, &community_id, &conn).await?,
655 ))?;668 ))?;
@@ -725,7 +738,7 @@ async fn remove_member(
725 }738 }
726 739
727 async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {740 async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
728- let mut user_ids = BTreeSet::new();741+ let mut user_ids = BTreeSet::from([user.id.clone()]);
729 for community in community::communities_of(&user.id, conn).await? {742 for community in community::communities_of(&user.id, conn).await? {
730 for member in user_community::members(&community.id, conn).await? {743 for member in user_community::members(&community.id, conn).await? {
731 user_ids.insert(member.user.id);744 user_ids.insert(member.user.id);
@@ -831,11 +844,21 @@ fn set_state(state: &Mutex<State>, new_state: State) {
831 *state.lock().unwrap() = new_state;844 *state.lock().unwrap() = new_state;
832 }845 }
833 846
834-fn authenticated(state: &Mutex<State>) -> Result<(User, String), Error> {847+async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<(User, String), Error> {
835- match state.lock().unwrap().clone() {848+ let (cached, token) = match state.lock().unwrap().clone() {
836- State::Anonymous => Err(CommonError::Unauthenticated.into()),849+ State::Anonymous => return Err(CommonError::Unauthenticated.into()),
837- State::Authenticated { user, token } => Ok((user, token)),850+ State::Authenticated { user, token } => (user, token),
838- }851+ };
852+ let user = user::read(&cached.id, conn).await?;
853+ set_state(
854+ state,
855+ State::Authenticated {
856+ user: user.clone(),
857+ token: token.clone(),
858+ },
859+ );
860+
861+ Ok((user, token))
839 }862 }
840 863
841 pub async fn actor_rank(864 pub async fn actor_rank(
crates/server/src/user.rsmodified+37 -4
@@ -28,8 +28,14 @@ fn role_of(row: &Row) -> Result<Role, Error> {
28 pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {28 pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {
29 let mut rows = conn29 let mut rows = conn
30 .query(30 .query(
31- "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username, role, status, avatar_id",31+ "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",
32- (new_id(), username, password_hash),32+ (
33+ new_id(),
34+ username,
35+ password_hash,
36+ Role::User.as_str(),
37+ Role::Staff.as_str(),
38+ ),
33 )39 )
34 .await?;40 .await?;
35 let row = rows.next().await?.ok_or(CommonError::NotFound)?;41 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
@@ -52,7 +58,7 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
52 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {58 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {
53 let mut rows = conn59 let mut rows = conn
54 .query(60 .query(
55- "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1",61+ "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1 COLLATE NOCASE",
56 (username,),62 (username,),
57 )63 )
58 .await?;64 .await?;
@@ -194,6 +200,33 @@ pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<U
194 from_row(&row)200 from_row(&row)
195 }201 }
196 202
203+pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {
204+ let mut rows = conn
205+ .query(
206+ "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id",
207+ (user_id, role.as_str()),
208+ )
209+ .await?;
210+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
211+
212+ from_row(&row)
213+}
214+
215+pub async fn all(conn: &Connection) -> Result<Vec<User>, Error> {
216+ let mut rows = conn
217+ .query(
218+ "SELECT id, username, role, status, avatar_id FROM user ORDER BY username COLLATE NOCASE",
219+ (),
220+ )
221+ .await?;
222+ let mut users = Vec::new();
223+ while let Some(row) = rows.next().await? {
224+ users.push(from_row(&row)?);
225+ }
226+
227+ Ok(users)
228+}
229+
197 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {230 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
198 let mut rows = conn231 let mut rows = conn
199 .query(232 .query(
@@ -274,7 +307,7 @@ mod tests {
274 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();307 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();
275 let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap();308 let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap();
276 309
277- let searched_user = user::by_username("Tahinli", &conn).await.unwrap();310+ let searched_user = user::by_username("tahinli", &conn).await.unwrap();
278 311
279 assert_eq!(Some(created_user), searched_user);312 assert_eq!(Some(created_user), searched_user);
280 }313 }