forge
Explore
Log in

Don't you dare go Hollow

Simplify codebase for ssot, kiss and yagni

Browse files at this commit

f8f75cba4d0856b527f994433c0e9ef69f0704bfAhmet Kaan GümüşParent: 040a711
  • refactor
    • simplify codebase for ssot, kiss and yagni
Show full message
♻️ refactor: simplify codebase for ssot, kiss and yagni

67 changed files +2208 -2911

crates/client/src/accounts.rsmodified+5 -11
@@ -3,6 +3,8 @@ use std::{fs, path::PathBuf};
3 use common::model::User;3 use common::model::User;
4 use tracing::warn;4 use tracing::warn;
5 5
6+use crate::config_file;
7+
6 #[derive(Debug, Clone, PartialEq, Eq)]8 #[derive(Debug, Clone, PartialEq, Eq)]
7 pub struct Account {9 pub struct Account {
8 pub user_id: String,10 pub user_id: String,
@@ -17,11 +19,6 @@ pub struct Accounts {
17 }19 }
18 20
19 impl Accounts {21 impl Accounts {
20- pub fn active(&self) -> Option<&Account> {
21- let active = self.active.as_deref()?;
22- self.list.iter().find(|account| account.user_id == active)
23- }
24-
25 pub fn get(&self, user_id: &str) -> Option<&Account> {22 pub fn get(&self, user_id: &str) -> Option<&Account> {
26 self.list.iter().find(|account| account.user_id == user_id)23 self.list.iter().find(|account| account.user_id == user_id)
27 }24 }
@@ -72,12 +69,9 @@ impl Accounts {
72 }69 }
73 }70 }
74 71
75-fn path() -> Option<PathBuf> {
76- dirs::config_dir().map(|dir| dir.join("yumush").join("accounts"))
77-}
78-
79 pub fn load() -> Accounts {72 pub fn load() -> Accounts {
80- let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else {73+ let Some(content) = config_file("accounts").and_then(|path| fs::read_to_string(path).ok())
74+ else {
81 return Accounts::default();75 return Accounts::default();
82 };76 };
83 let mut accounts = Accounts::default();77 let mut accounts = Accounts::default();
@@ -98,7 +92,7 @@ pub fn load() -> Accounts {
98 }92 }
99 93
100 fn save(accounts: &Accounts) {94 fn save(accounts: &Accounts) {
101- let Some(path) = path() else {95+ let Some(path) = config_file("accounts") else {
102 return;96 return;
103 };97 };
104 let mut content: String = accounts98 let mut content: String = accounts
crates/client/src/avatar.rsmodified+3 -3
@@ -7,7 +7,7 @@ use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterT
7 const QUALITIES: [u8; 3] = [85, 60, 40];7 const QUALITIES: [u8; 3] = [85, 60, 40];
8 8
9 pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> {9 pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Error> {
10- let image = image::load_from_memory(bytes).map_err(decode_error)?;10+ let image = image::load_from_memory(bytes).map_err(image_error)?;
11 let square = center_square(image)11 let square = center_square(image)
12 .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3)12 .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3)
13 .to_rgb8();13 .to_rgb8();
@@ -38,12 +38,12 @@ fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Error> {
38 let mut bytes = Vec::new();38 let mut bytes = Vec::new();
39 JpegEncoder::new_with_quality(&mut bytes, quality)39 JpegEncoder::new_with_quality(&mut bytes, quality)
40 .encode_image(image)40 .encode_image(image)
41- .map_err(decode_error)?;41+ .map_err(image_error)?;
42 42
43 Ok(bytes)43 Ok(bytes)
44 }44 }
45 45
46-fn decode_error(error: image::ImageError) -> Error {46+fn image_error(error: image::ImageError) -> Error {
47 Error::Decode(error.to_string())47 Error::Decode(error.to_string())
48 }48 }
49 49
crates/client/src/embed.rsmodified+8 -5
@@ -325,11 +325,14 @@ fn entity(e: &str) -> Option<char> {
325 "lt" => Some('<'),325 "lt" => Some('<'),
326 "gt" => Some('>'),326 "gt" => Some('>'),
327 "quot" => Some('"'),327 "quot" => Some('"'),
328- "#39" | "#x27" => Some('\''),328+ _ => numeric(e),
329- _ => match e.strip_prefix("#x") {329+ }
330- Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?),330+}
331- None => char::from_u32(e.strip_prefix('#')?.parse().ok()?),331+
332- },332+fn numeric(e: &str) -> Option<char> {
333+ match e.strip_prefix("#x") {
334+ Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?),
335+ None => char::from_u32(e.strip_prefix('#')?.parse().ok()?),
333 }336 }
334 }337 }
335 338
crates/client/src/gui.rsmodified+63 -74
@@ -11,8 +11,8 @@ use common::{
11 error::Error,11 error::Error,
12 event::Event,12 event::Event,
13 model::{13 model::{
14- BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, ServerSettings,14+ BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction,
15- Unread, User, mentions,15+ ServerSettings, Unread, User, mentions,
16 },16 },
17 time::created_at_ms,17 time::created_at_ms,
18 };18 };
@@ -338,9 +338,10 @@ pub fn pop_in<E: IntoElement + Styled + 'static>(
338 element: E,338 element: E,
339 anchor: Anchor,339 anchor: Anchor,
340 ) -> AnimationElement<E> {340 ) -> AnimationElement<E> {
341- let travel = match anchor.is_bottom() {341+ let travel = if anchor.is_bottom() {
342- true => MOTION_TRAVEL,342+ MOTION_TRAVEL
343- false => -MOTION_TRAVEL,343+ } else {
344+ -MOTION_TRAVEL
344 };345 };
345 346
346 element.with_animation(id, motion(), move |element, delta| {347 element.with_animation(id, motion(), move |element, delta| {
@@ -353,9 +354,10 @@ pub fn swap_in<E: IntoElement + Styled + 'static>(
353 element: E,354 element: E,
354 forward: bool,355 forward: bool,
355 ) -> AnimationElement<E> {356 ) -> AnimationElement<E> {
356- let travel = match forward {357+ let travel = if forward {
357- true => MOTION_TRAVEL,358+ MOTION_TRAVEL
358- false => -MOTION_TRAVEL,359+ } else {
360+ -MOTION_TRAVEL
359 };361 };
360 362
361 element.with_animation(id, motion(), move |element, delta| {363 element.with_animation(id, motion(), move |element, delta| {
@@ -662,8 +664,8 @@ impl Yumush {
662 }664 }
663 665
664 pub fn tray_state(&self) -> crate::tray::TrayState {666 pub fn tray_state(&self) -> crate::tray::TrayState {
665- let groups = self.chat.unread_total(true);667+ let groups = self.chat.unread_groups();
666- let direct = self.chat.unread_total(false);668+ let direct = self.chat.unread_direct();
667 crate::tray::TrayState {669 crate::tray::TrayState {
668 messages: groups.messages + direct.messages,670 messages: groups.messages + direct.messages,
669 mentions: groups.mentions + direct.mentions,671 mentions: groups.mentions + direct.mentions,
@@ -787,17 +789,13 @@ impl Yumush {
787 }789 }
788 790
789 fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {791 fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
790- let Some(user) = self.user.take() else {792+ let Some(user) = self.user.clone() else {
791 return;793 return;
792 };794 };
793 self.accounts.forget(&user.id);795 self.accounts.forget(&user.id);
794- self.end_voice(cx);796+ self.end_session(window, cx);
795- self.leave_settings();
796 let network = self.network.clone();797 let network = self.network.clone();
797 798
798- self.chat.reset();
799- self.change_page(Route::Login, window, cx);
800-
801 cx.spawn_in(window, async move |this, cx| {799 cx.spawn_in(window, async move |this, cx| {
802 if let Err(error) = network.logout().await {800 if let Err(error) = network.logout().await {
803 notify_error(&this, cx, error);801 notify_error(&this, cx, error);
@@ -866,7 +864,7 @@ impl Yumush {
866 }864 }
867 865
868 pub fn actor_rank(&self) -> Option<Rank> {866 pub fn actor_rank(&self) -> Option<Rank> {
869- self.user.as_ref().and_then(|me| self.chat.my_rank(me))867+ self.user.as_ref().and_then(|me| self.chat.rank_of(me))
870 }868 }
871 869
872 pub fn community_badge(870 pub fn community_badge(
@@ -952,7 +950,7 @@ impl Yumush {
952 Event::VoiceMuted {950 Event::VoiceMuted {
953 user_id,951 user_id,
954 muted: true,952 muted: true,
955- } if self.is_me(user_id) => self.force_mute(cx),953+ } if self.is_me(user_id) => self.set_muted(true, cx),
956 Event::Typing { .. } => {954 Event::Typing { .. } => {
957 cx.spawn(async move |this, cx| {955 cx.spawn(async move |this, cx| {
958 cx.background_executor().timer(chat::TYPING_TTL).await;956 cx.background_executor().timer(chat::TYPING_TTL).await;
@@ -1015,9 +1013,7 @@ impl Yumush {
1015 .entry(message.community_id.clone())1013 .entry(message.community_id.clone())
1016 .or_insert_with(|| Unread {1014 .or_insert_with(|| Unread {
1017 community_id: message.community_id.clone(),1015 community_id: message.community_id.clone(),
1018- messages: 0,1016+ ..Default::default()
1019- mentions: 0,
1020- last_read: None,
1021 });1017 });
1022 unread.messages += 1;1018 unread.messages += 1;
1023 if mentions(&message.body, &me.username) {1019 if mentions(&message.body, &me.username) {
@@ -1057,7 +1053,7 @@ impl Yumush {
1057 1053
1058 pub(super) fn is_direct(&self, community_id: &str) -> bool {1054 pub(super) fn is_direct(&self, community_id: &str) -> bool {
1059 self.chat.communities().iter().any(|community| {1055 self.chat.communities().iter().any(|community| {
1060- community.id == community_id && matches!(community.kind, CommunityKind::Direct { .. })1056+ community.id == community_id && community.kind.is_direct()
1061 })1057 })
1062 }1058 }
1063 1059
@@ -1128,45 +1124,8 @@ impl Yumush {
1128 let active = window1124 let active = window
1129 .as_ref()1125 .as_ref()
1130 .is_some_and(|window| window.is_window_active());1126 .is_some_and(|window| window.is_window_active());
1131- if let NetworkEvent::Pushed(pushed) = &event1127+ if let NetworkEvent::Pushed(pushed) = &event {
1132- && let Event::MessageCreated(message) = pushed.as_ref()1128+ self.before_pushed(pushed, active, cx);
1133- && self.should_notify(message, active)
1134- {
1135- self.network.play_notification();
1136- }
1137-
1138- if let NetworkEvent::Pushed(pushed) = &event
1139- && let Event::MessageCreated(message) = pushed.as_ref()
1140- {
1141- self.count_message(message, active, cx);
1142- }
1143-
1144- if let NetworkEvent::Pushed(pushed) = &event
1145- && let Event::MessageCreated(message) = pushed.as_ref()
1146- && message.call == Some(CallLog::Declined)
1147- && self.chat.in_voice(&message.community_id)
1148- {
1149- self.end_voice(cx);
1150- }
1151-
1152- if let NetworkEvent::Pushed(pushed) = &event
1153- && let Event::VoiceJoined {
1154- community_id,
1155- user_id,
1156- } = pushed.as_ref()
1157- && self.starts_call(community_id, user_id)
1158- {
1159- self.chat.ringing.insert(community_id.clone());
1160- }
1161-
1162- if let NetworkEvent::Pushed(pushed) = &event
1163- && let Event::VoiceLeft {
1164- community_id,
1165- user_id,
1166- } = pushed.as_ref()
1167- && self.ends_call(community_id, user_id)
1168- {
1169- self.end_voice(cx);
1170 }1129 }
1171 1130
1172 let Some(window) = window else {1131 let Some(window) = window else {
@@ -1188,7 +1147,7 @@ impl Yumush {
1188 NetworkEvent::Disconnected(error) => self.connection.lost(&error),1147 NetworkEvent::Disconnected(error) => self.connection.lost(&error),
1189 NetworkEvent::SessionLost => {1148 NetworkEvent::SessionLost => {
1190 if let Some(user) = &self.user {1149 if let Some(user) = &self.user {
1191- self.accounts.forget(&user.id.clone());1150+ self.accounts.forget(&user.id);
1192 }1151 }
1193 self.end_session(window, cx);1152 self.end_session(window, cx);
1194 }1153 }
@@ -1203,12 +1162,15 @@ impl Yumush {
1203 Event::Removed {1162 Event::Removed {
1204 community_id,1163 community_id,
1205 community_name,1164 community_name,
1206- banned,1165+ sanction,
1207 reason,1166 reason,
1208 } => {1167 } => {
1209 self.leave_voice_in(&community_id, cx);1168 self.leave_voice_in(&community_id, cx);
1210 self.chat.remove_community(&community_id);1169 self.chat.remove_community(&community_id);
1211- let action = if banned { "Banned from" } else { "Kicked from" };1170+ let action = match sanction {
1171+ Sanction::Ban => "Banned from",
1172+ Sanction::Kick => "Kicked from",
1173+ };
1212 let text = match reason {1174 let text = match reason {
1213 Some(reason) => format!("{action} {community_name}: {reason}"),1175 Some(reason) => format!("{action} {community_name}: {reason}"),
1214 None => format!("{action} {community_name}"),1176 None => format!("{action} {community_name}"),
@@ -1220,11 +1182,7 @@ impl Yumush {
1220 self.apply_pushed(Event::CommunityDeleted { community_id }, cx);1182 self.apply_pushed(Event::CommunityDeleted { community_id }, cx);
1221 }1183 }
1222 Event::ReportCreated => self.report_created(window, cx),1184 Event::ReportCreated => self.report_created(window, cx),
1223- Event::Announcement { text } => {1185+ Event::Announcement { text } => self.set_announcement(text),
1224- if let Some(settings) = self.server.as_mut() {
1225- settings.announcement = text;
1226- }
1227- }
1228 event => {1186 event => {
1229 let voice = matches!(1187 let voice = matches!(
1230 event,1188 event,
@@ -1244,6 +1202,41 @@ impl Yumush {
1244 cx.notify();1202 cx.notify();
1245 }1203 }
1246 1204
1205+ fn before_pushed(&mut self, event: &Event, active: bool, cx: &mut Context<Self>) {
1206+ match event {
1207+ Event::MessageCreated(message) => {
1208+ if self.should_notify(message, active) {
1209+ self.network.play_notification();
1210+ }
1211+ self.count_message(message, active, cx);
1212+ if message.call == Some(CallLog::Declined)
1213+ && self.chat.in_voice(&message.community_id)
1214+ {
1215+ self.end_voice(cx);
1216+ }
1217+ }
1218+ Event::VoiceJoined {
1219+ community_id,
1220+ user_id,
1221+ } if self.starts_call(community_id, user_id) => {
1222+ self.chat.ringing.insert(community_id.clone());
1223+ }
1224+ Event::VoiceLeft {
1225+ community_id,
1226+ user_id,
1227+ } if self.ends_call(community_id, user_id) => {
1228+ self.end_voice(cx);
1229+ }
1230+ _ => {}
1231+ }
1232+ }
1233+
1234+ fn set_announcement(&mut self, text: String) {
1235+ if let Some(settings) = self.server.as_mut() {
1236+ settings.announcement = text;
1237+ }
1238+ }
1239+
1247 fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context<Self>) {1240 fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context<Self>) {
1248 match event {1241 match event {
1249 NetworkEvent::Connected => {1242 NetworkEvent::Connected => {
@@ -1257,11 +1250,7 @@ impl Yumush {
1257 | Event::Removed { .. }1250 | Event::Removed { .. }
1258 | Event::CommunityDeleted { .. }1251 | Event::CommunityDeleted { .. }
1259 | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)),1252 | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)),
1260- Event::Announcement { text } => {1253+ Event::Announcement { text } => self.set_announcement(text),
1261- if let Some(settings) = self.server.as_mut() {
1262- settings.announcement = text;
1263- }
1264- }
1265 event => self.apply_pushed(event, cx),1254 event => self.apply_pushed(event, cx),
1266 },1255 },
1267 }1256 }
crates/client/src/gui/auth.rsmodified+6 -14
@@ -68,7 +68,7 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) {
68 .register(&username, &password, invite.as_deref())68 .register(&username, &password, invite.as_deref())
69 .await69 .await
70 }70 }
71- _ => network.login(&username, &password).await,71+ Route::Login | Route::Chat => network.login(&username, &password).await,
72 };72 };
73 73
74 match result {74 match result {
@@ -118,7 +118,7 @@ impl Yumush {
118 let palette = palette(cx);118 let palette = palette(cx);
119 let action_label = match route {119 let action_label = match route {
120 Route::Register => "Register",120 Route::Register => "Register",
121- _ => "Log in",121+ Route::Login | Route::Chat => "Log in",
122 };122 };
123 123
124 let entity = cx.entity();124 let entity = cx.entity();
@@ -134,18 +134,10 @@ impl Yumush {
134 .font_weight(FontWeight::MEDIUM)134 .font_weight(FontWeight::MEDIUM)
135 .child(action_label);135 .child(action_label);
136 136
137- let registration_open = self137+ let server = self.server.as_ref();
138- .server138+ let registration_open = server.is_none_or(|settings| settings.registration_open);
139- .as_ref()139+ let maintenance = server.is_some_and(|settings| settings.maintenance);
140- .is_none_or(|settings| settings.registration_open);140+ let title = server.map_or_else(|| "yumush".to_string(), |settings| settings.name.clone());
141- let maintenance = self
142- .server
143- .as_ref()
144- .is_some_and(|settings| settings.maintenance);
145- let title = self
146- .server
147- .as_ref()
148- .map_or_else(|| "yumush".to_string(), |settings| settings.name.clone());
149 141
150 let tabs = segment_track(palette)142 let tabs = segment_track(palette)
151 .child(tab(palette, &entity, Route::Login, "Log in", route))143 .child(tab(palette, &entity, Route::Login, "Log in", route))
crates/client/src/gui/builder.rsmodified+79 -32
@@ -11,6 +11,8 @@ mod ui;
11 mod users;11 mod users;
12 mod voice;12 mod voice;
13 13
14+use std::{fmt::Display, future::Future};
15+
14 use common::model::{CommunityKind, Member, Role};16 use common::model::{CommunityKind, Member, Role};
15 use gpui_kit::{17 use gpui_kit::{
16 AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement,18 AnyElement, App, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement,
@@ -27,19 +29,7 @@ use super::{
27 Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header,29 Palette, Yumush, chat::View, clickable, entity_action, notify_error, settings_page::header,
28 text,30 text,
29 };31 };
30-32+use crate::network::NetworkHandle;
31-const BUILDER_TABS: [(BuilderTab, &str, IconName); 10] = [
32- (BuilderTab::Overview, "Overview", IconName::LayoutDashboard),
33- (BuilderTab::Users, "Users", IconName::Users),
34- (BuilderTab::Communities, "Communities", IconName::Building2),
35- (BuilderTab::Messages, "Messages", IconName::MessageSquare),
36- (BuilderTab::Voice, "Voice", IconName::Mic),
37- (BuilderTab::Storage, "Storage", IconName::HardDrive),
38- (BuilderTab::Access, "Access", IconName::Key),
39- (BuilderTab::Reports, "Reports", IconName::Flag),
40- (BuilderTab::Server, "Server", IconName::Server),
41- (BuilderTab::Log, "Log", IconName::ScrollText),
42-];
43 33
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]34 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 pub(super) enum BuilderTab {35 pub(super) enum BuilderTab {
@@ -55,6 +45,51 @@ pub(super) enum BuilderTab {
55 Log,45 Log,
56 }46 }
57 47
48+impl BuilderTab {
49+ const ALL: [Self; 10] = [
50+ Self::Overview,
51+ Self::Users,
52+ Self::Communities,
53+ Self::Messages,
54+ Self::Voice,
55+ Self::Storage,
56+ Self::Access,
57+ Self::Reports,
58+ Self::Server,
59+ Self::Log,
60+ ];
61+
62+ fn label(self) -> &'static str {
63+ match self {
64+ Self::Overview => "Overview",
65+ Self::Users => "Users",
66+ Self::Communities => "Communities",
67+ Self::Messages => "Messages",
68+ Self::Voice => "Voice",
69+ Self::Storage => "Storage",
70+ Self::Access => "Access",
71+ Self::Reports => "Reports",
72+ Self::Server => "Server",
73+ Self::Log => "Log",
74+ }
75+ }
76+
77+ fn icon(self) -> IconName {
78+ match self {
79+ Self::Overview => IconName::LayoutDashboard,
80+ Self::Users => IconName::Users,
81+ Self::Communities => IconName::Building2,
82+ Self::Messages => IconName::MessageSquare,
83+ Self::Voice => IconName::Mic,
84+ Self::Storage => IconName::HardDrive,
85+ Self::Access => IconName::Key,
86+ Self::Reports => IconName::Flag,
87+ Self::Server => IconName::Server,
88+ Self::Log => IconName::ScrollText,
89+ }
90+ }
91+}
92+
58 pub(super) struct Transfer {93 pub(super) struct Transfer {
59 pub(super) community_id: String,94 pub(super) community_id: String,
60 pub(super) members: Vec<Member>,95 pub(super) members: Vec<Member>,
@@ -69,10 +104,7 @@ impl Yumush {
69 cx: &App,104 cx: &App,
70 ) -> impl IntoElement {105 ) -> impl IntoElement {
71 let tab = self.chat.builder_tab;106 let tab = self.chat.builder_tab;
72- let title = BUILDER_TABS107+ let title = tab.label();
73- .iter()
74- .find(|(candidate, _, _)| *candidate == tab)
75- .map_or("", |(_, label, _)| label);
76 let body = match tab {108 let body = match tab {
77 BuilderTab::Overview => self109 BuilderTab::Overview => self
78 .overview_rows(palette)110 .overview_rows(palette)
@@ -187,11 +219,7 @@ impl Yumush {
187 .bg(palette.panel)219 .bg(palette.panel)
188 .border_r_1()220 .border_r_1()
189 .border_color(palette.border)221 .border_color(palette.border)
190- .children(222+ .children(BuilderTab::ALL.map(|tab| self.builder_nav_item(tab, entity, palette)))
191- BUILDER_TABS.map(|(tab, label, icon)| {
192- self.builder_nav_item(tab, label, icon, entity, palette)
193- }),
194- )
195 .child(div().flex_1())223 .child(div().flex_1())
196 .child(self.ghost_toggle(entity, palette))224 .child(self.ghost_toggle(entity, palette))
197 }225 }
@@ -199,11 +227,11 @@ impl Yumush {
199 fn builder_nav_item(227 fn builder_nav_item(
200 &self,228 &self,
201 tab: BuilderTab,229 tab: BuilderTab,
202- label: &'static str,
203- icon: IconName,
204 entity: &Entity<Self>,230 entity: &Entity<Self>,
205 palette: Palette,231 palette: Palette,
206 ) -> impl IntoElement {232 ) -> impl IntoElement {
233+ let label = tab.label();
234+ let icon = tab.icon();
207 let active = self.chat.builder_tab == tab;235 let active = self.chat.builder_tab == tab;
208 let color = if active { palette.text } else { palette.muted };236 let color = if active { palette.text } else { palette.muted };
209 let open = (tab == BuilderTab::Reports)237 let open = (tab == BuilderTab::Reports)
@@ -309,22 +337,42 @@ impl Yumush {
309 cx.notify();337 cx.notify();
310 }338 }
311 339
312- pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context<Self>) {340+ pub(super) fn fetch_builder<T, E, Fut>(
341+ &self,
342+ window: &mut Window,
343+ cx: &mut Context<Self>,
344+ fetch: impl FnOnce(NetworkHandle) -> Fut + 'static,
345+ apply: impl FnOnce(&mut Self, T, &mut Context<Self>) + 'static,
346+ ) where
347+ T: 'static,
348+ E: Display + 'static,
349+ Fut: Future<Output = Result<T, E>> + 'static,
350+ {
313 if !self.is_builder() {351 if !self.is_builder() {
314 return;352 return;
315 }353 }
316 let network = self.network.clone();354 let network = self.network.clone();
317 355
318 cx.spawn_in(window, async move |this, cx| {356 cx.spawn_in(window, async move |this, cx| {
319- let accounts = match network.users().await {357+ let value = match fetch(network).await {
320- Ok(accounts) => accounts,358+ Ok(value) => value,
321 Err(error) => {359 Err(error) => {
322 notify_error(&this, cx, error);360 notify_error(&this, cx, error);
323 return;361 return;
324 }362 }
325 };363 };
326 364
327- let _ = this.update(cx, |yumush, cx| {365+ let _ = this.update(cx, |yumush, cx| apply(yumush, value, cx));
366+ })
367+ .detach();
368+ }
369+
370+ pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context<Self>) {
371+ self.fetch_builder(
372+ window,
373+ cx,
374+ |network| async move { network.users().await },
375+ |yumush, accounts, cx| {
328 for account in &accounts {376 for account in &accounts {
329 yumush.request_user_avatar(&account.user, cx);377 yumush.request_user_avatar(&account.user, cx);
330 }378 }
@@ -336,9 +384,8 @@ impl Yumush {
336 yumush.chat.builder_users = accounts;384 yumush.chat.builder_users = accounts;
337 yumush.set_ghost_state(ghost);385 yumush.set_ghost_state(ghost);
338 cx.notify();386 cx.notify();
339- });387+ },
340- })388+ );
341- .detach();
342 }389 }
343 390
344 pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context<Self>) {391 pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -390,7 +437,7 @@ impl Yumush {
390 let _ = this.update(cx, |yumush, cx| {437 let _ = this.update(cx, |yumush, cx| {
391 yumush.set_ghost_state(enabled);438 yumush.set_ghost_state(enabled);
392 if enabled {439 if enabled {
393- yumush.force_mute(cx);440+ yumush.set_muted(true, cx);
394 }441 }
395 cx.notify();442 cx.notify();
396 });443 });
crates/client/src/gui/builder/access.rsmodified+14 -36
@@ -156,49 +156,27 @@ impl Yumush {
156 }156 }
157 157
158 pub(super) fn load_invites(&self, window: &mut Window, cx: &mut Context<Self>) {158 pub(super) fn load_invites(&self, window: &mut Window, cx: &mut Context<Self>) {
159- if !self.is_builder() {159+ self.fetch_builder(
160- return;160+ window,
161- }161+ cx,
162- let network = self.network.clone();162+ |network| async move { network.invite_codes().await },
163-163+ |yumush, codes, cx| {
164- cx.spawn_in(window, async move |this, cx| {
165- let codes = match network.invite_codes().await {
166- Ok(codes) => codes,
167- Err(error) => {
168- notify_error(&this, cx, error);
169- return;
170- }
171- };
172-
173- let _ = this.update(cx, |yumush, cx| {
174 yumush.chat.builder_invites = codes;164 yumush.chat.builder_invites = codes;
175 cx.notify();165 cx.notify();
176- });166+ },
177- })167+ );
178- .detach();
179 }168 }
180 169
181 pub(super) fn load_server_bans(&self, window: &mut Window, cx: &mut Context<Self>) {170 pub(super) fn load_server_bans(&self, window: &mut Window, cx: &mut Context<Self>) {
182- if !self.is_builder() {171+ self.fetch_builder(
183- return;172+ window,
184- }173+ cx,
185- let network = self.network.clone();174+ |network| async move { network.server_bans().await },
186-175+ |yumush, bans, cx| {
187- cx.spawn_in(window, async move |this, cx| {
188- let bans = match network.server_bans().await {
189- Ok(bans) => bans,
190- Err(error) => {
191- notify_error(&this, cx, error);
192- return;
193- }
194- };
195-
196- let _ = this.update(cx, |yumush, cx| {
197 yumush.chat.builder_bans = bans;176 yumush.chat.builder_bans = bans;
198 cx.notify();177 cx.notify();
199- });178+ },
200- })179+ );
201- .detach();
202 }180 }
203 181
204 pub(super) fn create_invite(&mut self, window: &mut Window, cx: &mut Context<Self>) {182 pub(super) fn create_invite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
crates/client/src/gui/builder/backups.rsmodified+17 -48
@@ -4,51 +4,31 @@ use gpui_kit::{
4 component::Icon, div, prelude::FluentBuilder as _, px,4 component::Icon, div, prelude::FluentBuilder as _, px,
5 };5 };
6 6
7-use super::ui::{accent_button, card, card_header, list_row};7+use super::ui::{accent_button, card, card_header, delete_icon_button, icon_button, list_row};
8-use crate::gui::{8+use crate::gui::{DATE, Palette, Yumush, entity_action, millis_time, notify_error, storage, text};
9- DATE, Palette, Tooltip, Yumush, clickable, entity_action, millis_time, notify_error, storage,
10- text,
11-};
12 9
13 fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity<Yumush>, palette: Palette) -> Div {10 fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity<Yumush>, palette: Palette) -> Div {
14 let export_name = info.name.clone();11 let export_name = info.name.clone();
15- let export = clickable(12+ let export = icon_button(
16 format!("export_backup_{}", info.name),13 format!("export_backup_{}", info.name),
14+ IconName::Download,
15+ "Export",
16+ palette.muted,
17 palette,17 palette,
18 entity_action(entity, move |yumush, window, cx| {18 entity_action(entity, move |yumush, window, cx| {
19 yumush.export_backup(&export_name, window, cx)19 yumush.export_backup(&export_name, window, cx)
20 }),20 }),
21- )21+ );
22- .tip("Export")
23- .size(px(26.))
24- .flex()
25- .flex_shrink_0()
26- .items_center()
27- .justify_center()
28- .rounded(px(6.))
29- .text_color(palette.muted)
30- .child(Icon::new(IconName::Download).w(px(14.)).h(px(14.)));
31 22
32 let delete_name = info.name.clone();23 let delete_name = info.name.clone();
33- let delete = clickable(24+ let delete = delete_icon_button(
34 format!("delete_backup_{}", info.name),25 format!("delete_backup_{}", info.name),
26+ pending,
35 palette,27 palette,
36 entity_action(entity, move |yumush, window, cx| {28 entity_action(entity, move |yumush, window, cx| {
37 yumush.delete_backup(&delete_name, window, cx)29 yumush.delete_backup(&delete_name, window, cx)
38 }),30 }),
39- )31+ );
40- .tip(if pending { "Confirm" } else { "Delete" })
41- .size(px(26.))
42- .flex()
43- .flex_shrink_0()
44- .items_center()
45- .justify_center()
46- .rounded(px(6.))
47- .text_color(palette.danger)
48- .when(pending, |this| {
49- this.bg(palette.danger).text_color(palette.on_accent)
50- })
51- .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.)));
52 32
53 list_row()33 list_row()
54 .child(34 .child(
@@ -132,26 +112,15 @@ impl Yumush {
132 }112 }
133 113
134 pub(super) fn load_backups(&self, window: &mut Window, cx: &mut Context<Self>) {114 pub(super) fn load_backups(&self, window: &mut Window, cx: &mut Context<Self>) {
135- if !self.is_builder() {115+ self.fetch_builder(
136- return;116+ window,
137- }117+ cx,
138- let network = self.network.clone();118+ |network| async move { network.backups().await },
139-119+ |yumush, backups, cx| {
140- cx.spawn_in(window, async move |this, cx| {
141- let backups = match network.backups().await {
142- Ok(backups) => backups,
143- Err(error) => {
144- notify_error(&this, cx, error);
145- return;
146- }
147- };
148-
149- let _ = this.update(cx, |yumush, cx| {
150 yumush.backups = backups;120 yumush.backups = backups;
151 cx.notify();121 cx.notify();
152- });122+ },
153- })123+ );
154- .detach();
155 }124 }
156 125
157 fn create_backup(&self, window: &mut Window, cx: &mut Context<Self>) {126 fn create_backup(&self, window: &mut Window, cx: &mut Context<Self>) {
crates/client/src/gui/builder/communities.rsmodified+10 -41
@@ -1,4 +1,4 @@
1-use common::model::{Community, CommunityKind, CommunitySummary, Member, Rank};1+use common::model::{Community, CommunitySummary, Member, Rank};
2 use gpui_kit::{2 use gpui_kit::{
3 AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,3 AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
4 assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px,4 assets::IconName, component::input::Input, div, prelude::FluentBuilder as _, px,
@@ -6,33 +6,13 @@ use gpui_kit::{
6 6
7 use super::{7 use super::{
8 Transfer,8 Transfer,
9- ui::{card, icon_button, pill, plain_button},9+ ui::{card, icon_button, pill, plain_button, rows_body},
10 };10 };
11 use crate::gui::{11 use crate::gui::{
12 Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text,12 Palette, Yumush, avatar, chat::View, community_icon, community_settings::search_text,
13 entity_action, notify_error, profile::user_link, text,13 entity_action, notify_error, profile::user_link, text,
14 };14 };
15 15
16-fn rows_body(rows: Vec<Div>, empty: &str, palette: Palette) -> Div {
17- if rows.is_empty() {
18- return div()
19- .py(px(24.))
20- .flex()
21- .justify_center()
22- .text_size(text(12.))
23- .text_color(palette.muted)
24- .child(empty.to_string());
25- }
26- div()
27- .flex()
28- .flex_col()
29- .children(rows.into_iter().enumerate().map(|(index, row)| {
30- row.when(index > 0, |row| {
31- row.border_t_1().border_color(palette.border)
32- })
33- }))
34-}
35-
36 impl Yumush {16 impl Yumush {
37 pub(super) fn set_builder_community_voice(17 pub(super) fn set_builder_community_voice(
38 &mut self,18 &mut self,
@@ -58,21 +38,11 @@ impl Yumush {
58 }38 }
59 39
60 pub(super) fn load_builder_communities(&self, window: &mut Window, cx: &mut Context<Self>) {40 pub(super) fn load_builder_communities(&self, window: &mut Window, cx: &mut Context<Self>) {
61- if !self.is_builder() {41+ self.fetch_builder(
62- return;42+ window,
63- }43+ cx,
64- let network = self.network.clone();44+ |network| async move { network.all_communities().await },
65-45+ |yumush, summaries, cx| {
66- cx.spawn_in(window, async move |this, cx| {
67- let summaries = match network.all_communities().await {
68- Ok(summaries) => summaries,
69- Err(error) => {
70- notify_error(&this, cx, error);
71- return;
72- }
73- };
74-
75- let _ = this.update(cx, |yumush, cx| {
76 for summary in &summaries {46 for summary in &summaries {
77 if let Some(avatar_id) = &summary.community.avatar_id {47 if let Some(avatar_id) = &summary.community.avatar_id {
78 yumush.request_avatar(avatar_id, cx);48 yumush.request_avatar(avatar_id, cx);
@@ -83,9 +53,8 @@ impl Yumush {
83 }53 }
84 yumush.chat.builder_communities = summaries;54 yumush.chat.builder_communities = summaries;
85 cx.notify();55 cx.notify();
86- });56+ },
87- })57+ );
88- .detach();
89 }58 }
90 59
91 pub(super) fn delete_builder_community(60 pub(super) fn delete_builder_community(
@@ -267,7 +236,7 @@ impl Yumush {
267 ) {236 ) {
268 let community_id = community.id.clone();237 let community_id = community.id.clone();
269 if self.chat.joined(&community_id) {238 if self.chat.joined(&community_id) {
270- let direct = matches!(community.kind, CommunityKind::Direct { .. });239+ let direct = community.kind.is_direct();
271 self.go_to_community(community_id.clone(), direct, window, cx);240 self.go_to_community(community_id.clone(), direct, window, cx);
272 } else {241 } else {
273 self.open_builder_community(community, window, cx);242 self.open_builder_community(community, window, cx);
crates/client/src/gui/builder/log.rsmodified+7 -5
@@ -1,5 +1,5 @@
1 use common::{1 use common::{
2- model::{AdminAction, AdminLogEntry, action_detail, action_name},2+ model::{AdminAction, AdminLogEntry, action_detail},
3 time::{created_at_ms, now_ms},3 time::{created_at_ms, now_ms},
4 };4 };
5 use gpui_kit::{5 use gpui_kit::{
@@ -12,7 +12,9 @@ use gpui_kit::{
12 };12 };
13 use jiff::Timestamp;13 use jiff::Timestamp;
14 14
15-use super::ui::{accent_button, card, day_millis, list_row, pill, toolbar};15+use super::ui::{
16+ accent_button, card, end_of_day_ms, list_row, pill, start_of_day_ms, toolbar,
17+};
16 use crate::gui::STAMP;18 use crate::gui::STAMP;
17 use crate::gui::{19 use crate::gui::{
18 Palette, Yumush,20 Palette, Yumush,
@@ -104,7 +106,7 @@ fn builder_log_csv(entries: &[AdminLogEntry]) -> String {
104 let fields = [106 let fields = [
105 time,107 time,
106 actor,108 actor,
107- action_name(&entry.action).to_string(),109+ entry.action.name().to_string(),
108 target,110 target,
109 entry.community.clone().unwrap_or_default(),111 entry.community.clone().unwrap_or_default(),
110 action_detail(&entry.action).unwrap_or_default(),112 action_detail(&entry.action).unwrap_or_default(),
@@ -220,8 +222,8 @@ impl Yumush {
220 .copied()222 .copied()
221 .filter(|name| *name != "All")223 .filter(|name| *name != "All")
222 .map(str::to_string);224 .map(str::to_string);
223- let after_ms = day_millis(&search_text(&self.chat.builder_log_from, cx), false);225+ let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx));
224- let before_ms = day_millis(&search_text(&self.chat.builder_log_to, cx), true);226+ let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx));
225 let network = self.network.clone();227 let network = self.network.clone();
226 228
227 cx.spawn_in(window, async move |this, cx| {229 cx.spawn_in(window, async move |this, cx| {
crates/client/src/gui/builder/messages.rsmodified+9 -11
@@ -4,7 +4,10 @@ use gpui_kit::{
4 assets::IconName, div, prelude::FluentBuilder as _, px,4 assets::IconName, div, prelude::FluentBuilder as _, px,
5 };5 };
6 6
7-use super::ui::{accent_button, card, day_millis, icon_button, list_card, list_row};7+use super::ui::{
8+ accent_button, card, delete_icon_button, end_of_day_ms, icon_button, list_card, list_row,
9+ start_of_day_ms,
10+};
8 use crate::gui::YEAR_STAMP;11 use crate::gui::YEAR_STAMP;
9 use crate::gui::{12 use crate::gui::{
10 Palette, Yumush,13 Palette, Yumush,
@@ -36,19 +39,14 @@ fn message_hit_row(
36 yumush.jump_to(community_id.clone(), false, window, cx)39 yumush.jump_to(community_id.clone(), false, window, cx)
37 }),40 }),
38 );41 );
39- let delete = icon_button(42+ let delete = delete_icon_button(
40 format!("delete_message_{}", hit.message.id),43 format!("delete_message_{}", hit.message.id),
41- IconName::Trash,44+ pending,
42- if pending { "Confirm" } else { "Delete" },
43- palette.danger,
44 palette,45 palette,
45 entity_action(entity, move |yumush, window, cx| {46 entity_action(entity, move |yumush, window, cx| {
46 yumush.delete_builder_message(&message_id, window, cx)47 yumush.delete_builder_message(&message_id, window, cx)
47 }),48 }),
48- )49+ );
49- .when(pending, |this| {
50- this.bg(palette.danger).text_color(palette.on_accent)
51- });
52 let purge = hit.author.as_ref().map(|author| {50 let purge = hit.author.as_ref().map(|author| {
53 let user_id = author.id.clone();51 let user_id = author.id.clone();
54 icon_button(52 icon_button(
@@ -211,8 +209,8 @@ impl Yumush {
211 let community = search_text(&self.chat.builder_message_community, cx);209 let community = search_text(&self.chat.builder_message_community, cx);
212 let user_id = self.resolve_user(&username);210 let user_id = self.resolve_user(&username);
213 let community_id = self.resolve_community(&community);211 let community_id = self.resolve_community(&community);
214- let after_ms = day_millis(&search_text(&self.chat.builder_message_from, cx), false);212+ let after_ms = start_of_day_ms(&search_text(&self.chat.builder_message_from, cx));
215- let before_ms = day_millis(&search_text(&self.chat.builder_message_to, cx), true);213+ let before_ms = end_of_day_ms(&search_text(&self.chat.builder_message_to, cx));
216 let text = (!text.is_empty()).then_some(text);214 let text = (!text.is_empty()).then_some(text);
217 let network = self.network.clone();215 let network = self.network.clone();
218 216
crates/client/src/gui/builder/overview.rsmodified+9 -22
@@ -3,7 +3,7 @@ use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px
3 use jiff::Timestamp;3 use jiff::Timestamp;
4 4
5 use super::ui::{card, card_header, stat_tile};5 use super::ui::{card, card_header, stat_tile};
6-use crate::gui::{DAY, Palette, Yumush, notify_error, storage, text};6+use crate::gui::{DAY, Palette, Yumush, storage, text};
7 7
8 const CHART_HEIGHT: f32 = 80.;8 const CHART_HEIGHT: f32 = 80.;
9 9
@@ -103,31 +103,18 @@ fn bar_chart(
103 103
104 impl Yumush {104 impl Yumush {
105 pub(super) fn load_overview(&self, window: &mut Window, cx: &mut Context<Self>) {105 pub(super) fn load_overview(&self, window: &mut Window, cx: &mut Context<Self>) {
106- if !self.is_builder() {106+ self.fetch_builder(
107- return;107+ window,
108- }108+ cx,
109- let network = self.network.clone();109+ |network| async move {
110-
111- cx.spawn_in(window, async move |this, cx| {
112- let loaded = async {
113 Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?))110 Ok::<_, Error>((network.overview().await?, network.daily_stats(30).await?))
114- }111+ },
115- .await;112+ |yumush, (overview, stats), cx| {
116- let (overview, stats) = match loaded {
117- Ok(loaded) => loaded,
118- Err(error) => {
119- notify_error(&this, cx, error);
120- return;
121- }
122- };
123-
124- let _ = this.update(cx, |yumush, cx| {
125 yumush.chat.builder_overview = Some(overview);113 yumush.chat.builder_overview = Some(overview);
126 yumush.chat.builder_stats = stats;114 yumush.chat.builder_stats = stats;
127 cx.notify();115 cx.notify();
128- });116+ },
129- })117+ );
130- .detach();
131 }118 }
132 119
133 pub(super) fn overview_rows(&self, palette: Palette) -> Vec<Div> {120 pub(super) fn overview_rows(&self, palette: Palette) -> Vec<Div> {
crates/client/src/gui/builder/reports.rsmodified+21 -39
@@ -2,7 +2,7 @@ use std::future::Future;
2 2
3 use common::{3 use common::{
4 error::Error,4 error::Error,
5- model::{Report, ReportStatus},5+ model::{BanScope, Report, ReportStatus},
6 };6 };
7 use gpui_kit::{7 use gpui_kit::{
8 AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window,8 AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window,
@@ -48,50 +48,33 @@ fn status_color(status: ReportStatus, palette: Palette) -> Hsla {
48 48
49 impl Yumush {49 impl Yumush {
50 pub(super) fn load_open_reports(&self, window: &mut Window, cx: &mut Context<Self>) {50 pub(super) fn load_open_reports(&self, window: &mut Window, cx: &mut Context<Self>) {
51- if !self.is_builder() {51+ self.fetch_builder(
52- return;52+ window,
53- }53+ cx,
54- let network = self.network.clone();54+ |network| async move {
55-55+ network
56- cx.spawn_in(window, async move |this, cx| {56+ .reports(Some(ReportStatus::Open))
57- let count = match network.reports(Some(ReportStatus::Open)).await {57+ .await
58- Ok(reports) => reports.len(),58+ .map(|reports| reports.len())
59- Err(error) => {59+ },
60- notify_error(&this, cx, error);60+ |yumush, count, cx| {
61- return;
62- }
63- };
64-
65- let _ = this.update(cx, |yumush, cx| {
66 yumush.chat.open_reports = count;61 yumush.chat.open_reports = count;
67 cx.notify();62 cx.notify();
68- });63+ },
69- })64+ );
70- .detach();
71 }65 }
72 66
73 pub(super) fn load_reports(&self, window: &mut Window, cx: &mut Context<Self>) {67 pub(super) fn load_reports(&self, window: &mut Window, cx: &mut Context<Self>) {
74- if !self.is_builder() {
75- return;
76- }
77 let status = self.chat.report_filter;68 let status = self.chat.report_filter;
78- let network = self.network.clone();69+ self.fetch_builder(
79-70+ window,
80- cx.spawn_in(window, async move |this, cx| {71+ cx,
81- let reports = match network.reports(status).await {72+ move |network| async move { network.reports(status).await },
82- Ok(reports) => reports,73+ |yumush, reports, cx| {
83- Err(error) => {
84- notify_error(&this, cx, error);
85- return;
86- }
87- };
88-
89- let _ = this.update(cx, |yumush, cx| {
90 yumush.chat.builder_reports = reports;74 yumush.chat.builder_reports = reports;
91 cx.notify();75 cx.notify();
92- });76+ },
93- })77+ );
94- .detach();
95 }78 }
96 79
97 pub(super) fn refresh_reports(&self, window: &mut Window, cx: &mut Context<Self>) {80 pub(super) fn refresh_reports(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -177,7 +160,7 @@ impl Yumush {
177 let reason = reason.to_string();160 let reason = reason.to_string();
178 self.report_action(window, cx, move |network| async move {161 self.report_action(window, cx, move |network| async move {
179 network162 network
180- .ban_user(&user_id, Some(reason.as_str()), false)163+ .ban_user(&user_id, Some(reason.as_str()), BanScope::Account)
181 .await164 .await
182 });165 });
183 }166 }
@@ -390,7 +373,6 @@ impl Yumush {
390 danger_button(373 danger_button(
391 format!("ban_report_{}", report.id),374 format!("ban_report_{}", report.id),
392 "Ban",375 "Ban",
393- false,
394 palette,376 palette,
395 entity_action(entity, move |yumush, window, cx| {377 entity_action(entity, move |yumush, window, cx| {
396 yumush.ban_report_target(&ban_id, &ban_reason, window, cx)378 yumush.ban_report_target(&ban_id, &ban_reason, window, cx)
crates/client/src/gui/builder/server.rsmodified+36 -74
@@ -1,10 +1,20 @@
1 use common::model::ServerSettings;1 use common::model::ServerSettings;
2-use gpui_kit::{AnyElement, Context, Entity, IntoElement, Window};2+use gpui_kit::{
3+ AnyElement, App, Context, Entity, IntoElement, Window, component::input::InputState,
4+};
3 5
4-use super::ui::{6+use super::ui::{field_row, list_card, number, to_bytes, to_units};
5- field_row, kilobytes_bytes, kilobytes_text, list_card, megabytes_bytes, megabytes_text, number,7+use crate::gui::{
8+ KB, MB, Palette, Yumush, auth::field, notify_error, settings_page::segmented,
6 };9 };
7-use crate::gui::{Palette, Yumush, auth::field, notify_error, settings_page::segmented};10+
11+fn input_text(input: &Entity<InputState>, cx: &App) -> String {
12+ input.read(cx).text().to_string()
13+}
14+
15+fn input_number(input: &Entity<InputState>, cx: &App) -> u32 {
16+ number(&input_text(input, cx))
17+}
8 18
9 impl Yumush {19 impl Yumush {
10 pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {20 pub(super) fn fill_server_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -18,21 +28,21 @@ impl Yumush {
18 });28 });
19 self.chat.server_limit.update(cx, |input, cx| {29 self.chat.server_limit.update(cx, |input, cx| {
20 input.set_value(30 input.set_value(
21- megabytes_text(settings.max_attachment_bytes).as_str(),31+ to_units(settings.max_attachment_bytes, MB as u64).as_str(),
22 window,32 window,
23 cx,33 cx,
24 )34 )
25 });35 });
26 self.chat.server_user_quota.update(cx, |input, cx| {36 self.chat.server_user_quota.update(cx, |input, cx| {
27 input.set_value(37 input.set_value(
28- megabytes_text(settings.user_quota_bytes).as_str(),38+ to_units(settings.user_quota_bytes, MB as u64).as_str(),
29 window,39 window,
30 cx,40 cx,
31 )41 )
32 });42 });
33 self.chat.server_community_quota.update(cx, |input, cx| {43 self.chat.server_community_quota.update(cx, |input, cx| {
34 input.set_value(44 input.set_value(
35- megabytes_text(settings.community_quota_bytes).as_str(),45+ to_units(settings.community_quota_bytes, MB as u64).as_str(),
36 window,46 window,
37 cx,47 cx,
38 )48 )
@@ -68,7 +78,7 @@ impl Yumush {
68 });78 });
69 self.chat.server_max_avatar.update(cx, |input, cx| {79 self.chat.server_max_avatar.update(cx, |input, cx| {
70 input.set_value(80 input.set_value(
71- kilobytes_text(settings.max_avatar_bytes).as_str(),81+ to_units(settings.max_avatar_bytes, KB as u64).as_str(),
72 window,82 window,
73 cx,83 cx,
74 )84 )
@@ -88,73 +98,25 @@ impl Yumush {
88 }98 }
89 99
90 pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {100 pub(super) fn save_server_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
91- let name = self.chat.server_name.read(cx).text().to_string();101+ let chat = &self.chat;
92- let max_attachment_bytes =
93- megabytes_bytes(&self.chat.server_limit.read(cx).text().to_string());
94- let user_quota_bytes =
95- megabytes_bytes(&self.chat.server_user_quota.read(cx).text().to_string());
96- let community_quota_bytes =
97- megabytes_bytes(&self.chat.server_community_quota.read(cx).text().to_string());
98- let message_retention_days = number(
99- &self
100- .chat
101- .server_message_retention
102- .read(cx)
103- .text()
104- .to_string(),
105- );
106- let attachment_retention_days = number(
107- &self
108- .chat
109- .server_attachment_retention
110- .read(cx)
111- .text()
112- .to_string(),
113- );
114- let announcement = self.chat.server_announcement.read(cx).text().to_string();
115- let max_communities_per_user =
116- number(&self.chat.server_max_communities.read(cx).text().to_string());
117- let max_message_length = number(
118- &self
119- .chat
120- .server_max_message_length
121- .read(cx)
122- .text()
123- .to_string(),
124- );
125- let max_avatar_bytes =
126- kilobytes_bytes(&self.chat.server_max_avatar.read(cx).text().to_string());
127- let messages_per_minute = number(
128- &self
129- .chat
130- .server_messages_per_minute
131- .read(cx)
132- .text()
133- .to_string(),
134- );
135- let logins_per_minute = number(
136- &self
137- .chat
138- .server_logins_per_minute
139- .read(cx)
140- .text()
141- .to_string(),
142- );
143 let settings = ServerSettings {102 let settings = ServerSettings {
144- name,103+ name: input_text(&chat.server_name, cx),
145- registration_open: self.chat.server_registration_open,104+ registration_open: chat.server_registration_open,
146- max_attachment_bytes,105+ max_attachment_bytes: to_bytes(&input_text(&chat.server_limit, cx), MB as u64),
147- maintenance: self.chat.server_maintenance,106+ maintenance: chat.server_maintenance,
148- user_quota_bytes,107+ user_quota_bytes: to_bytes(&input_text(&chat.server_user_quota, cx), MB as u64),
149- community_quota_bytes,108+ community_quota_bytes: to_bytes(
150- message_retention_days,109+ &input_text(&chat.server_community_quota, cx),
151- attachment_retention_days,110+ MB as u64,
152- announcement,111+ ),
153- max_communities_per_user,112+ message_retention_days: input_number(&chat.server_message_retention, cx),
154- max_message_length,113+ attachment_retention_days: input_number(&chat.server_attachment_retention, cx),
155- max_avatar_bytes,114+ announcement: input_text(&chat.server_announcement, cx),
156- messages_per_minute,115+ max_communities_per_user: input_number(&chat.server_max_communities, cx),
157- logins_per_minute,116+ max_message_length: input_number(&chat.server_max_message_length, cx),
117+ max_avatar_bytes: to_bytes(&input_text(&chat.server_max_avatar, cx), KB as u64),
118+ messages_per_minute: input_number(&chat.server_messages_per_minute, cx),
119+ logins_per_minute: input_number(&chat.server_logins_per_minute, cx),
158 };120 };
159 let network = self.network.clone();121 let network = self.network.clone();
160 122
crates/client/src/gui/builder/storage.rsmodified+7 -17
@@ -4,11 +4,12 @@ use gpui_kit::{
4 assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative,4 assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px, relative,
5 };5 };
6 6
7-use super::ui::{accent_button, card, card_header, list_card, list_row, toolbar};7+use super::ui::{
8+ accent_button, card, card_header, delete_icon_button, list_card, list_row, toolbar,
9+};
8 use crate::gui::{10 use crate::gui::{
9- DATE, Palette, Tooltip, Yumush,11+ DATE, Palette, Yumush,
10 auth::field,12 auth::field,
11- clickable,
12 community_settings::{search_text, user_name},13 community_settings::{search_text, user_name},
13 entity_action, id_time, notify_error, storage, text,14 entity_action, id_time, notify_error, storage, text,
14 };15 };
@@ -83,25 +84,14 @@ fn attachment_row(
83 palette: Palette,84 palette: Palette,
84 ) -> Div {85 ) -> Div {
85 let attachment_id = info.attachment.id.clone();86 let attachment_id = info.attachment.id.clone();
86- let delete = clickable(87+ let delete = delete_icon_button(
87 format!("delete_attachment_{}", info.attachment.id),88 format!("delete_attachment_{}", info.attachment.id),
89+ pending,
88 palette,90 palette,
89 entity_action(entity, move |yumush, window, cx| {91 entity_action(entity, move |yumush, window, cx| {
90 yumush.delete_builder_attachment(&attachment_id, window, cx)92 yumush.delete_builder_attachment(&attachment_id, window, cx)
91 }),93 }),
92- )94+ );
93- .tip(if pending { "Confirm" } else { "Delete" })
94- .size(px(26.))
95- .flex()
96- .flex_shrink_0()
97- .items_center()
98- .justify_center()
99- .rounded(px(6.))
100- .text_color(palette.danger)
101- .when(pending, |this| {
102- this.bg(palette.danger).text_color(palette.on_accent)
103- })
104- .child(Icon::new(IconName::Trash).w(px(14.)).h(px(14.)));
105 95
106 list_row()96 list_row()
107 .child(97 .child(
crates/client/src/gui/builder/ui.rsmodified+56 -30
@@ -1,32 +1,20 @@
1-use crate::gui::{KB, MB, Palette, Tooltip as _, clickable, primary_button, text};1+use crate::gui::{Palette, Tooltip as _, clickable, primary_button, text};
2 use gpui_kit::{2 use gpui_kit::{
3 AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window,3 AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window,
4 assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px,4 assets::IconName, component::Icon, div, prelude::FluentBuilder as _, px,
5 };5 };
6 use jiff::{civil::Date, tz::TimeZone};6 use jiff::{civil::Date, tz::TimeZone};
7 7
8-pub(super) fn megabytes_bytes(text: &str) -> u64 {8+pub(super) fn to_bytes(text: &str, unit: u64) -> u64 {
9 text.trim()9 text.trim()
10 .parse::<u64>()10 .parse::<u64>()
11 .ok()11 .ok()
12- .and_then(|megabytes| megabytes.checked_mul(MB as u64))12+ .and_then(|units| units.checked_mul(unit))
13 .unwrap_or(0)13 .unwrap_or(0)
14 }14 }
15 15
16-pub(super) fn kilobytes_bytes(text: &str) -> u64 {16+pub(super) fn to_units(bytes: u64, unit: u64) -> String {
17- text.trim()17+ (bytes / unit).to_string()
18- .parse::<u64>()
19- .ok()
20- .and_then(|kilobytes| kilobytes.checked_mul(KB as u64))
21- .unwrap_or(0)
22-}
23-
24-pub(super) fn megabytes_text(bytes: u64) -> String {
25- (bytes / MB as u64).to_string()
26-}
27-
28-pub(super) fn kilobytes_text(bytes: u64) -> String {
29- (bytes / KB as u64).to_string()
30 }18 }
31 19
32 pub(super) fn number(text: &str) -> u32 {20 pub(super) fn number(text: &str) -> u32 {
@@ -53,6 +41,25 @@ pub(super) fn icon_button(
53 .child(Icon::new(icon).w(px(14.)).h(px(14.)))41 .child(Icon::new(icon).w(px(14.)).h(px(14.)))
54 }42 }
55 43
44+pub(super) fn delete_icon_button(
45+ id: String,
46+ pending: bool,
47+ palette: Palette,
48+ action: impl Fn(&mut Window, &mut App) + 'static,
49+) -> Stateful<Div> {
50+ icon_button(
51+ id,
52+ IconName::Trash,
53+ if pending { "Confirm" } else { "Delete" },
54+ palette.danger,
55+ palette,
56+ action,
57+ )
58+ .when(pending, |this| {
59+ this.bg(palette.danger).text_color(palette.on_accent)
60+ })
61+}
62+
56 pub(super) fn action_button(63 pub(super) fn action_button(
57 id: String,64 id: String,
58 icon: IconName,65 icon: IconName,
@@ -145,7 +152,6 @@ pub(super) fn action_group(
145 pub(super) fn danger_button(152 pub(super) fn danger_button(
146 id: String,153 id: String,
147 label: &'static str,154 label: &'static str,
148- pending: bool,
149 palette: Palette,155 palette: Palette,
150 action: impl Fn(&mut Window, &mut App) + 'static,156 action: impl Fn(&mut Window, &mut App) + 'static,
151 ) -> impl IntoElement {157 ) -> impl IntoElement {
@@ -160,26 +166,46 @@ pub(super) fn danger_button(
160 .border_1()166 .border_1()
161 .border_color(palette.danger.opacity(0.5))167 .border_color(palette.danger.opacity(0.5))
162 .text_color(palette.danger)168 .text_color(palette.danger)
163- .when(pending, |this| {169+ .child(label)
164- this.bg(palette.danger).text_color(palette.on_accent)
165- })
166- .child(if pending { "Confirm" } else { label })
167 }170 }
168 171
169-pub(super) fn day_millis(text: &str, end_of_day: bool) -> Option<u64> {172+fn epoch_ms(date: Date) -> Option<u64> {
170- let date: Date = text.parse().ok()?;
171- let date = if end_of_day {
172- date.tomorrow().ok()?
173- } else {
174- date
175- };
176 let millis = date173 let millis = date
177 .to_zoned_datetime(TimeZone::system())174 .to_zoned_datetime(TimeZone::system())
178 .ok()?175 .ok()?
179 .timestamp()176 .timestamp()
180 .as_millisecond();177 .as_millisecond();
178+ u64::try_from(millis).ok()
179+}
180+
181+pub(super) fn start_of_day_ms(text: &str) -> Option<u64> {
182+ let date: Date = text.parse().ok()?;
183+ epoch_ms(date)
184+}
185+
186+pub(super) fn end_of_day_ms(text: &str) -> Option<u64> {
187+ let date: Date = text.parse().ok()?;
188+ epoch_ms(date.tomorrow().ok()?)?.checked_sub(1)
189+}
181 190
182- u64::try_from(millis - i64::from(end_of_day)).ok()191+pub(super) fn rows_body(rows: Vec<Div>, empty: &str, palette: Palette) -> Div {
192+ if rows.is_empty() {
193+ return div()
194+ .py(px(24.))
195+ .flex()
196+ .justify_center()
197+ .text_size(text(12.))
198+ .text_color(palette.muted)
199+ .child(empty.to_string());
200+ }
201+ div()
202+ .flex()
203+ .flex_col()
204+ .children(rows.into_iter().enumerate().map(|(index, row)| {
205+ row.when(index > 0, |row| {
206+ row.border_t_1().border_color(palette.border)
207+ })
208+ }))
183 }209 }
184 210
185 pub(super) fn accent_button(211 pub(super) fn accent_button(
crates/client/src/gui/builder/users.rsmodified+8 -5
@@ -2,7 +2,7 @@ use std::future::Future;
2 2
3 use common::{3 use common::{
4 error::Error,4 error::Error,
5- model::{Account, Role, SessionInfo, User},5+ model::{Account, BanScope, Role, SessionInfo, User},
6 permission,6 permission,
7 time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms},7 time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms},
8 };8 };
@@ -338,7 +338,10 @@ impl Yumush {
338 }338 }
339 339
340 pub(super) fn toggle_builder_ban_ip(&mut self, cx: &mut Context<Self>) {340 pub(super) fn toggle_builder_ban_ip(&mut self, cx: &mut Context<Self>) {
341- self.chat.builder_ban_ip = !self.chat.builder_ban_ip;341+ self.chat.builder_ban_scope = match self.chat.builder_ban_scope {
342+ BanScope::Account => BanScope::AccountAndIp,
343+ BanScope::AccountAndIp => BanScope::Account,
344+ };
342 cx.notify();345 cx.notify();
343 }346 }
344 347
@@ -349,12 +352,12 @@ impl Yumush {
349 let reason = self.chat.builder_ban_reason.read(cx).text().to_string();352 let reason = self.chat.builder_ban_reason.read(cx).text().to_string();
350 let reason = reason.trim().to_string();353 let reason = reason.trim().to_string();
351 let reason = (!reason.is_empty()).then_some(reason);354 let reason = (!reason.is_empty()).then_some(reason);
352- let ip = self.chat.builder_ban_ip;355+ let scope = self.chat.builder_ban_scope;
353 self.chat356 self.chat
354 .builder_ban_reason357 .builder_ban_reason
355 .update(cx, |input, cx| input.set_value("", window, cx));358 .update(cx, |input, cx| input.set_value("", window, cx));
356 self.builder_user_action(window, cx, move |network| async move {359 self.builder_user_action(window, cx, move |network| async move {
357- network.ban_user(&user_id, reason.as_deref(), ip).await360+ network.ban_user(&user_id, reason.as_deref(), scope).await
358 });361 });
359 }362 }
360 363
@@ -506,7 +509,7 @@ impl Yumush {
506 entity: &Entity<Self>,509 entity: &Entity<Self>,
507 palette: Palette,510 palette: Palette,
508 ) -> Div {511 ) -> Div {
509- let ip_label = if self.chat.builder_ban_ip {512+ let ip_label = if self.chat.builder_ban_scope == BanScope::AccountAndIp {
510 "IP: on"513 "IP: on"
511 } else {514 } else {
512 "IP: off"515 "IP: off"
crates/client/src/gui/builder/voice.rsmodified+9 -40
@@ -6,57 +6,26 @@ use common::{
6 };6 };
7 use gpui_kit::{7 use gpui_kit::{
8 AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,8 AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName,
9- div, prelude::FluentBuilder as _, px,9+ div, px,
10 };10 };
11 11
12-use super::ui::{card, card_header, icon_button, list_card, pill};12+use super::ui::{card, card_header, icon_button, list_card, pill, rows_body};
13 use crate::{13 use crate::{
14 gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text},14 gui::{Palette, Yumush, avatar, entity_action, notify_error, profile::user_link, text},
15 network::NetworkHandle,15 network::NetworkHandle,
16 };16 };
17 17
18-fn rows_body(rows: Vec<Div>, empty: &str, palette: Palette) -> Div {
19- if rows.is_empty() {
20- return div()
21- .py(px(24.))
22- .flex()
23- .justify_center()
24- .text_size(text(12.))
25- .text_color(palette.muted)
26- .child(empty.to_string());
27- }
28- div()
29- .flex()
30- .flex_col()
31- .children(rows.into_iter().enumerate().map(|(index, row)| {
32- row.when(index > 0, |row| {
33- row.border_t_1().border_color(palette.border)
34- })
35- }))
36-}
37-
38 impl Yumush {18 impl Yumush {
39 pub(super) fn load_voice_rooms(&self, window: &mut Window, cx: &mut Context<Self>) {19 pub(super) fn load_voice_rooms(&self, window: &mut Window, cx: &mut Context<Self>) {
40- if !self.is_builder() {20+ self.fetch_builder(
41- return;21+ window,
42- }22+ cx,
43- let network = self.network.clone();23+ |network| async move { network.voice_rooms().await },
44-24+ |yumush, rooms, cx| {
45- cx.spawn_in(window, async move |this, cx| {
46- let rooms = match network.voice_rooms().await {
47- Ok(rooms) => rooms,
48- Err(error) => {
49- notify_error(&this, cx, error);
50- return;
51- }
52- };
53-
54- let _ = this.update(cx, |yumush, cx| {
55 yumush.chat.builder_voice_rooms = rooms;25 yumush.chat.builder_voice_rooms = rooms;
56 cx.notify();26 cx.notify();
57- });27+ },
58- })28+ );
59- .detach();
60 }29 }
61 30
62 pub(super) fn voice_action<Fut>(31 pub(super) fn voice_action<Fut>(
crates/client/src/gui/chat.rsmodified+116 -173
@@ -28,7 +28,7 @@ use common::{
28 constant::MESSAGE_PAGE_LIMIT,28 constant::MESSAGE_PAGE_LIMIT,
29 event::Event,29 event::Event,
30 model::{30 model::{
31- ACTION_NAMES, Account, AdminLogEntry, AttachmentInfo, Ban, CallLog, Community,31+ Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community,
32 CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode,32 CommunityKind, CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode,
33 LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus,33 LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus,
34 ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions,34 ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions,
@@ -183,7 +183,7 @@ pub struct Chat {
183 pub(super) builder_timeout: Entity<InputState>,183 pub(super) builder_timeout: Entity<InputState>,
184 pub(super) pending_builder_ban: Option<String>,184 pub(super) pending_builder_ban: Option<String>,
185 pub(super) builder_ban_reason: Entity<InputState>,185 pub(super) builder_ban_reason: Entity<InputState>,
186- pub(super) builder_ban_ip: bool,186+ pub(super) builder_ban_scope: BanScope,
187 pub(super) builder_bans: Vec<ServerBan>,187 pub(super) builder_bans: Vec<ServerBan>,
188 pub(super) builder_invites: Vec<InviteCode>,188 pub(super) builder_invites: Vec<InviteCode>,
189 pub(super) invite_uses: Entity<InputState>,189 pub(super) invite_uses: Entity<InputState>,
@@ -259,11 +259,6 @@ impl Chat {
259 )259 )
260 .detach();260 .detach();
261 261
262- let username_input = editable_input("Username...", Yumush::save_username, window, cx);
263- let status_input = editable_input("Status...", Yumush::save_status, window, cx);
264- let community_name_input =
265- editable_input("Community name...", Yumush::save_community_name, window, cx);
266-
267 let search_input = new_input("Find user", window, cx);262 let search_input = new_input("Find user", window, cx);
268 cx.subscribe_in(263 cx.subscribe_in(
269 &search_input,264 &search_input,
@@ -289,49 +284,7 @@ impl Chat {
289 let builder_search = new_input("Search...", window, cx);284 let builder_search = new_input("Search...", window, cx);
290 let builder_password = new_input("New password...", window, cx);285 let builder_password = new_input("New password...", window, cx);
291 builder_password.update(cx, |input, cx| input.set_masked(true, window, cx));286 builder_password.update(cx, |input, cx| input.set_masked(true, window, cx));
292- let builder_rename = new_input("New username...", window, cx);
293- let server_name = new_input("Server name...", window, cx);
294- let server_limit = new_input("", window, cx);
295- let server_user_quota = new_input("", window, cx);
296- let server_community_quota = new_input("", window, cx);
297- let server_message_retention = new_input("", window, cx);
298- let server_attachment_retention = new_input("", window, cx);
299- let server_announcement = new_input("Announcement...", window, cx);
300- let server_max_communities = new_input("", window, cx);
301- let server_max_message_length = new_input("Max message length...", window, cx);
302- let server_max_avatar = new_input("", window, cx);
303- let server_messages_per_minute = new_input("", window, cx);
304- let server_logins_per_minute = new_input("", window, cx);
305- let builder_timeout = new_input("Minutes...", window, cx);
306- let builder_ban_reason = new_input("Reason...", window, cx);
307- let invite_uses = new_input("Uses...", window, cx);
308- let invite_hours = new_input("Hours", window, cx);
309- let new_username = new_input("Username...", window, cx);
310 let new_password = new_input("Password...", window, cx);287 let new_password = new_input("Password...", window, cx);
311- let report_reason = new_input("Reason...", window, cx);
312- let builder_message_text = new_input("Text...", window, cx);
313- let builder_message_user = new_input("User...", window, cx);
314- let builder_message_community = new_input("Community...", window, cx);
315- let builder_message_from = new_input("From YYYY-MM-DD", window, cx);
316- let builder_message_to = new_input("To YYYY-MM-DD", window, cx);
317- let builder_attachment_user = new_input("User...", window, cx);
318- let builder_attachment_community = new_input("Community...", window, cx);
319- let builder_log_actor = new_input("Actor...", window, cx);
320- let builder_log_target = new_input("Target...", window, cx);
321- let builder_log_from = new_input("From YYYY-MM-DD", window, cx);
322- let builder_log_to = new_input("To YYYY-MM-DD", window, cx);
323- let builder_log_action = cx.new(|cx| {
324- SelectState::new(
325- SearchableVec::new(
326- std::iter::once("All")
327- .chain(ACTION_NAMES)
328- .collect::<Vec<_>>(),
329- ),
330- Some(IndexPath::new(0)),
331- window,
332- cx,
333- )
334- });
335 new_password.update(cx, |input, cx| input.set_masked(true, window, cx));288 new_password.update(cx, |input, cx| input.set_masked(true, window, cx));
336 for search in [&ban_search, &log_search, &builder_search] {289 for search in [&ban_search, &log_search, &builder_search] {
337 cx.subscribe_in(search, window, |_, _, event, window, cx| {290 cx.subscribe_in(search, window, |_, _, event, window, cx| {
@@ -383,9 +336,14 @@ impl Chat {
383 tab: SidebarTab::Communities,336 tab: SidebarTab::Communities,
384 sidebar_collapsed: false,337 sidebar_collapsed: false,
385 view: View::Chat,338 view: View::Chat,
386- username_input,339+ username_input: editable_input("Username...", Yumush::save_username, window, cx),
387- community_name_input,340+ community_name_input: editable_input(
388- status_input,341+ "Community name...",
342+ Yumush::save_community_name,
343+ window,
344+ cx,
345+ ),
346+ status_input: editable_input("Status...", Yumush::save_status, window, cx),
389 avatars: HashMap::new(),347 avatars: HashMap::new(),
390 hues: HashMap::new(),348 hues: HashMap::new(),
391 avatar_requests: HashSet::new(),349 avatar_requests: HashSet::new(),
@@ -402,22 +360,33 @@ impl Chat {
402 builder_overview: None,360 builder_overview: None,
403 builder_logs: vec![],361 builder_logs: vec![],
404 builder_stats: vec![],362 builder_stats: vec![],
405- builder_log_actor,363+ builder_log_actor: new_input("Actor...", window, cx),
406- builder_log_target,364+ builder_log_target: new_input("Target...", window, cx),
407- builder_log_action,365+ builder_log_action: cx.new(|cx| {
408- builder_log_from,366+ SelectState::new(
409- builder_log_to,367+ SearchableVec::new(
368+ std::iter::once("All")
369+ .chain(AdminActionKind::ALL.into_iter().map(AdminActionKind::as_str))
370+ .collect::<Vec<_>>(),
371+ ),
372+ Some(IndexPath::new(0)),
373+ window,
374+ cx,
375+ )
376+ }),
377+ builder_log_from: new_input("From YYYY-MM-DD", window, cx),
378+ builder_log_to: new_input("To YYYY-MM-DD", window, cx),
410 builder_search,379 builder_search,
411 builder_communities: vec![],380 builder_communities: vec![],
412 pending_community_delete: None,381 pending_community_delete: None,
413- builder_message_text,382+ builder_message_text: new_input("Text...", window, cx),
414- builder_message_user,383+ builder_message_user: new_input("User...", window, cx),
415- builder_message_community,384+ builder_message_community: new_input("Community...", window, cx),
416- builder_message_from,385+ builder_message_from: new_input("From YYYY-MM-DD", window, cx),
417- builder_message_to,386+ builder_message_to: new_input("To YYYY-MM-DD", window, cx),
418 builder_messages: vec![],387 builder_messages: vec![],
419- builder_attachment_user,388+ builder_attachment_user: new_input("User...", window, cx),
420- builder_attachment_community,389+ builder_attachment_community: new_input("Community...", window, cx),
421 builder_usage_users: vec![],390 builder_usage_users: vec![],
422 builder_usage_communities: vec![],391 builder_usage_communities: vec![],
423 builder_attachments: vec![],392 builder_attachments: vec![],
@@ -426,41 +395,41 @@ impl Chat {
426 pending_builder_purge: None,395 pending_builder_purge: None,
427 transfer: None,396 transfer: None,
428 builder_password,397 builder_password,
429- server_name,398+ server_name: new_input("Server name...", window, cx),
430- server_limit,399+ server_limit: new_input("", window, cx),
431- server_user_quota,400+ server_user_quota: new_input("", window, cx),
432- server_community_quota,401+ server_community_quota: new_input("", window, cx),
433- server_message_retention,402+ server_message_retention: new_input("", window, cx),
434- server_attachment_retention,403+ server_attachment_retention: new_input("", window, cx),
435- server_announcement,404+ server_announcement: new_input("Announcement...", window, cx),
436- server_max_communities,405+ server_max_communities: new_input("", window, cx),
437- server_max_message_length,406+ server_max_message_length: new_input("Max message length...", window, cx),
438- server_max_avatar,407+ server_max_avatar: new_input("", window, cx),
439- server_messages_per_minute,408+ server_messages_per_minute: new_input("", window, cx),
440- server_logins_per_minute,409+ server_logins_per_minute: new_input("", window, cx),
441 server_registration_open: true,410 server_registration_open: true,
442 server_maintenance: false,411 server_maintenance: false,
443 pending_builder_timeout: None,412 pending_builder_timeout: None,
444- builder_timeout,413+ builder_timeout: new_input("Minutes...", window, cx),
445 pending_builder_ban: None,414 pending_builder_ban: None,
446- builder_ban_reason,415+ builder_ban_reason: new_input("Reason...", window, cx),
447- builder_ban_ip: false,416+ builder_ban_scope: BanScope::Account,
448 builder_bans: vec![],417 builder_bans: vec![],
449 builder_invites: vec![],418 builder_invites: vec![],
450- invite_uses,419+ invite_uses: new_input("Uses...", window, cx),
451- invite_hours,420+ invite_hours: new_input("Hours", window, cx),
452 pending_invite_delete: None,421 pending_invite_delete: None,
453- new_username,422+ new_username: new_input("Username...", window, cx),
454 new_password,423 new_password,
455 pending_builder_password: None,424 pending_builder_password: None,
456 builder_sessions: None,425 builder_sessions: None,
457 pending_builder_rename: None,426 pending_builder_rename: None,
458- builder_rename,427+ builder_rename: new_input("New username...", window, cx),
459 builder_reports: vec![],428 builder_reports: vec![],
460 report_filter: Some(ReportStatus::Open),429 report_filter: Some(ReportStatus::Open),
461 open_reports: 0,430 open_reports: 0,
462 report: None,431 report: None,
463- report_reason,432+ report_reason: new_input("Reason...", window, cx),
464 voice: HashMap::new(),433 voice: HashMap::new(),
465 drafts: HashMap::new(),434 drafts: HashMap::new(),
466 voice_state: VoiceState::Off,435 voice_state: VoiceState::Off,
@@ -478,13 +447,10 @@ impl Chat {
478 }447 }
479 }448 }
480 449
481- pub(super) fn unread_total(&self, group: bool) -> Unread {450+ fn unread_where(&self, keep: impl Fn(&CommunityKind) -> bool) -> Unread {
482 self.communities451 self.communities
483 .iter()452 .iter()
484- .filter(|community| {453+ .filter(|community| !self.muted.contains(&community.id) && keep(&community.kind))
485- !self.muted.contains(&community.id)
486- && matches!(community.kind, CommunityKind::Group) == group
487- })
488 .filter_map(|community| self.unread.get(&community.id))454 .filter_map(|community| self.unread.get(&community.id))
489 .fold(Unread::default(), |total, unread| Unread {455 .fold(Unread::default(), |total, unread| Unread {
490 messages: total.messages + unread.messages,456 messages: total.messages + unread.messages,
@@ -493,6 +459,14 @@ impl Chat {
493 })459 })
494 }460 }
495 461
462+ pub(super) fn unread_groups(&self) -> Unread {
463+ self.unread_where(|kind| matches!(kind, CommunityKind::Group))
464+ }
465+
466+ pub(super) fn unread_direct(&self) -> Unread {
467+ self.unread_where(|kind| !matches!(kind, CommunityKind::Group))
468+ }
469+
496 pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {470 pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {
497 let input = match self.selected_community_id {471 let input = match self.selected_community_id {
498 Some(_) => &self.message_input,472 Some(_) => &self.message_input,
@@ -880,10 +854,6 @@ impl Chat {
880 permission::effective_rank(user.role, rank)854 permission::effective_rank(user.role, rank)
881 }855 }
882 856
883- pub fn my_rank(&self, me: &User) -> Option<Rank> {
884- self.rank_of(me)
885- }
886-
887 pub fn rank_of_id(&self, user_id: &str) -> Option<Rank> {857 pub fn rank_of_id(&self, user_id: &str) -> Option<Rank> {
888 self.member(user_id).and_then(|user| self.rank_of(user))858 self.member(user_id).and_then(|user| self.rank_of(user))
889 }859 }
@@ -891,8 +861,8 @@ impl Chat {
891 pub fn can_pin(&self, me: &User) -> bool {861 pub fn can_pin(&self, me: &User) -> bool {
892 let direct = self862 let direct = self
893 .selected_community()863 .selected_community()
894- .is_some_and(|community| matches!(community.kind, CommunityKind::Direct { .. }));864+ .is_some_and(|community| community.kind.is_direct());
895- permission::can_pin(self.my_rank(me), direct)865+ permission::can_pin(self.rank_of(me), direct)
896 }866 }
897 867
898 fn update_pin(&mut self, message: &Message) {868 fn update_pin(&mut self, message: &Message) {
@@ -905,7 +875,7 @@ impl Chat {
905 875
906 pub fn can_delete(&self, message: &Message, me: &User) -> bool {876 pub fn can_delete(&self, message: &Message, me: &User) -> bool {
907 permission::can_delete_message(877 permission::can_delete_message(
908- self.my_rank(me),878+ self.rank_of(me),
909 self.rank_of_id(&message.user_id),879 self.rank_of_id(&message.user_id),
910 message.user_id == me.id,880 message.user_id == me.id,
911 )881 )
@@ -1016,7 +986,7 @@ impl Chat {
1016 self.pending_builder_rename = None;986 self.pending_builder_rename = None;
1017 self.pending_builder_timeout = None;987 self.pending_builder_timeout = None;
1018 self.pending_builder_ban = None;988 self.pending_builder_ban = None;
1019- self.builder_ban_ip = false;989+ self.builder_ban_scope = BanScope::Account;
1020 self.builder_bans.clear();990 self.builder_bans.clear();
1021 self.builder_invites.clear();991 self.builder_invites.clear();
1022 self.pending_invite_delete = None;992 self.pending_invite_delete = None;
@@ -1228,15 +1198,7 @@ impl Yumush {
1228 let text = self.announcement()?;1198 let text = self.announcement()?;
1229 1199
1230 Some(1200 Some(
1231- div()1201+ accent_bar(palette)
1232- .flex()
1233- .items_center()
1234- .justify_between()
1235- .gap(px(8.))
1236- .px(px(12.))
1237- .py(px(6.))
1238- .bg(palette.accent)
1239- .text_color(palette.on_accent)
1240 .child(text.to_string())1202 .child(text.to_string())
1241 .child(1203 .child(
1242 clickable(1204 clickable(
@@ -1311,15 +1273,7 @@ impl Yumush {
1311 return None;1273 return None;
1312 }1274 }
1313 Some(1275 Some(
1314- div()1276+ accent_bar(palette)
1315- .flex()
1316- .items_center()
1317- .justify_between()
1318- .gap(px(8.))
1319- .px(px(12.))
1320- .py(px(6.))
1321- .bg(palette.accent)
1322- .text_color(palette.on_accent)
1323 .child(format!("{count} new messages"))1277 .child(format!("{count} new messages"))
1324 .child(1278 .child(
1325 div()1279 div()
@@ -1381,7 +1335,7 @@ impl Yumush {
1381 .absolute()1335 .absolute()
1382 .top(px(-6.))1336 .top(px(-6.))
1383 .right(px(-6.))1337 .right(px(-6.))
1384- .children(super::sidebar::badge(1338+ .children(super::sidebar::unread_badge(
1385 palette,1339 palette,
1386 false,1340 false,
1387 Some(&Unread {1341 Some(&Unread {
@@ -1548,7 +1502,7 @@ impl Yumush {
1548 self.load_members(window, cx);1502 self.load_members(window, cx);
1549 self.load_pins(window, cx);1503 self.load_pins(window, cx);
1550 self.load_voice(window, cx);1504 self.load_voice(window, cx);
1551- self.load_latest_messages(window, cx);1505+ self.load_messages(None, window, cx);
1552 cx.notify();1506 cx.notify();
1553 }1507 }
1554 1508
@@ -1570,7 +1524,7 @@ impl Yumush {
1570 1524
1571 if self.chat.selected_community_id.is_some() {1525 if self.chat.selected_community_id.is_some() {
1572 self.load_members(window, cx);1526 self.load_members(window, cx);
1573- self.load_latest_messages(window, cx);1527+ self.load_messages(None, window, cx);
1574 }1528 }
1575 }1529 }
1576 1530
@@ -1757,6 +1711,11 @@ impl Yumush {
1757 ) {1711 ) {
1758 self.chat.jump = Some(message_id);1712 self.chat.jump = Some(message_id);
1759 self.chat.reveal_jump();1713 self.chat.reveal_jump();
1714+ self.continue_jump(window, cx);
1715+ cx.notify();
1716+ }
1717+
1718+ fn continue_jump(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1760 if self.chat.jump.is_none() {1719 if self.chat.jump.is_none() {
1761 Self::fade_highlight(cx);1720 Self::fade_highlight(cx);
1762 } else if self.chat.history == History::More {1721 } else if self.chat.history == History::More {
@@ -1764,7 +1723,6 @@ impl Yumush {
1764 } else {1723 } else {
1765 self.chat.jump = None;1724 self.chat.jump = None;
1766 }1725 }
1767- cx.notify();
1768 }1726 }
1769 1727
1770 fn fade_highlight(cx: &mut Context<Self>) {1728 fn fade_highlight(cx: &mut Context<Self>) {
@@ -1775,10 +1733,6 @@ impl Yumush {
1775 .detach();1733 .detach();
1776 }1734 }
1777 1735
1778- fn load_latest_messages(&self, window: &mut Window, cx: &mut Context<Self>) {
1779- self.load_messages(None, window, cx);
1780- }
1781-
1782 fn load_older_messages(&self, window: &mut Window, cx: &mut Context<Self>) {1736 fn load_older_messages(&self, window: &mut Window, cx: &mut Context<Self>) {
1783 let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else {1737 let Some(oldest_id) = self.chat.messages.first().map(|message| message.id.clone()) else {
1784 return;1738 return;
@@ -1813,13 +1767,7 @@ impl Yumush {
1813 .chat1767 .chat
1814 .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str()));1768 .add_page(page, yumush.user.as_ref().map(|user| user.id.as_str()));
1815 if seeking {1769 if seeking {
1816- if yumush.chat.jump.is_none() {1770+ yumush.continue_jump(window, cx);
1817- Self::fade_highlight(cx);
1818- } else if yumush.chat.history == History::More {
1819- yumush.load_older_messages(window, cx);
1820- } else {
1821- yumush.chat.jump = None;
1822- }
1823 }1771 }
1824 if let Some(message_id) = newest.filter(|_| latest) {1772 if let Some(message_id) = newest.filter(|_| latest) {
1825 yumush.mark_read(&community_id, &message_id, cx);1773 yumush.mark_read(&community_id, &message_id, cx);
@@ -1959,7 +1907,9 @@ impl Yumush {
1959 Ok(participants) => {1907 Ok(participants) => {
1960 network.set_deafened(deafened);1908 network.set_deafened(deafened);
1961 let _ = this.update_in(cx, |yumush, _, cx| {1909 let _ = this.update_in(cx, |yumush, _, cx| {
1962- let muted = muted || yumush.mic_locked() || yumush.hidden_in(&community_id);1910+ let muted = muted
1911+ || yumush.is_server_muted()
1912+ || yumush.hidden_in(&community_id);
1963 yumush.network.set_muted(muted);1913 yumush.network.set_muted(muted);
1964 yumush.chat.voice.insert(community_id.clone(), participants);1914 yumush.chat.voice.insert(community_id.clone(), participants);
1965 yumush.chat.voice_state = VoiceState::In {1915 yumush.chat.voice_state = VoiceState::In {
@@ -2030,10 +1980,6 @@ impl Yumush {
2030 .is_some_and(|me| self.chat.server_muted.contains(&me.id))1980 .is_some_and(|me| self.chat.server_muted.contains(&me.id))
2031 }1981 }
2032 1982
2033- pub(super) fn mic_locked(&self) -> bool {
2034- self.is_server_muted()
2035- }
2036-
2037 fn hidden_in(&self, community_id: &str) -> bool {1983 fn hidden_in(&self, community_id: &str) -> bool {
2038 self.chat.ghost || !self.chat.joined(community_id)1984 self.chat.ghost || !self.chat.joined(community_id)
2039 }1985 }
@@ -2044,16 +1990,8 @@ impl Yumush {
2044 .is_some_and(|community_id| self.hidden_in(community_id))1990 .is_some_and(|community_id| self.hidden_in(community_id))
2045 }1991 }
2046 1992
2047- pub(super) fn force_mute(&mut self, cx: &mut Context<Self>) {
2048- if let VoiceState::In { muted, .. } = &mut self.chat.voice_state {
2049- *muted = true;
2050- self.network.set_muted(true);
2051- }
2052- cx.notify();
2053- }
2054-
2055 fn toggle_mute(&mut self, window: &mut Window, cx: &mut Context<Self>) {1993 fn toggle_mute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2056- if self.mic_locked() {1994+ if self.is_server_muted() {
2057 return;1995 return;
2058 }1996 }
2059 let Some((muted, _)) = self.chat.voice_flags() else {1997 let Some((muted, _)) = self.chat.voice_flags() else {
@@ -2066,7 +2004,7 @@ impl Yumush {
2066 self.set_muted(!muted, cx);2004 self.set_muted(!muted, cx);
2067 }2005 }
2068 2006
2069- fn set_muted(&mut self, value: bool, cx: &mut Context<Self>) {2007+ pub(super) fn set_muted(&mut self, value: bool, cx: &mut Context<Self>) {
2070 if let VoiceState::In { muted, .. } = &mut self.chat.voice_state {2008 if let VoiceState::In { muted, .. } = &mut self.chat.voice_state {
2071 *muted = value;2009 *muted = value;
2072 self.network.set_muted(value);2010 self.network.set_muted(value);
@@ -2269,15 +2207,7 @@ impl Yumush {
2269 let accept_id = community_id.clone();2207 let accept_id = community_id.clone();
2270 2208
2271 Some(2209 Some(
2272- div()2210+ accent_bar(palette)
2273- .flex()
2274- .items_center()
2275- .justify_between()
2276- .gap(px(8.))
2277- .px(px(12.))
2278- .py(px(6.))
2279- .bg(palette.accent)
2280- .text_color(palette.on_accent)
2281 .child(2211 .child(
2282 div()2212 div()
2283 .flex()2213 .flex()
@@ -2505,25 +2435,31 @@ impl Yumush {
2505 }2435 }
2506 }2436 }
2507 2437
2438+struct MemberRow {
2439+ user: User,
2440+ rank: Option<Rank>,
2441+ in_voice: bool,
2442+ muted: bool,
2443+ presence: Presence,
2444+}
2445+
2508 fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> impl IntoElement {2446 fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> impl IntoElement {
2509 let chat = &yumush.chat;2447 let chat = &yumush.chat;
2510 let entity = entity.clone();2448 let entity = entity.clone();
2511- let voice: Vec<String> = chat2449+ let voice = chat
2512 .selected_community_id2450 .selected_community_id
2513 .as_deref()2451 .as_deref()
2514- .map(|community_id| chat.voice_ids(community_id).to_vec())2452+ .map(|community_id| chat.voice_ids(community_id))
2515 .unwrap_or_default();2453 .unwrap_or_default();
2516- let members: Vec<(User, Option<Rank>, bool, bool, Presence)> = chat2454+ let members: Vec<MemberRow> = chat
2517 .members2455 .members
2518 .iter()2456 .iter()
2519- .map(|member| {2457+ .map(|member| MemberRow {
2520- (2458+ user: member.user.clone(),
2521- member.user.clone(),2459+ rank: chat.rank_of(&member.user),
2522- chat.rank_of(&member.user),2460+ in_voice: voice.contains(&member.user.id),
2523- voice.contains(&member.user.id),2461+ muted: chat.server_muted.contains(&member.user.id),
2524- chat.server_muted.contains(&member.user.id),2462+ presence: yumush.presence_of(&member.user.id),
2525- yumush.presence_of(&member.user.id),
2526- )
2527 })2463 })
2528 .collect();2464 .collect();
2529 let avatars = chat.avatars.clone();2465 let avatars = chat.avatars.clone();
@@ -2533,10 +2469,7 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -
2533 .appearance(false)2469 .appearance(false)
2534 .trigger(MembersTrigger {2470 .trigger(MembersTrigger {
2535 palette,2471 palette,
2536- members: members2472+ members: members.iter().map(|row| row.user.clone()).collect(),
2537- .iter()
2538- .map(|(user, _, _, _, _)| user.clone())
2539- .collect(),
2540 avatars: avatars.clone(),2473 avatars: avatars.clone(),
2541 })2474 })
2542 .content(move |_, _, _| {2475 .content(move |_, _, _| {
@@ -2556,7 +2489,7 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -
2556 .children(2489 .children(
2557 members2490 members
2558 .iter()2491 .iter()
2559- .map(|(user, rank, in_voice, muted, presence)| {2492+ .map(|MemberRow { user, rank, in_voice, muted, presence }| {
2560 profile_popover(2493 profile_popover(
2561 format!("member_{}", user.id),2494 format!("member_{}", user.id),
2562 Anchor::TopRight,2495 Anchor::TopRight,
@@ -2623,6 +2556,18 @@ fn members_popover(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -
2623 })2556 })
2624 }2557 }
2625 2558
2559+fn accent_bar(palette: Palette) -> Div {
2560+ div()
2561+ .flex()
2562+ .items_center()
2563+ .justify_between()
2564+ .gap(px(8.))
2565+ .px(px(12.))
2566+ .py(px(6.))
2567+ .bg(palette.accent)
2568+ .text_color(palette.on_accent)
2569+}
2570+
2626 fn new_divider(palette: Palette) -> impl IntoElement {2571 fn new_divider(palette: Palette) -> impl IntoElement {
2627 div()2572 div()
2628 .flex()2573 .flex()
@@ -2716,9 +2661,7 @@ fn render_message(
2716 return render_call(message, call, chat, me, palette);2661 return render_call(message, call, chat, me, palette);
2717 }2662 }
2718 let author = chat.author(&message.user_id);2663 let author = chat.author(&message.user_id);
2719- let username = author2664+ let username = author.map_or("unknown", |user| user.username.as_str());
2720- .map(|user| user.username.as_str())
2721- .unwrap_or("unknown");
2722 let name = div()2665 let name = div()
2723 .flex()2666 .flex()
2724 .items_center()2667 .items_center()
crates/client/src/gui/community_settings.rsmodified+11 -35
@@ -10,8 +10,7 @@ use common::{
10 };10 };
11 use gpui_kit::{11 use gpui_kit::{
12 AnyElement, App, AsyncWindowContext, Context, Div, Entity, Image, InteractiveElement,12 AnyElement, App, AsyncWindowContext, Context, Div, Entity, Image, InteractiveElement,
13- IntoElement, ParentElement, PathPromptOptions, StatefulInteractiveElement, Styled, WeakEntity,13+ IntoElement, ParentElement, StatefulInteractiveElement, Styled, WeakEntity, Window,
14- Window,
15 component::{14 component::{
16 WindowExt,15 WindowExt,
17 input::{Input, InputState},16 input::{Input, InputState},
@@ -28,8 +27,8 @@ use super::{
28 clickable, community_icon, entity_action, id_time, notify_error,27 clickable, community_icon, entity_action, id_time, notify_error,
29 profile::user_link,28 profile::user_link,
30 settings_page::{29 settings_page::{
31- Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file,30+ Editable, Picture, danger_section, delete_control, page, picked_avatar, picture_card, row,
32- row, section, text_row,31+ section, text_row,
33 },32 },
34 };33 };
35 34
@@ -78,21 +77,15 @@ impl Yumush {
78 palette: Palette,77 palette: Palette,
79 cx: &App,78 cx: &App,
80 ) -> impl IntoElement {79 ) -> impl IntoElement {
81- let name = self80+ let community = self.chat.selected_community();
82- .chat81+ let name = community
83- .selected_community()
84 .map(|community| community.name.clone())82 .map(|community| community.name.clone())
85 .unwrap_or_default();83 .unwrap_or_default();
86 let actor = self.actor_rank();84 let actor = self.actor_rank();
87- let community_id = self.chat.selected_community_id.clone().unwrap_or_default();
88 let bans_count = self.chat.bans.len();85 let bans_count = self.chat.bans.len();
89 let mut sections = Vec::new();86 let mut sections = Vec::new();
90 87
91- if let Some(community) = self88+ if let Some(community) = community.filter(|_| permission::can_rename_community(actor)) {
92- .chat
93- .selected_community()
94- .filter(|_| permission::can_rename_community(actor))
95- {
96 sections.push(89 sections.push(
97 picture_card(90 picture_card(
98 Picture {91 Picture {
@@ -137,11 +130,7 @@ impl Yumush {
137 .into_any_element(),130 .into_any_element(),
138 );131 );
139 }132 }
140- if let Some(community) = self133+ if let Some(community) = community.filter(|_| permission::can_manage_voice(actor)) {
141- .chat
142- .selected_community()
143- .filter(|_| permission::can_manage_voice(actor))
144- {
145 sections.push(134 sections.push(
146 section(135 section(
147 "Voice",136 "Voice",
@@ -191,10 +180,10 @@ impl Yumush {
191 sections.push(section("Moderation", palette, moderation).into_any_element());180 sections.push(section("Moderation", palette, moderation).into_any_element());
192 }181 }
193 let mut danger = Vec::new();182 let mut danger = Vec::new();
194- if permission::can_leave(actor) {183+ if let Some(community) = community.filter(|_| permission::can_leave(actor)) {
195 danger.push(row(184 danger.push(row(
196 "Leave community",185 "Leave community",
197- leave_control(entity, community_id, palette),186+ leave_control(entity, community.id.clone(), palette),
198 ));187 ));
199 }188 }
200 if permission::can_delete_community(actor) {189 if permission::can_delete_community(actor) {
@@ -263,26 +252,13 @@ impl Yumush {
263 let Some(community_id) = self.chat.selected_community_id.clone() else {252 let Some(community_id) = self.chat.selected_community_id.clone() else {
264 return;253 return;
265 };254 };
266- let picked = cx.prompt_for_paths(PathPromptOptions {255+ let picked = picked_avatar(cx, self.max_avatar_bytes());
267- files: true,
268- directories: false,
269- multiple: false,
270- prompt: None,
271- });
272 let network = self.network.clone();256 let network = self.network.clone();
273- let maximum = self.max_avatar_bytes();
274 257
275 cx.spawn_in(window, async move |this, cx| {258 cx.spawn_in(window, async move |this, cx| {
276- let Ok(Ok(Some(paths))) = picked.await else {259+ let Some(prepared) = picked.await else {
277- return;
278- };
279- let Some(path) = paths.into_iter().next() else {
280 return;260 return;
281 };261 };
282- let prepared = cx
283- .background_executor()
284- .spawn(async move { read_avatar_file(&path, maximum) })
285- .await;
286 let result = match prepared {262 let result = match prepared {
287 Ok(bytes) => {263 Ok(bytes) => {
288 network264 network
crates/client/src/gui/composer.rsmodified+26 -28
@@ -9,8 +9,8 @@ use common::{
9 validate::{validate_message_body, validate_new_message, validate_poll},9 validate::{validate_message_body, validate_new_message, validate_poll},
10 };10 };
11 use gpui_kit::{11 use gpui_kit::{
12- Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement,12+ Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement,
13- KeyBinding, ParentElement, Styled, Window, actions,13+ IntoElement, KeyBinding, ParentElement, Styled, Window, actions,
14 assets::IconName,14 assets::IconName,
15 component::{15 component::{
16 Icon, WindowExt,16 Icon, WindowExt,
@@ -31,7 +31,7 @@ use super::{
31 31
32 actions!(composer, [Bold, Italic, Code, Strike]);32 actions!(composer, [Bold, Italic, Code, Strike]);
33 33
34-pub const CONTEXT: &str = "MessageComposer";34+const CONTEXT: &str = "MessageComposer";
35 35
36 const FORMAT_ROWS: [(&str, &str); 6] = [36 const FORMAT_ROWS: [(&str, &str); 6] = [
37 ("**bold**", "Ctrl+B"),37 ("**bold**", "Ctrl+B"),
@@ -471,22 +471,31 @@ fn wrap(input: &Entity<InputState>, mark: &str, window: &mut Window, cx: &mut Ap
471 });471 });
472 }472 }
473 473
474+pub(super) fn trigger_icon(
475+ id: impl Into<ElementId>,
476+ icon: IconName,
477+ size: f32,
478+ palette: Palette,
479+) -> Trigger {
480+ Trigger::new(hoverable(
481+ id,
482+ div()
483+ .size(px(size))
484+ .flex()
485+ .items_center()
486+ .justify_center()
487+ .rounded(px(6.))
488+ .text_color(palette.muted)
489+ .child(Icon::new(icon).w(px(14.)).h(px(14.))),
490+ palette,
491+ ))
492+}
493+
474 pub fn format_popover(palette: Palette) -> impl IntoElement {494 pub fn format_popover(palette: Palette) -> impl IntoElement {
475 Popover::new("format_popover")495 Popover::new("format_popover")
476 .anchor(Anchor::BottomLeft)496 .anchor(Anchor::BottomLeft)
477 .appearance(false)497 .appearance(false)
478- .trigger(Trigger::new(hoverable(498+ .trigger(trigger_icon("format_trigger", IconName::Type, 28., palette))
479- "format_trigger",
480- div()
481- .size(px(28.))
482- .flex()
483- .items_center()
484- .justify_center()
485- .rounded(px(6.))
486- .text_color(palette.muted)
487- .child(Icon::new(IconName::Type).w(px(14.)).h(px(14.))),
488- palette,
489- )))
490 .content(move |_, _, _| {499 .content(move |_, _, _| {
491 pop_in(500 pop_in(
492 "format_list",501 "format_list",
@@ -515,7 +524,7 @@ pub fn format_popover(palette: Palette) -> impl IntoElement {
515 })524 })
516 }525 }
517 526
518-fn poll_field(input: &Entity<InputState>, palette: Palette) -> impl IntoElement {527+pub(super) fn poll_field(input: &Entity<InputState>, palette: Palette) -> impl IntoElement {
519 div()528 div()
520 .h(px(30.))529 .h(px(30.))
521 .px(px(10.))530 .px(px(10.))
@@ -543,18 +552,7 @@ pub fn poll_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i
543 Popover::new("poll_popover")552 Popover::new("poll_popover")
544 .anchor(Anchor::BottomLeft)553 .anchor(Anchor::BottomLeft)
545 .appearance(false)554 .appearance(false)
546- .trigger(Trigger::new(hoverable(555+ .trigger(trigger_icon("poll_trigger", IconName::ChartBar, 28., palette))
547- "poll_trigger",
548- div()
549- .size(px(28.))
550- .flex()
551- .items_center()
552- .justify_center()
553- .rounded(px(6.))
554- .text_color(palette.muted)
555- .child(Icon::new(IconName::ChartBar).w(px(14.)).h(px(14.))),
556- palette,
557- )))
558 .content(move |_, _, cx| {556 .content(move |_, _, cx| {
559 let popover = cx.entity();557 let popover = cx.entity();
560 let toggle = entity.clone();558 let toggle = entity.clone();
crates/client/src/gui/forward.rsmodified+12 -20
@@ -5,12 +5,16 @@ use gpui_kit::{
5 component::{5 component::{
6 WindowExt,6 WindowExt,
7 checkbox::Checkbox,7 checkbox::Checkbox,
8- input::{Input, InputEvent, InputState},8+ input::{InputEvent, InputState},
9 },9 },
10 div, px,10 div, px,
11 };11 };
12 12
13-use super::{Yumush, clickable, community_name, composer::Composer, notify_error, palette};13+use super::{
14+ Yumush, clickable,
15+ composer::{Composer, poll_field},
16+ community_name, notify_error, palette,
17+};
14 18
15 pub struct Forward {19 pub struct Forward {
16 yumush: Entity<Yumush>,20 yumush: Entity<Yumush>,
@@ -97,22 +101,7 @@ impl Render for Forward {
97 .flex_col()101 .flex_col()
98 .gap(px(10.))102 .gap(px(10.))
99 .child(103 .child(
100- div()104+ poll_field(&self.filter, palette),
101- .h(px(30.))
102- .px(px(10.))
103- .flex()
104- .items_center()
105- .rounded(px(8.))
106- .border_1()
107- .border_color(palette.border)
108- .bg(palette.field)
109- .child(
110- Input::new(&self.filter)
111- .appearance(false)
112- .text_color(palette.text)
113- .flex_1()
114- .min_w_0(),
115- ),
116 )105 )
117 .child(106 .child(
118 Checkbox::new("keep_authors")107 Checkbox::new("keep_authors")
@@ -160,7 +149,7 @@ impl Yumush {
160 &mut self,149 &mut self,
161 selected: Vec<String>,150 selected: Vec<String>,
162 community_id: String,151 community_id: String,
163- snippet: bool,152+ keep_authors: bool,
164 window: &mut Window,153 window: &mut Window,
165 cx: &mut Context<Self>,154 cx: &mut Context<Self>,
166 ) {155 ) {
@@ -179,7 +168,10 @@ impl Yumush {
179 let network = self.network.clone();168 let network = self.network.clone();
180 169
181 cx.spawn_in(window, async move |this, cx| {170 cx.spawn_in(window, async move |this, cx| {
182- if let Err(error) = network.forward_messages(ids, &community_id, snippet).await {171+ if let Err(error) = network
172+ .forward_messages(ids, &community_id, keep_authors)
173+ .await
174+ {
183 notify_error(&this, cx, error);175 notify_error(&this, cx, error);
184 }176 }
185 })177 })
crates/client/src/gui/media_view.rsmodified+39 -20
@@ -8,9 +8,9 @@ use std::{
8 8
9 use common::model::{Attachment, AttachmentKind, Message};9 use common::model::{Attachment, AttachmentKind, Message};
10 use gpui_kit::{10 use gpui_kit::{
11- App, AppContext, Context, Entity, FontWeight, Image, ImageFormat, InteractiveElement,11+ App, AppContext, AsyncWindowContext, Context, Entity, FontWeight, Image, ImageFormat,
12- IntoElement, ParentElement, PathPromptOptions, RenderImage, StatefulInteractiveElement, Styled,12+ InteractiveElement, IntoElement, ParentElement, PathPromptOptions, RenderImage,
13- Subscription, Task, Window,13+ StatefulInteractiveElement, Styled, Subscription, Task, WeakEntity, Window,
14 assets::IconName,14 assets::IconName,
15 component::{15 component::{
16 Icon, WindowExt,16 Icon, WindowExt,
@@ -29,6 +29,7 @@ use super::{
29 use crate::{29 use crate::{
30 embed::{self, Embed, EmbedKind},30 embed::{self, Embed, EmbedKind},
31 media::{Player, voice_note as note},31 media::{Player, voice_note as note},
32+ network::NetworkHandle,
32 };33 };
33 34
34 const FRAME_TICK: Duration = Duration::from_millis(16);35 const FRAME_TICK: Duration = Duration::from_millis(16);
@@ -120,7 +121,7 @@ fn fit(width: Option<u32>, height: Option<u32>, limit: (f32, f32)) -> (f32, f32)
120 }121 }
121 122
122 fn cache_path(attachment: &Attachment) -> Option<PathBuf> {123 fn cache_path(attachment: &Attachment) -> Option<PathBuf> {
123- let directory = dirs::cache_dir()?.join("yumush").join("media");124+ let directory = note::media_cache_dir()?;
124 std::fs::create_dir_all(&directory).ok()?;125 std::fs::create_dir_all(&directory).ok()?;
125 let extension = attachment126 let extension = attachment
126 .name127 .name
@@ -135,6 +136,35 @@ pub fn time_text(time: Duration) -> String {
135 format!("{}:{:02}", seconds / 60, seconds % 60)136 format!("{}:{:02}", seconds / 60, seconds % 60)
136 }137 }
137 138
139+fn duration_secs(player: &Player) -> f32 {
140+ player
141+ .info()
142+ .duration
143+ .unwrap_or_default()
144+ .as_secs_f32()
145+ .max(0.1)
146+}
147+
148+pub(super) async fn upload_file(
149+ this: &WeakEntity<Yumush>,
150+ network: &NetworkHandle,
151+ community_id: &str,
152+ path: PathBuf,
153+ maximum: Option<u64>,
154+ cx: &mut AsyncWindowContext,
155+) -> Result<Attachment, common::error::Error> {
156+ let _ = this.update(cx, |yumush, cx| {
157+ yumush.chat.media.uploading += 1;
158+ cx.notify();
159+ });
160+ let uploaded = network.upload_attachment(community_id, path, maximum).await;
161+ let _ = this.update(cx, |yumush, cx| {
162+ yumush.chat.media.uploading -= 1;
163+ cx.notify();
164+ });
165+ uploaded
166+}
167+
138 fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> {168 fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> {
139 let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?;169 let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?;
140 Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)])))170 Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)])))
@@ -265,15 +295,9 @@ impl Yumush {
265 return;295 return;
266 };296 };
267 for path in paths {297 for path in paths {
298+ let result =
299+ upload_file(&this, &network, &community_id, path, maximum, cx).await;
268 let _ = this.update(cx, |yumush, cx| {300 let _ = this.update(cx, |yumush, cx| {
269- yumush.chat.media.uploading += 1;
270- cx.notify();
271- });
272- let result = network
273- .upload_attachment(&community_id, path, maximum)
274- .await;
275- let _ = this.update(cx, |yumush, cx| {
276- yumush.chat.media.uploading -= 1;
277 if let Ok(attachment) = &result {301 if let Ok(attachment) = &result {
278 yumush.chat.media.pending.push(attachment.clone());302 yumush.chat.media.pending.push(attachment.clone());
279 }303 }
@@ -417,11 +441,11 @@ impl Yumush {
417 window: &mut Window,441 window: &mut Window,
418 cx: &mut Context<Self>,442 cx: &mut Context<Self>,
419 ) {443 ) {
420- let duration = player.info().duration.unwrap_or_default().as_secs_f32();444+ let duration = duration_secs(&player);
421 let seek = cx.new(|_| {445 let seek = cx.new(|_| {
422 SliderState::new()446 SliderState::new()
423 .min(0.)447 .min(0.)
424- .max(duration.max(0.1))448+ .max(duration)
425 .default_value(0.)449 .default_value(0.)
426 });450 });
427 let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| {451 let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| {
@@ -760,12 +784,7 @@ fn waveform_view(
760 .map_or(&[][..], |waveform| waveform.peaks.as_slice());784 .map_or(&[][..], |waveform| waveform.peaks.as_slice());
761 match state {785 match state {
762 Some(PlayState::Ready { player, .. }) => {786 Some(PlayState::Ready { player, .. }) => {
763- let duration = player787+ let duration = duration_secs(player);
764- .info()
765- .duration
766- .unwrap_or_default()
767- .as_secs_f32()
768- .max(0.1);
769 let progress = player.position().as_secs_f32() / duration;788 let progress = player.position().as_secs_f32() / duration;
770 let entity = entity.clone();789 let entity = entity.clone();
771 bars(levels, progress, palette, move |index, _, cx| {790 bars(levels, progress, palette, move |index, _, cx| {
crates/client/src/gui/message_actions.rsmodified+9 -40
@@ -14,11 +14,12 @@ use gpui_kit::{
14 };14 };
15 15
16 use super::{16 use super::{
17- CLOCK, Palette, Tooltip as _, Trigger, Yumush,17+ CLOCK, Palette, Tooltip as _, Yumush,
18 auth::field,18 auth::field,
19 avatar,19 avatar,
20 chat::{Chat, ReportTarget},20 chat::{Chat, ReportTarget},
21- clickable, entity_action, hoverable, id_time, notify_error, pop_in, primary_button, sidebar,21+ clickable, composer::trigger_icon, entity_action, id_time, notify_error, pop_in,
22+ primary_button, sidebar,
22 };23 };
23 24
24 pub fn reactions(25 pub fn reactions(
@@ -84,22 +85,12 @@ pub fn react_popover(
84 Popover::new(format!("react_{}", message.id))85 Popover::new(format!("react_{}", message.id))
85 .anchor(Anchor::TopRight)86 .anchor(Anchor::TopRight)
86 .appearance(false)87 .appearance(false)
87- .trigger(Trigger::new(hoverable(88+ .trigger(trigger_icon(
88 format!("react_trigger_{}", message.id),89 format!("react_trigger_{}", message.id),
89- div()90+ IconName::FaceSlightlySmiling,
90- .size(px(24.))91+ 24.,
91- .flex()
92- .items_center()
93- .justify_center()
94- .rounded(px(6.))
95- .text_color(palette.muted)
96- .child(
97- Icon::new(IconName::FaceSlightlySmiling)
98- .w(px(14.))
99- .h(px(14.)),
100- ),
101 palette,92 palette,
102- )))93+ ))
103 .content(move |_, _, cx| {94 .content(move |_, _, cx| {
104 let popover = cx.entity();95 let popover = cx.entity();
105 pop_in(96 pop_in(
@@ -243,18 +234,7 @@ pub fn search_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) ->
243 Popover::new("search_popover")234 Popover::new("search_popover")
244 .anchor(Anchor::TopRight)235 .anchor(Anchor::TopRight)
245 .appearance(false)236 .appearance(false)
246- .trigger(Trigger::new(hoverable(237+ .trigger(trigger_icon("search_trigger", IconName::Search, 24., palette))
247- "search_trigger",
248- div()
249- .size(px(24.))
250- .flex()
251- .items_center()
252- .justify_center()
253- .rounded(px(6.))
254- .text_color(palette.muted)
255- .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))),
256- palette,
257- )))
258 .content(move |_, _, cx| {238 .content(move |_, _, cx| {
259 let popover = cx.entity();239 let popover = cx.entity();
260 pop_in(240 pop_in(
@@ -331,18 +311,7 @@ pub fn pins_popover(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> i
331 Popover::new("pins_popover")311 Popover::new("pins_popover")
332 .anchor(Anchor::TopRight)312 .anchor(Anchor::TopRight)
333 .appearance(false)313 .appearance(false)
334- .trigger(Trigger::new(hoverable(314+ .trigger(trigger_icon("pins_trigger", IconName::Pin, 24., palette))
335- "pins_trigger",
336- div()
337- .size(px(24.))
338- .flex()
339- .items_center()
340- .justify_center()
341- .rounded(px(6.))
342- .text_color(palette.muted)
343- .child(Icon::new(IconName::Pin).w(px(14.)).h(px(14.))),
344- palette,
345- )))
346 .content(move |_, _, cx| {315 .content(move |_, _, cx| {
347 let popover = cx.entity();316 let popover = cx.entity();
348 pop_in(317 pop_in(
crates/client/src/gui/poll.rsmodified+9 -9
@@ -25,14 +25,14 @@ fn my_positions(poll: &Poll, user_id: &str) -> Vec<u32> {
25 .collect()25 .collect()
26 }26 }
27 27
28-fn next_votes(poll: &Poll, user_id: &str, position: u32) -> Vec<u32> {28+fn next_votes(mine: &[u32], position: u32, multiple: bool) -> Vec<u32> {
29- let mut mine = my_positions(poll, user_id);29+ let mut next = mine.to_vec();
30 if mine.contains(&position) {30 if mine.contains(&position) {
31- mine.retain(|mine| *mine != position);31+ next.retain(|vote| *vote != position);
32- mine32+ next
33- } else if poll.multiple {33+ } else if multiple {
34- mine.push(position);34+ next.push(position);
35- mine35+ next
36 } else {36 } else {
37 vec![position]37 vec![position]
38 }38 }
@@ -69,7 +69,7 @@ pub fn poll_card(
69 .filter(|message| {69 .filter(|message| {
70 !poll.closed70 !poll.closed
71 && me.is_some_and(|me| {71 && me.is_some_and(|me| {
72- me.id == message.user_id || chat.my_rank(me) >= Some(Rank::Moderator)72+ me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator)
73 })73 })
74 })74 })
75 .map(|message| message.id.clone());75 .map(|message| message.id.clone());
@@ -79,7 +79,7 @@ pub fn poll_card(
79 let share = percent(count, voters);79 let share = percent(count, voters);
80 let picked = mine.contains(&(position as u32));80 let picked = mine.contains(&(position as u32));
81 let next = me_id81 let next = me_id
82- .map(|id| next_votes(poll, id, position as u32))82+ .map(|_| next_votes(&mine, position as u32, poll.multiple))
83 .unwrap_or_default();83 .unwrap_or_default();
84 let entity = entity.clone();84 let entity = entity.clone();
85 let id = format!("poll_option_{key}_{position}");85 let id = format!("poll_option_{key}_{position}");
crates/client/src/gui/profile.rsmodified+37 -47
@@ -138,7 +138,7 @@ impl Card {
138 menu_row(138 menu_row(
139 "profile_message",139 "profile_message",
140 "Message",140 "Message",
141- IconName::MessageSquare,141+ menu_icon(IconName::MessageSquare),
142 palette.text,142 palette.text,
143 palette,143 palette,
144 yumush_action(entity, popover, move |yumush, window, cx| {144 yumush_action(entity, popover, move |yumush, window, cx| {
@@ -153,7 +153,7 @@ impl Card {
153 menu_row(153 menu_row(
154 "profile_report",154 "profile_report",
155 "Report",155 "Report",
156- IconName::TriangleAlert,156+ menu_icon(IconName::TriangleAlert),
157 palette.danger,157 palette.danger,
158 palette,158 palette,
159 entity_action(entity, move |yumush, window, cx| {159 entity_action(entity, move |yumush, window, cx| {
@@ -169,7 +169,7 @@ impl Card {
169 menu_row(169 menu_row(
170 "profile_friend",170 "profile_friend",
171 label,171 label,
172- icon,172+ menu_icon(icon),
173 palette.text,173 palette.text,
174 palette,174 palette,
175 yumush_action(entity, popover, move |yumush, window, cx| {175 yumush_action(entity, popover, move |yumush, window, cx| {
@@ -287,7 +287,7 @@ impl Card {
287 menu_row(287 menu_row(
288 label.clone(),288 label.clone(),
289 label,289 label,
290- IconName::Shield,290+ menu_icon(IconName::Shield),
291 palette.text,291 palette.text,
292 palette,292 palette,
293 yumush_action(entity, popover, move |yumush, window, cx| {293 yumush_action(entity, popover, move |yumush, window, cx| {
@@ -306,7 +306,7 @@ impl Card {
306 menu_row(306 menu_row(
307 "kick",307 "kick",
308 "Kick",308 "Kick",
309- IconName::Close,309+ menu_icon(IconName::Close),
310 palette.danger,310 palette.danger,
311 palette,311 palette,
312 yumush_action(entity, popover, move |yumush, window, cx| {312 yumush_action(entity, popover, move |yumush, window, cx| {
@@ -319,7 +319,7 @@ impl Card {
319 menu_row(319 menu_row(
320 "ban",320 "ban",
321 "Ban",321 "Ban",
322- IconName::Ban,322+ menu_icon(IconName::Ban),
323 palette.danger,323 palette.danger,
324 palette,324 palette,
325 yumush_action(entity, popover, move |yumush, window, cx| {325 yumush_action(entity, popover, move |yumush, window, cx| {
@@ -345,7 +345,7 @@ impl Card {
345 menu_row(345 menu_row(
346 "delete_user",346 "delete_user",
347 label,347 label,
348- IconName::Trash,348+ menu_icon(IconName::Trash),
349 palette.danger,349 palette.danger,
350 palette,350 palette,
351 delete_user_action(&user_id, self.confirming, entity, popover),351 delete_user_action(&user_id, self.confirming, entity, popover),
@@ -380,30 +380,26 @@ fn main_self_rows(
380 palette: Palette,380 palette: Palette,
381 ) -> Vec<AnyElement> {381 ) -> Vec<AnyElement> {
382 vec![382 vec![
383- presence_row(383+ drill_row(menu_row(
384 "profile_presence",384 "profile_presence",
385- presence,385+ presence.label(),
386+ presence_dot(presence, palette),
387+ palette.text,
386 palette,388 palette,
387 card_menu_action(entity, CardMenu::Presence),389 card_menu_action(entity, CardMenu::Presence),
388- )390+ )),
389- .child(div().flex_1())391+ drill_row(menu_row(
390- .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.)))
391- .into_any_element(),
392- menu_row(
393 "profile_accounts",392 "profile_accounts",
394 "Accounts",393 "Accounts",
395- IconName::CircleUser,394+ menu_icon(IconName::CircleUser),
396 palette.text,395 palette.text,
397 palette,396 palette,
398 card_menu_action(entity, CardMenu::Accounts),397 card_menu_action(entity, CardMenu::Accounts),
399- )398+ )),
400- .child(div().flex_1())
401- .child(Icon::new(IconName::ChevronRight).w(px(14.)).h(px(14.)))
402- .into_any_element(),
403 menu_row(399 menu_row(
404 "profile_settings",400 "profile_settings",
405 "Settings",401 "Settings",
406- IconName::Settings,402+ menu_icon(IconName::Settings),
407 palette.text,403 palette.text,
408 palette,404 palette,
409 yumush_action(entity, popover, |yumush, window, cx| {405 yumush_action(entity, popover, |yumush, window, cx| {
@@ -414,7 +410,7 @@ fn main_self_rows(
414 menu_row(410 menu_row(
415 "profile_logout",411 "profile_logout",
416 "Log out",412 "Log out",
417- IconName::LogOut,413+ menu_icon(IconName::LogOut),
418 palette.danger,414 palette.danger,
419 palette,415 palette,
420 yumush_action(entity, popover, |yumush, window, cx| {416 yumush_action(entity, popover, |yumush, window, cx| {
@@ -436,7 +432,7 @@ fn accounts_rows(
436 menu_row(432 menu_row(
437 format!("switch_{user_id}"),433 format!("switch_{user_id}"),
438 username.clone(),434 username.clone(),
439- IconName::CircleUser,435+ menu_icon(IconName::CircleUser),
440 palette.text,436 palette.text,
441 palette,437 palette,
442 yumush_action(entity, popover, move |yumush, window, cx| {438 yumush_action(entity, popover, move |yumush, window, cx| {
@@ -449,7 +445,7 @@ fn accounts_rows(
449 menu_row(445 menu_row(
450 "profile_accounts_back",446 "profile_accounts_back",
451 "Accounts",447 "Accounts",
452- IconName::ArrowLeft,448+ menu_icon(IconName::ArrowLeft),
453 palette.muted,449 palette.muted,
454 palette,450 palette,
455 card_menu_action(entity, CardMenu::Main),451 card_menu_action(entity, CardMenu::Main),
@@ -466,7 +462,7 @@ fn accounts_rows(
466 menu_row(462 menu_row(
467 "profile_add_account",463 "profile_add_account",
468 "Add account",464 "Add account",
469- IconName::UserPlus,465+ menu_icon(IconName::UserPlus),
470 palette.text,466 palette.text,
471 palette,467 palette,
472 yumush_action(entity, popover, |yumush, window, cx| {468 yumush_action(entity, popover, |yumush, window, cx| {
@@ -482,7 +478,7 @@ fn presence_rows(entity: &Entity<Yumush>, palette: Palette) -> Vec<AnyElement> {
482 menu_row(478 menu_row(
483 "profile_presence_back",479 "profile_presence_back",
484 "Status",480 "Status",
485- IconName::ArrowLeft,481+ menu_icon(IconName::ArrowLeft),
486 palette.muted,482 palette.muted,
487 palette,483 palette,
488 card_menu_action(entity, CardMenu::Main),484 card_menu_action(entity, CardMenu::Main),
@@ -491,9 +487,11 @@ fn presence_rows(entity: &Entity<Yumush>, palette: Palette) -> Vec<AnyElement> {
491 ];487 ];
492 488
493 rows.extend(Presence::ALL.into_iter().map(|presence| {489 rows.extend(Presence::ALL.into_iter().map(|presence| {
494- presence_row(490+ menu_row(
495 format!("presence_{}", presence.as_str()),491 format!("presence_{}", presence.as_str()),
496- presence,492+ presence.label(),
493+ presence_dot(presence, palette),
494+ palette.text,
497 palette,495 palette,
498 entity_action(entity, move |yumush, window, cx| {496 entity_action(entity, move |yumush, window, cx| {
499 yumush.set_presence(presence, window, cx)497 yumush.set_presence(presence, window, cx)
@@ -522,24 +520,6 @@ fn presence_dot(presence: Presence, palette: Palette) -> Div {
522 .bg(presence_color(presence, palette))520 .bg(presence_color(presence, palette))
523 }521 }
524 522
525-fn presence_row(
526- id: impl Into<ElementId>,
527- presence: Presence,
528- palette: Palette,
529- on_click: impl Fn(&mut Window, &mut App) + 'static,
530-) -> Stateful<Div> {
531- clickable(id, palette, on_click)
532- .h(px(30.))
533- .px(px(8.))
534- .flex()
535- .items_center()
536- .gap(px(8.))
537- .rounded(px(6.))
538- .text_color(palette.text)
539- .child(presence_dot(presence, palette))
540- .child(presence.label())
541-}
542-
543 fn yumush_action(523 fn yumush_action(
544 entity: &Entity<Yumush>,524 entity: &Entity<Yumush>,
545 popover: &Entity<PopoverState>,525 popover: &Entity<PopoverState>,
@@ -576,10 +556,14 @@ fn delete_user_action(
576 }556 }
577 }557 }
578 558
559+fn menu_icon(icon: IconName) -> Icon {
560+ Icon::new(icon).w(px(14.)).h(px(14.))
561+}
562+
579 fn menu_row(563 fn menu_row(
580 id: impl Into<ElementId>,564 id: impl Into<ElementId>,
581 label: impl Into<SharedString>,565 label: impl Into<SharedString>,
582- icon: IconName,566+ leading: impl IntoElement,
583 color: Hsla,567 color: Hsla,
584 palette: Palette,568 palette: Palette,
585 on_click: impl Fn(&mut Window, &mut App) + 'static,569 on_click: impl Fn(&mut Window, &mut App) + 'static,
@@ -592,10 +576,16 @@ fn menu_row(
592 .gap(px(8.))576 .gap(px(8.))
593 .rounded(px(6.))577 .rounded(px(6.))
594 .text_color(color)578 .text_color(color)
595- .child(Icon::new(icon).w(px(14.)).h(px(14.)))579+ .child(leading)
596 .child(label.into())580 .child(label.into())
597 }581 }
598 582
583+fn drill_row(row: Stateful<Div>) -> AnyElement {
584+ row.child(div().flex_1())
585+ .child(menu_icon(IconName::ChevronRight))
586+ .into_any_element()
587+}
588+
599 impl Yumush {589 impl Yumush {
600 fn open_removal(590 fn open_removal(
601 &self,591 &self,
crates/client/src/gui/settings_page.rsmodified+56 -60
@@ -1,10 +1,11 @@
1 use super::text;1 use super::text;
2-use std::path::Path;2+use std::{future::Future, path::Path};
3 3
4 use common::{error::Error, model::User};4 use common::{error::Error, model::User};
5 use gpui_kit::{5 use gpui_kit::{
6- AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement,6+ AnyElement, App, AsyncWindowContext, Context, Div, Entity, FontWeight, Hsla,
7- ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window,7+ InteractiveElement, IntoElement, ParentElement, PathPromptOptions, Stateful,
8+ StatefulInteractiveElement, Styled, WeakEntity, Window,
8 assets::IconName,9 assets::IconName,
9 component::{Icon, input::InputState, switch::Switch},10 component::{Icon, input::InputState, switch::Switch},
10 div,11 div,
@@ -18,19 +19,6 @@ use super::{
18 };19 };
19 use crate::settings::{self, FontSize, ThemeChoice};20 use crate::settings::{self, FontSize, ThemeChoice};
20 21
21-const THEMES: [(ThemeChoice, &str); 4] = [
22- (ThemeChoice::System, "System"),
23- (ThemeChoice::Light, "Light"),
24- (ThemeChoice::Dark, "Dark"),
25- (ThemeChoice::Black, "Black"),
26-];
27-
28-const FONT_SIZES: [(FontSize, &str); 3] = [
29- (FontSize::Small, "Small"),
30- (FontSize::Medium, "Medium"),
31- (FontSize::Large, "Large"),
32-];
33-
34 impl Yumush {22 impl Yumush {
35 pub(super) fn settings_page(23 pub(super) fn settings_page(
36 &self,24 &self,
@@ -101,7 +89,7 @@ impl Yumush {
101 row(89 row(
102 "Theme",90 "Theme",
103 segmented(91 segmented(
104- THEMES,92+ ThemeChoice::ALL.map(|choice| (choice, choice.label())),
105 self.settings.theme,93 self.settings.theme,
106 entity,94 entity,
107 palette,95 palette,
@@ -111,7 +99,7 @@ impl Yumush {
111 row(99 row(
112 "Font size",100 "Font size",
113 segmented(101 segmented(
114- FONT_SIZES,102+ FontSize::ALL.map(|size| (size, size.label())),
115 self.settings.font_size,103 self.settings.font_size,
116 entity,104 entity,
117 palette,105 palette,
@@ -171,12 +159,8 @@ impl Yumush {
171 let network = self.network.clone();159 let network = self.network.clone();
172 160
173 cx.spawn_in(window, async move |this, cx| {161 cx.spawn_in(window, async move |this, cx| {
174- match network.update_user(&username).await {162+ let result = network.update_user(&username).await;
175- Ok(user) => {163+ apply_user(&this, cx, result);
176- let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
177- }
178- Err(error) => notify_error(&this, cx, error),
179- }
180 })164 })
181 .detach();165 .detach();
182 }166 }
@@ -186,49 +170,25 @@ impl Yumush {
186 let network = self.network.clone();170 let network = self.network.clone();
187 171
188 cx.spawn_in(window, async move |this, cx| {172 cx.spawn_in(window, async move |this, cx| {
189- match network.update_status(&status).await {173+ let result = network.update_status(&status).await;
190- Ok(user) => {174+ apply_user(&this, cx, result);
191- let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
192- }
193- Err(error) => notify_error(&this, cx, error),
194- }
195 })175 })
196 .detach();176 .detach();
197 }177 }
198 178
199 pub(super) fn upload_avatar(&mut self, window: &mut Window, cx: &mut Context<Self>) {179 pub(super) fn upload_avatar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
200- let picked = cx.prompt_for_paths(PathPromptOptions {180+ let picked = picked_avatar(cx, self.max_avatar_bytes());
201- files: true,
202- directories: false,
203- multiple: false,
204- prompt: None,
205- });
206 let network = self.network.clone();181 let network = self.network.clone();
207- let maximum = self.max_avatar_bytes();
208 182
209 cx.spawn_in(window, async move |this, cx| {183 cx.spawn_in(window, async move |this, cx| {
210- let Ok(Ok(Some(paths))) = picked.await else {184+ let Some(prepared) = picked.await else {
211- return;
212- };
213- let Some(path) = paths.into_iter().next() else {
214 return;185 return;
215 };186 };
216-
217- let prepared = cx
218- .background_executor()
219- .spawn(async move { read_avatar_file(&path, maximum) })
220- .await;
221 let result = match prepared {187 let result = match prepared {
222 Ok(bytes) => network.update_avatar(bytes).await,188 Ok(bytes) => network.update_avatar(bytes).await,
223 Err(error) => Err(error),189 Err(error) => Err(error),
224 };190 };
225-191+ apply_user(&this, cx, result);
226- match result {
227- Ok(user) => {
228- let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
229- }
230- Err(error) => notify_error(&this, cx, error),
231- }
232 })192 })
233 .detach();193 .detach();
234 }194 }
@@ -237,12 +197,8 @@ impl Yumush {
237 let network = self.network.clone();197 let network = self.network.clone();
238 198
239 cx.spawn_in(window, async move |this, cx| {199 cx.spawn_in(window, async move |this, cx| {
240- match network.remove_avatar().await {200+ let result = network.remove_avatar().await;
241- Ok(user) => {201+ apply_user(&this, cx, result);
242- let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
243- }
244- Err(error) => notify_error(&this, cx, error),
245- }
246 })202 })
247 .detach();203 .detach();
248 }204 }
@@ -293,6 +249,46 @@ impl Yumush {
293 }249 }
294 }250 }
295 251
252+fn apply_user(
253+ this: &WeakEntity<Yumush>,
254+ cx: &mut AsyncWindowContext,
255+ result: Result<User, Error>,
256+) {
257+ match result {
258+ Ok(user) => {
259+ let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
260+ }
261+ Err(error) => notify_error(this, cx, error),
262+ }
263+}
264+
265+pub(super) fn picked_avatar(
266+ cx: &App,
267+ maximum: u64,
268+) -> impl Future<Output = Option<Result<Vec<u8>, Error>>> + 'static {
269+ let picked = cx.prompt_for_paths(PathPromptOptions {
270+ files: true,
271+ directories: false,
272+ multiple: false,
273+ prompt: None,
274+ });
275+ let executor = cx.background_executor().clone();
276+
277+ async move {
278+ let Ok(Ok(Some(paths))) = picked.await else {
279+ return None;
280+ };
281+ let Some(path) = paths.into_iter().next() else {
282+ return None;
283+ };
284+ Some(
285+ executor
286+ .spawn(async move { read_avatar_file(&path, maximum) })
287+ .await,
288+ )
289+ }
290+}
291+
296 pub(super) fn header(292 pub(super) fn header(
297 entity: &Entity<Yumush>,293 entity: &Entity<Yumush>,
298 palette: Palette,294 palette: Palette,
@@ -577,7 +573,7 @@ pub(super) fn delete_control(
577 .child(if confirming { "Confirm" } else { "Delete" })573 .child(if confirming { "Confirm" } else { "Delete" })
578 }574 }
579 575
580-pub(super) fn read_avatar_file(path: &Path, maximum: u64) -> Result<Vec<u8>, Error> {576+fn read_avatar_file(path: &Path, maximum: u64) -> Result<Vec<u8>, Error> {
581 let bytes = std::fs::read(path)?;577 let bytes = std::fs::read(path)?;
582 578
583 crate::avatar::prepare(&bytes, maximum)579 crate::avatar::prepare(&bytes, maximum)
crates/client/src/gui/sidebar.rsmodified+160 -181
@@ -1,12 +1,12 @@
1 use super::text;1 use super::text;
2 use common::{2 use common::{
3- model::{CommunityKind, Invitation, Role, Unread, User},3+ model::{Community, CommunityKind, Invitation, Role, Unread, User},
4 permission,4 permission,
5 validate::validate_community_name,5 validate::validate_community_name,
6 };6 };
7 use gpui_kit::{7 use gpui_kit::{
8 Anchor, AnimationExt, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement,8 Anchor, AnimationExt, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement,
9- IntoElement, MouseButton, ParentElement, StatefulInteractiveElement, Styled, Window,9+ IntoElement, MouseButton, ParentElement, Pixels, StatefulInteractiveElement, Styled, Window,
10 assets::IconName,10 assets::IconName,
11 component::{11 component::{
12 Icon,12 Icon,
@@ -47,13 +47,15 @@ impl Yumush {
47 palette: Palette,47 palette: Palette,
48 ) -> impl IntoElement {48 ) -> impl IntoElement {
49 let collapsed = self.chat.sidebar_collapsed;49 let collapsed = self.chat.sidebar_collapsed;
50- let (from, to, id) = match collapsed {50+ let (from, to, id) = if collapsed {
51- true => (SIDEBAR_WIDTH, SIDEBAR_COLLAPSED_WIDTH, "sidebar_collapsing"),51+ (SIDEBAR_WIDTH, SIDEBAR_COLLAPSED_WIDTH, "sidebar_collapsing")
52- false => (SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_WIDTH, "sidebar_expanding"),52+ } else {
53+ (SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_WIDTH, "sidebar_expanding")
53 };54 };
54- let content = match collapsed {55+ let content = if collapsed {
55- true => self.collapsed_sidebar(entity, palette).into_any_element(),56+ self.collapsed_sidebar(entity, palette).into_any_element()
56- false => self.expanded_sidebar(entity, query, palette),57+ } else {
58+ self.expanded_sidebar(entity, query, palette)
57 };59 };
58 60
59 div()61 div()
@@ -136,65 +138,54 @@ impl Yumush {
136 138
137 fn voice_panel(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {139 fn voice_panel(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
138 let community = self.chat.voice_room()?;140 let community = self.chat.voice_room()?;
139- let direct = matches!(community.kind, CommunityKind::Direct { .. });
140- let go_id = community.id.clone();
141 let tone = voice_stats::quality(&self.chat.voice_samples)141 let tone = voice_stats::quality(&self.chat.voice_samples)
142 .map_or(palette.ok, |quality| quality.color(palette));142 .map_or(palette.ok, |quality| quality.color(palette));
143 let stats_entity = entity.clone();143 let stats_entity = entity.clone();
144 144
145- let panel = div()145+ let panel = call_style(div(), palette)
146 .flex()146 .flex()
147 .items_center()147 .items_center()
148 .gap(px(4.))148 .gap(px(4.))
149 .p(px(6.))149 .p(px(6.))
150 .rounded(px(8.))150 .rounded(px(8.))
151- .border_1()
152- .border_color(palette.ok.opacity(0.35))
153- .bg(palette.ok.opacity(0.08))
154 .child(151 .child(
155- clickable(152+ clickable("voice_panel_go", palette, go_to_call(entity, community))
156- "voice_panel_go",153+ .tip("Go to call")
157- palette,154+ .flex_1()
158- entity_action(entity, move |yumush, window, cx| {155+ .min_w_0()
159- yumush.go_to_community(go_id.clone(), direct, window, cx)156+ .px(px(4.))
160- }),157+ .py(px(2.))
161- )158+ .rounded(px(6.))
162- .tip("Go to call")159+ .flex()
163- .flex_1()160+ .items_center()
164- .min_w_0()161+ .gap(px(8.))
165- .px(px(4.))162+ .child(
166- .py(px(2.))163+ Icon::new(IconName::AudioLines)
167- .rounded(px(6.))164+ .w(px(16.))
168- .flex()165+ .h(px(16.))
169- .items_center()166+ .text_color(tone),
170- .gap(px(8.))167+ )
171- .child(168+ .child(
172- Icon::new(IconName::AudioLines)169+ div()
173- .w(px(16.))170+ .flex_1()
174- .h(px(16.))171+ .min_w_0()
175- .text_color(tone),172+ .flex()
176- )173+ .flex_col()
177- .child(174+ .child(
178- div()175+ div()
179- .flex_1()176+ .text_size(text(12.))
180- .min_w_0()177+ .font_weight(FontWeight::SEMIBOLD)
181- .flex()178+ .text_color(palette.ok)
182- .flex_col()179+ .child("Voice connected"),
183- .child(180+ )
184- div()181+ .child(
185- .text_size(text(12.))182+ div()
186- .font_weight(FontWeight::SEMIBOLD)183+ .truncate()
187- .text_color(palette.ok)184+ .text_size(text(11.))
188- .child("Voice connected"),185+ .text_color(palette.muted)
189- )186+ .child(community_name(community).to_string()),
190- .child(187+ ),
191- div()188+ ),
192- .truncate()
193- .text_size(text(11.))
194- .text_color(palette.muted)
195- .child(community_name(community).to_string()),
196- ),
197- ),
198 )189 )
199 .child(icon_button(190 .child(icon_button(
200 "voice_panel_leave".to_string(),191 "voice_panel_leave".to_string(),
@@ -226,16 +217,15 @@ impl Yumush {
226 217
227 fn voice_dot(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {218 fn voice_dot(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
228 let community = self.chat.voice_room()?;219 let community = self.chat.voice_room()?;
229- let direct = matches!(community.kind, CommunityKind::Direct { .. });
230- let go_id = community.id.clone();
231 220
232 Some(221 Some(
233- clickable(222+ call_style(
234- "voice_panel_go_collapsed",223+ clickable(
224+ "voice_panel_go_collapsed",
225+ palette,
226+ go_to_call(entity, community),
227+ ),
235 palette,228 palette,
236- entity_action(entity, move |yumush, window, cx| {
237- yumush.go_to_community(go_id.clone(), direct, window, cx)
238- }),
239 )229 )
240 .tip("Go to call")230 .tip("Go to call")
241 .size(px(28.))231 .size(px(28.))
@@ -243,9 +233,6 @@ impl Yumush {
243 .items_center()233 .items_center()
244 .justify_center()234 .justify_center()
245 .rounded(px(6.))235 .rounded(px(6.))
246- .border_1()
247- .border_color(palette.ok.opacity(0.35))
248- .bg(palette.ok.opacity(0.08))
249 .child(236 .child(
250 Icon::new(IconName::AudioLines)237 Icon::new(IconName::AudioLines)
251 .w(px(14.))238 .w(px(14.))
@@ -275,9 +262,10 @@ impl Yumush {
275 }262 }
276 263
277 fn collapse_button(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement {264 fn collapse_button(&self, entity: &Entity<Self>, palette: Palette) -> AnyElement {
278- let (icon, tip) = match self.chat.sidebar_collapsed {265+ let (icon, tip) = if self.chat.sidebar_collapsed {
279- true => (IconName::PanelLeftOpen, "Expand"),266+ (IconName::PanelLeftOpen, "Expand")
280- false => (IconName::PanelLeftClose, "Collapse"),267+ } else {
268+ (IconName::PanelLeftClose, "Collapse")
281 };269 };
282 270
283 icon_button(271 icon_button(
@@ -294,13 +282,9 @@ impl Yumush {
294 282
295 fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {283 fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
296 let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32;284 let requests = (self.chat.friends.incoming.len() + self.chat.invitations.len()) as u32;
297- let direct = self.chat.unread_total(false);285+ let direct = self.chat.unread_direct();
298 let tabs = [286 let tabs = [
299- (287+ (SidebarTab::Communities, "Communities", self.chat.unread_groups()),
300- SidebarTab::Communities,
301- "Communities",
302- self.chat.unread_total(true),
303- ),
304 (288 (
305 SidebarTab::Messages,289 SidebarTab::Messages,
306 "Messages",290 "Messages",
@@ -330,7 +314,7 @@ impl Yumush {
330 .gap(px(6.))314 .gap(px(6.))
331 .text_size(text(12.))315 .text_size(text(12.))
332 .child(label)316 .child(label)
333- .children(badge(palette, false, Some(&alert)));317+ .children(unread_badge(palette, false, Some(&alert)));
334 318
335 match tab {319 match tab {
336 SidebarTab::Communities => item320 SidebarTab::Communities => item
@@ -390,7 +374,7 @@ impl Yumush {
390 .h(px(20.))374 .h(px(20.))
391 .text_color(palette.accent),375 .text_color(palette.accent),
392 "Notes",376 "Notes",
393- badge(palette, false, unread),377+ unread_badge(palette, false, unread),
394 ),378 ),
395 palette.accent.opacity(0.1),379 palette.accent.opacity(0.1),
396 )380 )
@@ -423,45 +407,56 @@ impl Yumush {
423 .map(|community| {407 .map(|community| {
424 let active = self.chat.is_selected(&community.id);408 let active = self.chat.is_selected(&community.id);
425 let muted = self.chat.muted.contains(&community.id);409 let muted = self.chat.muted.contains(&community.id);
426- let unread = self.chat.unread.get(&community.id);
427 let can_leave = !active || permission::can_leave(self.actor_rank());410 let can_leave = !active || permission::can_leave(self.actor_rank());
428- let community_id = community.id.clone();411+
429- let select = entity.clone();412+ self.sidebar_community_row(
430-
431- let themed = palette.for_community(Some(community), &self.chat.hues);
432- hoverable_with(
433- format!("community_{}", community.id),
434- entry(
435- themed,
436- active,
437- community_icon(
438- palette,
439- community,
440- px(16.),
441- text(10.),
442- &self.chat.avatars,
443- ),
444- community.name.clone(),
445- badge(palette, muted, unread),
446- ),
447- themed.accent.opacity(0.1),
448- )
449- .on_click(move |_, window, cx| {
450- select.update(cx, |yumush, cx| {
451- yumush.select_community(community_id.clone(), window, cx)
452- })
453- })
454- .context_menu(community_menu(
455 entity,413 entity,
456- community.id.clone(),414+ community,
457- can_leave,415+ palette,
458- muted,416+ px(16.),
459- ))417+ "community",
460- .into_any_element()418+ community_menu(entity, community.id.clone(), can_leave, muted),
419+ )
461 }),420 }),
462 )421 )
463 }422 }
464 423
424+ fn sidebar_community_row(
425+ &self,
426+ entity: &Entity<Self>,
427+ community: &Community,
428+ palette: Palette,
429+ size: Pixels,
430+ key: &str,
431+ menu: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
432+ ) -> AnyElement {
433+ let active = self.chat.is_selected(&community.id);
434+ let muted = self.chat.muted.contains(&community.id);
435+ let unread = self.chat.unread.get(&community.id);
436+ let community_id = community.id.clone();
437+ let select = entity.clone();
438+
439+ let themed = palette.for_community(Some(community), &self.chat.hues);
440+ hoverable_with(
441+ format!("{key}_{}", community.id),
442+ entry(
443+ themed,
444+ active,
445+ self.community_badge(community, size, text(10.), palette),
446+ community_name(community).to_string(),
447+ unread_badge(palette, muted, unread),
448+ ),
449+ themed.accent.opacity(0.1),
450+ )
451+ .on_click(move |_, window, cx| {
452+ select.update(cx, |yumush, cx| {
453+ yumush.select_community(community_id.clone(), window, cx)
454+ })
455+ })
456+ .context_menu(menu)
457+ .into_any_element()
458+ }
459+
465 fn requests(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {460 fn requests(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
466 let friends = &self.chat.friends;461 let friends = &self.chat.friends;
467 let rows: Vec<AnyElement> = friends462 let rows: Vec<AnyElement> = friends
@@ -489,34 +484,21 @@ impl Yumush {
489 self.chat484 self.chat
490 .communities485 .communities
491 .iter()486 .iter()
492- .filter(|community| matches!(community.kind, CommunityKind::Direct { .. }))487+ .filter(|community| community.kind.is_direct())
493 .filter(|community| matches_query(community_name(community), query))488 .filter(|community| matches_query(community_name(community), query))
494 .map(|community| {489 .map(|community| {
495- let active = self.chat.is_selected(&community.id);
496 let muted = self.chat.muted.contains(&community.id);490 let muted = self.chat.muted.contains(&community.id);
497- let unread = self.chat.unread.get(&community.id);491+ let menu_entity = entity.clone();
498- let community_id = community.id.clone();492+ let menu_id = community.id.clone();
499- let select = entity.clone();493+
500-494+ self.sidebar_community_row(
501- let themed = palette.for_community(Some(community), &self.chat.hues);495+ entity,
502- hoverable_with(496+ community,
503- format!("direct_{}", community.id),497+ palette,
504- entry(498+ px(20.),
505- themed,499+ "direct",
506- active,500+ move |menu, _, _| mute_item(menu, &menu_entity, menu_id.clone(), muted),
507- self.community_badge(community, px(20.), text(10.), palette),
508- community_name(community).to_string(),
509- badge(palette, muted, unread),
510- ),
511- themed.accent.opacity(0.1),
512 )501 )
513- .on_click(move |_, window, cx| {
514- select.update(cx, |yumush, cx| {
515- yumush.select_community(community_id.clone(), window, cx)
516- })
517- })
518- .context_menu(direct_menu(entity, community.id.clone(), muted))
519- .into_any_element()
520 })502 })
521 .collect()503 .collect()
522 }504 }
@@ -535,18 +517,7 @@ impl Yumush {
535 517
536 hoverable(518 hoverable(
537 format!("friend_{}", user.id),519 format!("friend_{}", user.id),
538- entry(520+ self.user_row(palette, user, Vec::new()),
539- palette,
540- false,
541- presence_avatar(
542- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
543- self.presence_of(&user.id),
544- px(20.),
545- palette,
546- ),
547- user.username.clone(),
548- Vec::new(),
549- ),
550 palette,521 palette,
551 )522 )
552 .on_click(move |_, window, cx| {523 .on_click(move |_, window, cx| {
@@ -587,10 +558,11 @@ impl Yumush {
587 }),558 }),
588 ));559 ));
589 }560 }
590- if let Some((label, icon)) = relation561+ let action = match relation {
591- .action()562+ Relation::Stranger | Relation::Incoming => relation.action(),
592- .filter(|_| matches!(relation, Relation::Stranger | Relation::Incoming))563+ _ => None,
593- {564+ };
565+ if let Some((label, icon)) = action {
594 let user_id = user.id.clone();566 let user_id = user.id.clone();
595 trailing.push(icon_button(567 trailing.push(icon_button(
596 format!("friend_action_{}", user.id),568 format!("friend_action_{}", user.id),
@@ -603,6 +575,15 @@ impl Yumush {
603 ));575 ));
604 }576 }
605 577
578+ self.user_row(palette, user, trailing).into_any_element()
579+ }
580+
581+ fn user_row(
582+ &self,
583+ palette: Palette,
584+ user: &User,
585+ trailing: impl IntoIterator<Item = AnyElement>,
586+ ) -> Div {
606 entry(587 entry(
607 palette,588 palette,
608 false,589 false,
@@ -615,23 +596,15 @@ impl Yumush {
615 user.username.clone(),596 user.username.clone(),
616 trailing,597 trailing,
617 )598 )
618- .into_any_element()
619 }599 }
620 600
621 fn incoming_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {601 fn incoming_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {
622 let accept_id = user.id.clone();602 let accept_id = user.id.clone();
623 let decline_id = user.id.clone();603 let decline_id = user.id.clone();
624 604
625- entry(605+ self.user_row(
626 palette,606 palette,
627- false,607+ user,
628- presence_avatar(
629- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
630- self.presence_of(&user.id),
631- px(20.),
632- palette,
633- ),
634- user.username.clone(),
635 [608 [
636 icon_button(609 icon_button(
637 format!("accept_friend_{}", user.id),610 format!("accept_friend_{}", user.id),
@@ -659,16 +632,9 @@ impl Yumush {
659 fn outgoing_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {632 fn outgoing_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {
660 let cancel_id = user.id.clone();633 let cancel_id = user.id.clone();
661 634
662- entry(635+ self.user_row(
663 palette,636 palette,
664- false,637+ user,
665- presence_avatar(
666- avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
667- self.presence_of(&user.id),
668- px(20.),
669- palette,
670- ),
671- user.username.clone(),
672 [icon_button(638 [icon_button(
673 format!("cancel_friend_{}", user.id),639 format!("cancel_friend_{}", user.id),
674 palette,640 palette,
@@ -814,7 +780,30 @@ impl Yumush {
814 }780 }
815 }781 }
816 782
817-pub(super) fn badge(palette: Palette, muted: bool, unread: Option<&Unread>) -> Option<AnyElement> {783+fn go_to_call(
784+ entity: &Entity<Yumush>,
785+ community: &Community,
786+) -> impl Fn(&mut Window, &mut App) + 'static {
787+ let direct = community.kind.is_direct();
788+ let go_id = community.id.clone();
789+
790+ entity_action(entity, move |yumush, window, cx| {
791+ yumush.go_to_community(go_id.clone(), direct, window, cx)
792+ })
793+}
794+
795+fn call_style<E: Styled>(element: E, palette: Palette) -> E {
796+ element
797+ .border_1()
798+ .border_color(palette.ok.opacity(0.35))
799+ .bg(palette.ok.opacity(0.08))
800+}
801+
802+pub(super) fn unread_badge(
803+ palette: Palette,
804+ muted: bool,
805+ unread: Option<&Unread>,
806+) -> Option<AnyElement> {
818 if muted {807 if muted {
819 return Some(808 return Some(
820 div()809 div()
@@ -866,16 +855,6 @@ fn mute_item(
866 }))855 }))
867 }856 }
868 857
869-fn direct_menu(
870- entity: &Entity<Yumush>,
871- community_id: String,
872- muted: bool,
873-) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static {
874- let entity = entity.clone();
875-
876- move |menu, _, _| mute_item(menu, &entity, community_id.clone(), muted)
877-}
878-
879 fn community_menu(858 fn community_menu(
880 entity: &Entity<Yumush>,859 entity: &Entity<Yumush>,
881 community_id: String,860 community_id: String,
crates/client/src/gui/voice_note.rsmodified+13 -19
@@ -15,7 +15,8 @@ use gpui_kit::{
15 use rtrb::{Consumer, RingBuffer};15 use rtrb::{Consumer, RingBuffer};
16 16
17 use super::{17 use super::{
18- Palette, Tooltip as _, Yumush, chat::VoiceState, clickable, media_view::time_text,18+ Palette, Tooltip as _, Yumush, chat::VoiceState, clickable,
19+ media_view::{time_text, upload_file},
19 notify_error, primary_button, text,20 notify_error, primary_button, text,
20 };21 };
21 use crate::{22 use crate::{
@@ -47,6 +48,12 @@ pub enum VoiceNote {
47 },48 },
48 }49 }
49 50
51+fn drain(consumer: &mut Consumer<f32>, samples: &mut Vec<f32>) {
52+ while let Ok(sample) = consumer.pop() {
53+ samples.push(sample);
54+ }
55+}
56+
50 pub fn bars(57 pub fn bars(
51 levels: &[f32],58 levels: &[f32],
52 progress: f32,59 progress: f32,
@@ -214,9 +221,7 @@ impl Yumush {
214 } = &mut self.chat.media.voice_note221 } = &mut self.chat.media.voice_note
215 {222 {
216 let start = samples.len();223 let start = samples.len();
217- while let Ok(sample) = consumer.pop() {224+ drain(consumer, samples);
218- samples.push(sample);
219- }
220 levels.push(voice_note::level(&samples[start..]));225 levels.push(voice_note::level(&samples[start..]));
221 if levels.len() > BARS {226 if levels.len() > BARS {
222 levels.remove(0);227 levels.remove(0);
@@ -239,9 +244,7 @@ impl Yumush {
239 else {244 else {
240 return;245 return;
241 };246 };
242- while let Ok(sample) = consumer.pop() {247+ drain(&mut consumer, &mut samples);
243- samples.push(sample);
244- }
245 let Some(community_id) = self.chat.selected_community_id.clone() else {248 let Some(community_id) = self.chat.selected_community_id.clone() else {
246 return;249 return;
247 };250 };
@@ -260,18 +263,9 @@ impl Yumush {
260 else {263 else {
261 return;264 return;
262 };265 };
263- let _ = this.update(cx, |yumush, cx| {266+ let attachment = match upload_file(&this, &network, &community_id, path, maximum, cx)
264- yumush.chat.media.uploading += 1;267+ .await
265- cx.notify();268+ {
266- });
267- let uploaded = network
268- .upload_attachment(&community_id, path, maximum)
269- .await;
270- let _ = this.update(cx, |yumush, cx| {
271- yumush.chat.media.uploading -= 1;
272- cx.notify();
273- });
274- let attachment = match uploaded {
275 Ok(attachment) => attachment,269 Ok(attachment) => attachment,
276 Err(error) => return notify_error(&this, cx, error),270 Err(error) => return notify_error(&this, cx, error),
277 };271 };
crates/client/src/gui/voice_settings.rsmodified+23 -28
@@ -37,13 +37,6 @@ pub(super) enum Side {
37 Output,37 Output,
38 }38 }
39 39
40-#[derive(Clone, Copy)]
41-pub(super) enum VoiceField {
42- Sensitivity,
43- InputVolume,
44- OutputVolume,
45-}
46-
47 #[derive(Clone, Copy, PartialEq, Eq)]40 #[derive(Clone, Copy, PartialEq, Eq)]
48 pub(super) enum MicTest {41 pub(super) enum MicTest {
49 Off,42 Off,
@@ -121,13 +114,13 @@ impl VoiceControls {
121 }114 }
122 }),115 }),
123 cx.subscribe(&sensitivity, |this, _, event: &SliderEvent, cx| {116 cx.subscribe(&sensitivity, |this, _, event: &SliderEvent, cx| {
124- this.slider_changed(VoiceField::Sensitivity, event, cx);117+ this.slider_changed(event, |voice, value| voice.sensitivity_db = value, cx);
125 }),118 }),
126 cx.subscribe(&input_volume, |this, _, event: &SliderEvent, cx| {119 cx.subscribe(&input_volume, |this, _, event: &SliderEvent, cx| {
127- this.slider_changed(VoiceField::InputVolume, event, cx);120+ this.slider_changed(event, |voice, value| voice.input_volume = value, cx);
128 }),121 }),
129 cx.subscribe(&output_volume, |this, _, event: &SliderEvent, cx| {122 cx.subscribe(&output_volume, |this, _, event: &SliderEvent, cx| {
130- this.slider_changed(VoiceField::OutputVolume, event, cx);123+ this.slider_changed(event, |voice, value| voice.output_volume = value, cx);
131 }),124 }),
132 ];125 ];
133 126
@@ -348,18 +341,16 @@ impl Yumush {
348 .child(content)341 .child(content)
349 }342 }
350 343
351- fn slider_changed(&mut self, field: VoiceField, event: &SliderEvent, cx: &mut Context<Self>) {344+ fn slider_changed(
345+ &mut self,
346+ event: &SliderEvent,
347+ set: fn(&mut VoiceSettings, f32),
348+ cx: &mut Context<Self>,
349+ ) {
352 let SliderEvent::Change(value) = event else {350 let SliderEvent::Change(value) = event else {
353 return;351 return;
354 };352 };
355- let value = value.start();353+ set(&mut self.settings.voice, value.start());
356- let voice = &mut self.settings.voice;
357-
358- match field {
359- VoiceField::Sensitivity => voice.sensitivity_db = value,
360- VoiceField::InputVolume => voice.input_volume = value,
361- VoiceField::OutputVolume => voice.output_volume = value,
362- }
363 self.commit_settings(cx);354 self.commit_settings(cx);
364 }355 }
365 356
@@ -398,18 +389,25 @@ impl Yumush {
398 && self.settings.voice.push_to_talk_key == key389 && self.settings.voice.push_to_talk_key == key
399 }390 }
400 391
392+ fn finish_capture(&mut self, key: String, cx: &mut Context<Self>) {
393+ self.voice.key = KeyCapture::Idle;
394+ self.settings.voice.push_to_talk_key = key;
395+ self.commit_settings(cx);
396+ cx.notify();
397+ }
398+
401 pub(super) fn voice_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context<Self>) {399 pub(super) fn voice_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context<Self>) {
402 let key = event.keystroke.key.clone();400 let key = event.keystroke.key.clone();
403 401
404 match self.voice.key {402 match self.voice.key {
405 KeyCapture::Waiting => {403 KeyCapture::Waiting => {
406 cx.stop_propagation();404 cx.stop_propagation();
407- self.voice.key = KeyCapture::Idle;405+ if key == "escape" {
408- if key != "escape" {406+ self.voice.key = KeyCapture::Idle;
409- self.settings.voice.push_to_talk_key = key;407+ cx.notify();
410- self.commit_settings(cx);408+ } else {
409+ self.finish_capture(key, cx);
411 }410 }
412- cx.notify();
413 }411 }
414 KeyCapture::Idle => {412 KeyCapture::Idle => {
415 if self.is_push_key(&key) {413 if self.is_push_key(&key) {
@@ -443,10 +441,7 @@ impl Yumush {
443 let Some((key, _)) = held.iter().find(|(_, down)| *down) else {441 let Some((key, _)) = held.iter().find(|(_, down)| *down) else {
444 return;442 return;
445 };443 };
446- self.voice.key = KeyCapture::Idle;444+ self.finish_capture(key.to_string(), cx);
447- self.settings.voice.push_to_talk_key = key.to_string();
448- self.commit_settings(cx);
449- cx.notify();
450 }445 }
451 KeyCapture::Idle => {446 KeyCapture::Idle => {
452 if let Some((_, down)) = held.iter().find(|(key, _)| self.is_push_key(key)) {447 if let Some((_, down)) = held.iter().find(|(key, _)| self.is_push_key(key)) {
crates/client/src/lib.rsmodified+6 -0
@@ -1,3 +1,5 @@
1+use std::path::PathBuf;
2+
1 use common::config::Config;3 use common::config::Config;
2 4
3 pub mod accounts;5 pub mod accounts;
@@ -13,6 +15,10 @@ pub mod voice;
13 15
14 pub const NAME: &str = "Yumush";16 pub const NAME: &str = "Yumush";
15 17
18+pub fn config_file(name: &str) -> Option<PathBuf> {
19+ dirs::config_dir().map(|dir| dir.join("yumush").join(name))
20+}
21+
16 const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!(22 const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!(
17 env!("CARGO_MANIFEST_DIR"),23 env!("CARGO_MANIFEST_DIR"),
18 "/../../configs/client_config.toml"24 "/../../configs/client_config.toml"
crates/client/src/media/mod.rsmodified+8 -8
@@ -116,13 +116,18 @@ impl Info {
116 }116 }
117 }117 }
118 118
119-pub fn probe(path: &Path) -> Result<Info, MediaError> {119+fn open_tracks(path: &Path) -> Result<(Reader, Tracks, Info), MediaError> {
120 let reader = Reader::open(path)?;120 let reader = Reader::open(path)?;
121 let tracks = Tracks::find(&reader);121 let tracks = Tracks::find(&reader);
122 if tracks.video.is_none() && tracks.audio.is_none() {122 if tracks.video.is_none() && tracks.audio.is_none() {
123 return Err(MediaError::Unsupported);123 return Err(MediaError::Unsupported);
124 }124 }
125- Ok(Info::of(path, &reader, &tracks))125+ let info = Info::of(path, &reader, &tracks);
126+ Ok((reader, tracks, info))
127+}
128+
129+pub fn probe(path: &Path) -> Result<Info, MediaError> {
130+ open_tracks(path).map(|(_, _, info)| info)
126 }131 }
127 132
128 const FLAC_TAIL: u64 = 256 * 1024;133 const FLAC_TAIL: u64 = 256 * 1024;
@@ -167,12 +172,7 @@ pub struct Player {
167 172
168 impl Player {173 impl Player {
169 pub fn open(path: &Path, choice: Choice) -> Result<Player, MediaError> {174 pub fn open(path: &Path, choice: Choice) -> Result<Player, MediaError> {
170- let reader = Reader::open(path)?;175+ let (reader, tracks, info) = open_tracks(path)?;
171- let tracks = Tracks::find(&reader);
172- if tracks.video.is_none() && tracks.audio.is_none() {
173- return Err(MediaError::Unsupported);
174- }
175- let info = Info::of(path, &reader, &tracks);
176 let (producer, consumer) = RingBuffer::new(RING_SAMPLES);176 let (producer, consumer) = RingBuffer::new(RING_SAMPLES);
177 let playback: Playback = Arc::new(Mutex::new(consumer));177 let playback: Playback = Arc::new(Mutex::new(consumer));
178 let audio = if tracks.audio.is_some() {178 let audio = if tracks.audio.is_some() {
crates/client/src/media/voice_note.rsmodified+5 -1
@@ -103,9 +103,13 @@ pub fn encode(samples: &[f32]) -> Option<Vec<u8>> {
103 Some(muxer.into_inner())103 Some(muxer.into_inner())
104 }104 }
105 105
106+pub fn media_cache_dir() -> Option<PathBuf> {
107+ Some(dirs::cache_dir()?.join("yumush").join("media"))
108+}
109+
106 pub fn save(samples: &[f32]) -> Option<PathBuf> {110 pub fn save(samples: &[f32]) -> Option<PathBuf> {
107 let bytes = encode(samples)?;111 let bytes = encode(samples)?;
108- let directory = dirs::cache_dir()?.join("yumush").join("media");112+ let directory = media_cache_dir()?;
109 std::fs::create_dir_all(&directory).ok()?;113 std::fs::create_dir_all(&directory).ok()?;
110 let path = directory.join(format!("voice-{}.ogg", now_ms()));114 let path = directory.join(format!("voice-{}.ogg", now_ms()));
111 std::fs::write(&path, bytes).ok()?;115 std::fs::write(&path, bytes).ok()?;
crates/client/src/mutes.rsmodified+5 -10
@@ -1,21 +1,16 @@
1-use std::{1+use std::{collections::HashSet, fs, path::Path};
2- collections::HashSet,
3- fs,
4- path::{Path, PathBuf},
5-};
6 2
7 use tracing::warn;3 use tracing::warn;
8 4
9-fn path() -> Option<PathBuf> {5+use crate::config_file;
10- dirs::config_dir().map(|dir| dir.join("yumush").join("mutes"))
11-}
12 6
13 fn prefix(account_user_id: &str) -> String {7 fn prefix(account_user_id: &str) -> String {
14 format!("{account_user_id}\t")8 format!("{account_user_id}\t")
15 }9 }
16 10
17 pub fn load(account_user_id: &str) -> HashSet<String> {11 pub fn load(account_user_id: &str) -> HashSet<String> {
18- let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else {12+ let Some(content) = config_file("mutes").and_then(|path| fs::read_to_string(path).ok())
13+ else {
19 return HashSet::new();14 return HashSet::new();
20 };15 };
21 let prefix = prefix(account_user_id);16 let prefix = prefix(account_user_id);
@@ -28,7 +23,7 @@ pub fn load(account_user_id: &str) -> HashSet<String> {
28 }23 }
29 24
30 pub fn save(account_user_id: &str, muted: &HashSet<String>) {25 pub fn save(account_user_id: &str, muted: &HashSet<String>) {
31- let Some(path) = path() else {26+ let Some(path) = config_file("mutes") else {
32 return;27 return;
33 };28 };
34 let prefix = prefix(account_user_id);29 let prefix = prefix(account_user_id);
crates/client/src/network.rsmodified+98 -177
@@ -12,14 +12,14 @@ use common::{
12 error::Error,12 error::Error,
13 event::Event,13 event::Event,
14 model::{14 model::{
15- Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, Community,15+ Account, AdminLogEntry, Attachment, AttachmentInfo, BackupInfo, Ban, BanScope, Community,
16 CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,16 CommunitySummary, CommunityUsage, DayStat, Friends, Invitation, InviteCode, LogEntry,
17 Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,17 Member, Message, MessageHit, Overview, Presence, Rank, Report, ReportStatus, Role,
18 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,18 ServerBan, ServerSettings, SessionInfo, Unread, Usage, User, VoiceRoom,
19 },19 },
20 network::{20 network::{
21 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,21 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,
22- receive_download_status, receive_event, send_download_request, send_encoded, send_request,22+ receive_download_status, receive_event, send_encoded, send_request,
23 send_stream_kind, send_upload_header,23 send_stream_kind, send_upload_header,
24 },24 },
25 request::{DownloadRequest, Request, UploadHeader},25 request::{DownloadRequest, Request, UploadHeader},
@@ -112,15 +112,29 @@ pub struct NetworkHandle {
112 }112 }
113 113
114 impl NetworkHandle {114 impl NetworkHandle {
115- pub async fn request(&self, request: Request) -> Result<Response, Error> {115+ async fn ask<T>(
116+ &self,
117+ build: impl FnOnce(oneshot::Sender<Result<T, Error>>) -> Command,
118+ ) -> Result<T, Error> {
116 let (reply, response) = oneshot::channel();119 let (reply, response) = oneshot::channel();
117 120
118 self.command_sender121 self.command_sender
119- .send(Command::Request { request, reply })122+ .send(build(reply))
120 .await123 .await
121 .map_err(|_| Error::ChannelClosed)?;124 .map_err(|_| Error::ChannelClosed)?;
122 125
123- match response.await.map_err(|_| Error::ChannelClosed)?? {126+ response.await.map_err(|_| Error::ChannelClosed)?
127+ }
128+
129+ fn with_voice<T>(&self, f: impl FnOnce(&Voice) -> T) -> Option<T> {
130+ self.voice.lock().unwrap().as_ref().map(f)
131+ }
132+
133+ async fn request(&self, request: Request) -> Result<Response, Error> {
134+ match self
135+ .ask(|reply| Command::Request { request, reply })
136+ .await?
137+ {
124 Response::Error(error) => Err(error),138 Response::Error(error) => Err(error),
125 response => Ok(response),139 response => Ok(response),
126 }140 }
@@ -131,18 +145,11 @@ impl NetworkHandle {
131 Response::Session { user, token } => (user, token),145 Response::Session { user, token } => (user, token),
132 _ => return Err(Error::Server),146 _ => return Err(Error::Server),
133 };147 };
134- let _ = self.set_device(&device_name()).await;148+ let _ = self.done(Request::SetDevice { name: device_name() }).await;
135 149
136 Ok(session)150 Ok(session)
137 }151 }
138 152
139- async fn set_device(&self, name: &str) -> Result<(), Error> {
140- self.done(Request::SetDevice {
141- name: name.to_string(),
142- })
143- .await
144- }
145-
146 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Error> {153 pub async fn sessions(&self, user_id: &str) -> Result<Vec<SessionInfo>, Error> {
147 match self154 match self
148 .request(Request::Sessions {155 .request(Request::Sessions {
@@ -186,10 +193,7 @@ impl NetworkHandle {
186 }193 }
187 194
188 pub async fn detach(&self) -> Result<(), Error> {195 pub async fn detach(&self) -> Result<(), Error> {
189- match self.request(Request::Detach).await? {196+ self.done(Request::Detach).await
190- Response::Done => Ok(()),
191- _ => Err(Error::Server),
192- }
193 }197 }
194 198
195 pub async fn register(199 pub async fn register(
@@ -221,10 +225,7 @@ impl NetworkHandle {
221 }225 }
222 226
223 pub async fn logout(&self) -> Result<(), Error> {227 pub async fn logout(&self) -> Result<(), Error> {
224- match self.request(Request::Logout).await? {228+ self.done(Request::Logout).await
225- Response::Done => Ok(()),
226- _ => Err(Error::Server),
227- }
228 }229 }
229 230
230 pub async fn update_user(&self, username: &str) -> Result<User, Error> {231 pub async fn update_user(&self, username: &str) -> Result<User, Error> {
@@ -280,14 +281,14 @@ impl NetworkHandle {
280 &self,281 &self,
281 user_id: &str,282 user_id: &str,
282 reason: Option<&str>,283 reason: Option<&str>,
283- ip: bool,284+ scope: BanScope,
284 ) -> Result<(), Error> {285 ) -> Result<(), Error> {
285 validate_reason(reason)?;286 validate_reason(reason)?;
286 287
287 self.done(Request::BanUser {288 self.done(Request::BanUser {
288 user_id: user_id.to_string(),289 user_id: user_id.to_string(),
289 reason: reason.map(str::to_string),290 reason: reason.map(str::to_string),
290- ip,291+ scope,
291 })292 })
292 .await293 .await
293 }294 }
@@ -520,15 +521,10 @@ impl NetworkHandle {
520 }521 }
521 522
522 pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> {523 pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> {
523- match self524+ self.done(Request::LeaveCommunity {
524- .request(Request::LeaveCommunity {525+ community_id: community_id.to_string(),
525- community_id: community_id.to_string(),526+ })
526- })527+ .await
527- .await?
528- {
529- Response::Done => Ok(()),
530- _ => Err(Error::Server),
531- }
532 }528 }
533 529
534 pub async fn communities(&self) -> Result<Vec<Community>, Error> {530 pub async fn communities(&self) -> Result<Vec<Community>, Error> {
@@ -557,17 +553,12 @@ impl NetworkHandle {
557 reason: Option<&str>,553 reason: Option<&str>,
558 ) -> Result<(), Error> {554 ) -> Result<(), Error> {
559 validate_reason(reason)?;555 validate_reason(reason)?;
560- match self556+ self.done(Request::Kick {
561- .request(Request::Kick {557+ community_id: community_id.to_string(),
562- community_id: community_id.to_string(),558+ user_id: user_id.to_string(),
563- user_id: user_id.to_string(),559+ reason: reason.map(str::to_string),
564- reason: reason.map(str::to_string),560+ })
565- })561+ .await
566- .await?
567- {
568- Response::Done => Ok(()),
569- _ => Err(Error::Server),
570- }
571 }562 }
572 563
573 pub async fn ban(564 pub async fn ban(
@@ -577,30 +568,20 @@ impl NetworkHandle {
577 reason: Option<&str>,568 reason: Option<&str>,
578 ) -> Result<(), Error> {569 ) -> Result<(), Error> {
579 validate_reason(reason)?;570 validate_reason(reason)?;
580- match self571+ self.done(Request::Ban {
581- .request(Request::Ban {572+ community_id: community_id.to_string(),
582- community_id: community_id.to_string(),573+ user_id: user_id.to_string(),
583- user_id: user_id.to_string(),574+ reason: reason.map(str::to_string),
584- reason: reason.map(str::to_string),575+ })
585- })576+ .await
586- .await?
587- {
588- Response::Done => Ok(()),
589- _ => Err(Error::Server),
590- }
591 }577 }
592 578
593 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Error> {579 pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Error> {
594- match self580+ self.done(Request::Unban {
595- .request(Request::Unban {581+ community_id: community_id.to_string(),
596- community_id: community_id.to_string(),582+ user_id: user_id.to_string(),
597- user_id: user_id.to_string(),583+ })
598- })584+ .await
599- .await?
600- {
601- Response::Done => Ok(()),
602- _ => Err(Error::Server),
603- }
604 }585 }
605 586
606 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Error> {587 pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Error> {
@@ -633,17 +614,12 @@ impl NetworkHandle {
633 user_id: &str,614 user_id: &str,
634 rank: Rank,615 rank: Rank,
635 ) -> Result<(), Error> {616 ) -> Result<(), Error> {
636- match self617+ self.done(Request::SetRank {
637- .request(Request::SetRank {618+ community_id: community_id.to_string(),
638- community_id: community_id.to_string(),619+ user_id: user_id.to_string(),
639- user_id: user_id.to_string(),620+ rank,
640- rank,621+ })
641- })622+ .await
642- .await?
643- {
644- Response::Done => Ok(()),
645- _ => Err(Error::Server),
646- }
647 }623 }
648 624
649 pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> {625 pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> {
@@ -1040,19 +1016,13 @@ impl NetworkHandle {
1040 path: PathBuf,1016 path: PathBuf,
1041 maximum: Option<u64>,1017 maximum: Option<u64>,
1042 ) -> Result<Attachment, Error> {1018 ) -> Result<Attachment, Error> {
1043- let (reply, response) = oneshot::channel();1019+ self.ask(|reply| Command::Upload {
1044-1020+ community_id: community_id.to_string(),
1045- self.command_sender1021+ path,
1046- .send(Command::Upload {1022+ maximum,
1047- community_id: community_id.to_string(),1023+ reply,
1048- path,1024+ })
1049- maximum,1025+ .await
1050- reply,
1051- })
1052- .await
1053- .map_err(|_| Error::ChannelClosed)?;
1054-
1055- response.await.map_err(|_| Error::ChannelClosed)?
1056 }1026 }
1057 1027
1058 pub async fn download_attachment(1028 pub async fn download_attachment(
@@ -1060,33 +1030,21 @@ impl NetworkHandle {
1060 attachment_id: &str,1030 attachment_id: &str,
1061 thumbnail: bool,1031 thumbnail: bool,
1062 ) -> Result<Vec<u8>, Error> {1032 ) -> Result<Vec<u8>, Error> {
1063- let (reply, response) = oneshot::channel();1033+ self.ask(|reply| Command::Download {
1064-1034+ attachment_id: attachment_id.to_string(),
1065- self.command_sender1035+ thumbnail,
1066- .send(Command::Download {1036+ reply,
1067- attachment_id: attachment_id.to_string(),1037+ })
1068- thumbnail,1038+ .await
1069- reply,
1070- })
1071- .await
1072- .map_err(|_| Error::ChannelClosed)?;
1073-
1074- response.await.map_err(|_| Error::ChannelClosed)?
1075 }1039 }
1076 1040
1077 pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> {1041 pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Error> {
1078- let (reply, response) = oneshot::channel();1042+ self.ask(|reply| Command::BackupDownload {
1079-1043+ name: name.to_string(),
1080- self.command_sender1044+ path,
1081- .send(Command::BackupDownload {1045+ reply,
1082- name: name.to_string(),1046+ })
1083- path,1047+ .await
1084- reply,
1085- })
1086- .await
1087- .map_err(|_| Error::ChannelClosed)?;
1088-
1089- response.await.map_err(|_| Error::ChannelClosed)?
1090 }1048 }
1091 1049
1092 pub async fn read_messages(1050 pub async fn read_messages(
@@ -1114,16 +1072,11 @@ impl NetworkHandle {
1114 }1072 }
1115 1073
1116 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> {1074 pub async fn mark_read(&self, community_id: &str, message_id: &str) -> Result<(), Error> {
1117- match self1075+ self.done(Request::MarkRead {
1118- .request(Request::MarkRead {1076+ community_id: community_id.to_string(),
1119- community_id: community_id.to_string(),1077+ message_id: message_id.to_string(),
1120- message_id: message_id.to_string(),1078+ })
1121- })1079+ .await
1122- .await?
1123- {
1124- Response::Done => Ok(()),
1125- _ => Err(Error::Server),
1126- }
1127 }1080 }
1128 1081
1129 pub async fn update_status(&self, status: &str) -> Result<User, Error> {1082 pub async fn update_status(&self, status: &str) -> Result<User, Error> {
@@ -1202,22 +1155,14 @@ impl NetworkHandle {
1202 }1155 }
1203 1156
1204 pub async fn typing(&self, community_id: &str) -> Result<(), Error> {1157 pub async fn typing(&self, community_id: &str) -> Result<(), Error> {
1205- match self1158+ self.done(Request::Typing {
1206- .request(Request::Typing {1159+ community_id: community_id.to_string(),
1207- community_id: community_id.to_string(),1160+ })
1208- })1161+ .await
1209- .await?
1210- {
1211- Response::Done => Ok(()),
1212- _ => Err(Error::Server),
1213- }
1214 }1162 }
1215 1163
1216 pub async fn leave_voice(&self) -> Result<(), Error> {1164 pub async fn leave_voice(&self) -> Result<(), Error> {
1217- match self.request(Request::LeaveVoice).await? {1165+ self.done(Request::LeaveVoice).await
1218- Response::Done => Ok(()),
1219- _ => Err(Error::Server),
1220- }
1221 }1166 }
1222 1167
1223 pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> {1168 pub async fn read_community(&self, community_id: &str) -> Result<Community, Error> {
@@ -1252,35 +1197,22 @@ impl NetworkHandle {
1252 }1197 }
1253 1198
1254 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> {1199 pub async fn set_ghost(&self, enabled: bool) -> Result<(), Error> {
1255- match self.request(Request::SetGhost { enabled }).await? {1200+ self.done(Request::SetGhost { enabled }).await
1256- Response::Done => Ok(()),
1257- _ => Err(Error::Server),
1258- }
1259 }1201 }
1260 1202
1261 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Error> {1203 pub async fn kick_from_voice(&self, user_id: &str) -> Result<(), Error> {
1262- match self1204+ self.done(Request::KickFromVoice {
1263- .request(Request::KickFromVoice {1205+ user_id: user_id.to_string(),
1264- user_id: user_id.to_string(),1206+ })
1265- })1207+ .await
1266- .await?
1267- {
1268- Response::Done => Ok(()),
1269- _ => Err(Error::Server),
1270- }
1271 }1208 }
1272 1209
1273 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Error> {1210 pub async fn server_mute(&self, user_id: &str, muted: bool) -> Result<(), Error> {
1274- match self1211+ self.done(Request::ServerMute {
1275- .request(Request::ServerMute {1212+ user_id: user_id.to_string(),
1276- user_id: user_id.to_string(),1213+ muted,
1277- muted,1214+ })
1278- })1215+ .await
1279- .await?
1280- {
1281- Response::Done => Ok(()),
1282- _ => Err(Error::Server),
1283- }
1284 }1216 }
1285 1217
1286 pub async fn set_community_voice(1218 pub async fn set_community_voice(
@@ -1336,39 +1268,28 @@ impl NetworkHandle {
1336 }1268 }
1337 1269
1338 pub fn voice_level_db(&self) -> Option<f32> {1270 pub fn voice_level_db(&self) -> Option<f32> {
1339- let live = self.voice.lock().unwrap().as_ref().map(Voice::level_db);1271+ self.with_voice(Voice::level_db)
1340- live.or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db))1272+ .or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db))
1341 }1273 }
1342 1274
1343 pub fn voice_sample(&self) -> Option<VoiceSample> {1275 pub fn voice_sample(&self) -> Option<VoiceSample> {
1344- self.voice.lock().unwrap().as_ref().map(Voice::sample)1276+ self.with_voice(Voice::sample)
1345 }1277 }
1346 1278
1347 pub fn set_talking(&self, talking: bool) {1279 pub fn set_talking(&self, talking: bool) {
1348- if let Some(voice) = self.voice.lock().unwrap().as_ref() {1280+ self.with_voice(|voice| voice.set_talking(talking));
1349- voice.set_talking(talking);
1350- }
1351 }1281 }
1352 1282
1353 pub fn set_muted(&self, muted: bool) {1283 pub fn set_muted(&self, muted: bool) {
1354- if let Some(voice) = self.voice.lock().unwrap().as_ref() {1284+ self.with_voice(|voice| voice.set_muted(muted));
1355- voice.set_muted(muted);
1356- }
1357 }1285 }
1358 1286
1359 pub fn set_deafened(&self, deafened: bool) {1287 pub fn set_deafened(&self, deafened: bool) {
1360- if let Some(voice) = self.voice.lock().unwrap().as_ref() {1288+ self.with_voice(|voice| voice.set_deafened(deafened));
1361- voice.set_deafened(deafened);
1362- }
1363 }1289 }
1364 1290
1365 pub fn speaking(&self) -> Vec<String> {1291 pub fn speaking(&self) -> Vec<String> {
1366- self.voice1292+ self.with_voice(Voice::speaking).unwrap_or_default()
1367- .lock()
1368- .unwrap()
1369- .as_ref()
1370- .map(Voice::speaking)
1371- .unwrap_or_default()
1372 }1293 }
1373 }1294 }
1374 1295
@@ -1629,7 +1550,7 @@ async fn download(
1629 attachment_id: attachment_id.to_string(),1550 attachment_id: attachment_id.to_string(),
1630 thumbnail,1551 thumbnail,
1631 };1552 };
1632- send_download_request(&request, &mut send_stream).await?;1553+ send_encoded(&request, &mut send_stream).await?;
1633 send_stream.finish()?;1554 send_stream.finish()?;
1634 1555
1635 match receive_download_status(&mut receive_stream).await? {1556 match receive_download_status(&mut receive_stream).await? {
crates/client/src/settings.rsmodified+51 -74
@@ -1,6 +1,6 @@
1-use std::{fmt::Display, fs, ops::RangeInclusive, path::PathBuf};1+use std::{fmt::Display, fs, ops::RangeInclusive};
2 2
3-use common::config::Config;3+use common::{config::Config, string_enum};
4 use gpui_kit::{4 use gpui_kit::{
5 App, Global, Pixels,5 App, Global, Pixels,
6 component::{Theme, ThemeMode},6 component::{Theme, ThemeMode},
@@ -8,28 +8,32 @@ use gpui_kit::{
8 };8 };
9 use tracing::warn;9 use tracing::warn;
10 10
11-use crate::voice::audio::Choice;11+use crate::{config_file, voice::audio::Choice};
12 12
13 pub const SENSITIVITY_DB: RangeInclusive<f32> = -80.0..=0.0;13 pub const SENSITIVITY_DB: RangeInclusive<f32> = -80.0..=0.0;
14 pub const VOLUME: RangeInclusive<f32> = 0.0..=200.0;14 pub const VOLUME: RangeInclusive<f32> = 0.0..=200.0;
15 15
16-#[derive(Debug, Clone, Copy, PartialEq, Eq)]16+string_enum! {
17-pub enum ThemeChoice {17+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18- System,18+ ThemeChoice {
19- Light,19+ System => "system",
20- Dark,20+ Light => "light",
21- Black,21+ Dark => "dark",
22+ Black => "black",
23+ }
22 }24 }
23 25
24 pub struct Look(pub ThemeChoice);26 pub struct Look(pub ThemeChoice);
25 27
26 impl Global for Look {}28 impl Global for Look {}
27 29
28-#[derive(Debug, Clone, Copy, PartialEq, Eq)]30+string_enum! {
29-pub enum FontSize {31+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
30- Small,32+ FontSize {
31- Medium,33+ Small => "small",
32- Large,34+ Medium => "medium",
35+ Large => "large",
36+ }
33 }37 }
34 38
35 pub struct Scale(pub FontSize);39 pub struct Scale(pub FontSize);
@@ -37,20 +41,14 @@ pub struct Scale(pub FontSize);
37 impl Global for Scale {}41 impl Global for Scale {}
38 42
39 impl FontSize {43 impl FontSize {
40- const ALL: [Self; 3] = [FontSize::Small, FontSize::Medium, FontSize::Large];44+ pub fn label(self) -> &'static str {
41-
42- fn name(self) -> &'static str {
43 match self {45 match self {
44- FontSize::Small => "small",46+ FontSize::Small => "Small",
45- FontSize::Medium => "medium",47+ FontSize::Medium => "Medium",
46- FontSize::Large => "large",48+ FontSize::Large => "Large",
47 }49 }
48 }50 }
49 51
50- fn parse(value: &str) -> Option<Self> {
51- Self::ALL.into_iter().find(|size| size.name() == value)
52- }
53-
54 pub fn pixels(self) -> Pixels {52 pub fn pixels(self) -> Pixels {
55 match self {53 match self {
56 FontSize::Small => px(13.),54 FontSize::Small => px(13.),
@@ -61,37 +59,30 @@ impl FontSize {
61 }59 }
62 60
63 impl ThemeChoice {61 impl ThemeChoice {
64- const ALL: [Self; 4] = [62+ pub fn label(self) -> &'static str {
65- ThemeChoice::System,
66- ThemeChoice::Light,
67- ThemeChoice::Dark,
68- ThemeChoice::Black,
69- ];
70-
71- fn name(self) -> &'static str {
72 match self {63 match self {
73- ThemeChoice::System => "system",64+ ThemeChoice::System => "System",
74- ThemeChoice::Light => "light",65+ ThemeChoice::Light => "Light",
75- ThemeChoice::Dark => "dark",66+ ThemeChoice::Dark => "Dark",
76- ThemeChoice::Black => "black",67+ ThemeChoice::Black => "Black",
77 }68 }
78 }69 }
79-
80- fn parse(value: &str) -> Option<Self> {
81- Self::ALL.into_iter().find(|choice| choice.name() == value)
82- }
83 }70 }
84 71
85-#[derive(Debug, Clone, Copy, PartialEq, Eq)]72+string_enum! {
86-pub enum Activation {73+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
87- VoiceActivity,74+ Activation {
88- PushToTalk,75+ VoiceActivity => "voice_activity",
76+ PushToTalk => "push_to_talk",
77+ }
89 }78 }
90 79
91-#[derive(Debug, Clone, Copy, PartialEq, Eq)]80+string_enum! {
92-pub enum Profile {81+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
93- Voice,82+ Profile {
94- Music,83+ Voice => "voice",
84+ Music => "music",
85+ }
95 }86 }
96 87
97 #[derive(Debug, Clone, PartialEq)]88 #[derive(Debug, Clone, PartialEq)]
@@ -127,12 +118,8 @@ pub struct Settings {
127 pub close_to_tray: bool,118 pub close_to_tray: bool,
128 }119 }
129 120
130-fn path() -> Option<PathBuf> {
131- dirs::config_dir().map(|dir| dir.join("yumush").join("settings"))
132-}
133-
134 pub fn load() -> Settings {121 pub fn load() -> Settings {
135- let config = path()122+ let config = config_file("settings")
136 .and_then(|path| fs::read_to_string(path).ok())123 .and_then(|path| fs::read_to_string(path).ok())
137 .and_then(|content| Config::parse(&content).ok());124 .and_then(|content| Config::parse(&content).ok());
138 let text = |key: &str| {125 let text = |key: &str| {
@@ -161,14 +148,12 @@ pub fn load() -> Settings {
161 input: text("voice.input"),148 input: text("voice.input"),
162 output: text("voice.output"),149 output: text("voice.output"),
163 },150 },
164- activation: match text("voice.activation").as_deref() {151+ activation: text("voice.activation")
165- Some("push_to_talk") => Activation::PushToTalk,152+ .and_then(|value| Activation::parse(&value))
166- _ => Activation::VoiceActivity,153+ .unwrap_or(Activation::VoiceActivity),
167- },154+ profile: text("voice.profile")
168- profile: match text("voice.profile").as_deref() {155+ .and_then(|value| Profile::parse(&value))
169- Some("music") => Profile::Music,156+ .unwrap_or(Profile::Voice),
170- _ => Profile::Voice,
171- },
172 push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(),157 push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(),
173 };158 };
174 159
@@ -189,23 +174,15 @@ fn line(key: &str, value: impl Display) -> String {
189 }174 }
190 175
191 pub fn save(settings: &Settings) {176 pub fn save(settings: &Settings) {
192- let Some(path) = path() else {177+ let Some(path) = config_file("settings") else {
193 return;178 return;
194 };179 };
195 180
196 let voice = &settings.voice;181 let voice = &settings.voice;
197- let activation = match voice.activation {
198- Activation::VoiceActivity => "voice_activity",
199- Activation::PushToTalk => "push_to_talk",
200- };
201- let profile = match voice.profile {
202- Profile::Voice => "voice",
203- Profile::Music => "music",
204- };
205 let key = voice.push_to_talk_key.as_str();182 let key = voice.push_to_talk_key.as_str();
206 let content = [183 let content = [
207- line("theme", settings.theme.name()),184+ line("theme", settings.theme.as_str()),
208- line("font_size", settings.font_size.name()),185+ line("font_size", settings.font_size.as_str()),
209 line("close_to_tray", settings.close_to_tray),186 line("close_to_tray", settings.close_to_tray),
210 line("voice.sensitivity", voice.sensitivity_db),187 line("voice.sensitivity", voice.sensitivity_db),
211 line("voice.input_volume", voice.input_volume),188 line("voice.input_volume", voice.input_volume),
@@ -218,8 +195,8 @@ pub fn save(settings: &Settings) {
218 "voice.output",195 "voice.output",
219 voice.choice.output.as_deref().unwrap_or_default(),196 voice.choice.output.as_deref().unwrap_or_default(),
220 ),197 ),
221- line("voice.activation", activation),198+ line("voice.activation", voice.activation.as_str()),
222- line("voice.profile", profile),199+ line("voice.profile", voice.profile.as_str()),
223 line("voice.push_to_talk", key),200 line("voice.push_to_talk", key),
224 ]201 ]
225 .concat();202 .concat();
crates/client/src/tray.rsmodified+18 -13
@@ -136,19 +136,24 @@ impl ksni::Tray for Tray {
136 fn menu(&self) -> Vec<ksni::MenuItem<Self>> {136 fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
137 use ksni::menu::StandardItem;137 use ksni::menu::StandardItem;
138 138
139- [("Show", TrayAction::Show), ("Quit", TrayAction::Quit)]139+ vec![
140- .into_iter()140+ StandardItem {
141- .map(|(label, action)| {141+ label: "Show".to_string(),
142- StandardItem {142+ activate: Box::new(|tray: &mut Self| {
143- label: label.to_string(),143+ let _ = tray.sender.send(TrayAction::Show);
144- activate: Box::new(move |tray: &mut Self| {144+ }),
145- let _ = tray.sender.send(action);145+ ..Default::default()
146- }),146+ }
147- ..Default::default()147+ .into(),
148- }148+ StandardItem {
149- .into()149+ label: "Quit".to_string(),
150- })150+ activate: Box::new(|tray: &mut Self| {
151- .collect()151+ let _ = tray.sender.send(TrayAction::Quit);
152+ }),
153+ ..Default::default()
154+ }
155+ .into(),
156+ ]
152 }157 }
153 }158 }
154 159
crates/client/src/voice/audio.rsmodified+21 -7
@@ -54,13 +54,27 @@ pub enum Audio {
54 Device(backend::Backend),54 Device(backend::Backend),
55 }55 }
56 56
57-pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Audio {57+enum Mode {
58+ Off,
59+ Tone,
60+ Device,
61+}
62+
63+fn mode() -> Mode {
58 match std::env::var("YUMUSH_AUDIO").as_deref() {64 match std::env::var("YUMUSH_AUDIO").as_deref() {
59- Ok("off") => Audio::Silent,65+ Ok("off") => Mode::Off,
60- Ok("tone") => Audio::Tone(Worker::spawn("voice-tone", move |stop| {66+ Ok("tone") => Mode::Tone,
67+ _ => Mode::Device,
68+ }
69+}
70+
71+pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Audio {
72+ match mode() {
73+ Mode::Off => Audio::Silent,
74+ Mode::Tone => Audio::Tone(Worker::spawn("voice-tone", move |stop| {
61 tone(capture.as_ref(), &playback, stop)75 tone(capture.as_ref(), &playback, stop)
62 })),76 })),
63- _ => device(capture, playback, choice),77+ Mode::Device => device(capture, playback, choice),
64 }78 }
65 }79 }
66 80
@@ -76,9 +90,9 @@ fn device(_: Option<Capture>, _: Playback, _: Choice) -> Audio {
76 90
77 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]91 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
78 pub fn devices() -> Devices {92 pub fn devices() -> Devices {
79- match std::env::var("YUMUSH_AUDIO").as_deref() {93+ match mode() {
80- Ok("off" | "tone") => Devices::default(),94+ Mode::Off | Mode::Tone => Devices::default(),
81- _ => backend::devices(),95+ Mode::Device => backend::devices(),
82 }96 }
83 }97 }
84 98
crates/client/src/voice/audio/pipewire.rsmodified+4 -3
@@ -250,9 +250,10 @@ fn run(
250 return;250 return;
251 };251 };
252 let chunks = bytes.as_chunks_mut::<BYTES_PER_FRAME>().0;252 let chunks = bytes.as_chunks_mut::<BYTES_PER_FRAME>().0;
253- let frames = match requested {253+ let frames = if requested == 0 {
254- 0 => chunks.len(),254+ chunks.len()
255- requested => requested.min(chunks.len()),255+ } else {
256+ requested.min(chunks.len())
256 };257 };
257 play(&playback, frames, |index, sample| {258 play(&playback, frames, |index, sample| {
258 chunks[index] = stereo_bytes(sample);259 chunks[index] = stereo_bytes(sample);
crates/client/src/voice/engine.rsmodified+25 -35
@@ -11,7 +11,7 @@ use common::{
11 };11 };
12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};
13 13
14-use crate::settings::Profile;14+use crate::settings::{Activation, Profile};
15 15
16 pub const SILENT_DB: f32 = -100.0;16 pub const SILENT_DB: f32 = -100.0;
17 const JITTER_CAPACITY: usize = 10;17 const JITTER_CAPACITY: usize = 10;
@@ -45,13 +45,20 @@ fn db(amplitude: f32) -> f32 {
45 (20.0 * amplitude.log10()).max(SILENT_DB)45 (20.0 * amplitude.log10()).max(SILENT_DB)
46 }46 }
47 47
48+fn bitrate(profile: Profile) -> u32 {
49+ match profile {
50+ Profile::Voice => VOICE_BITRATE as u32,
51+ Profile::Music => MUSIC_BITRATE as u32,
52+ }
53+}
54+
48 fn encoder(profile: Profile) -> Encoder {55 fn encoder(profile: Profile) -> Encoder {
49- let (application, bitrate) = match profile {56+ let application = match profile {
50- Profile::Voice => (Application::Voip, VOICE_BITRATE),57+ Profile::Voice => Application::Voip,
51- Profile::Music => (Application::Audio, MUSIC_BITRATE),58+ Profile::Music => Application::Audio,
52 };59 };
53 let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder");60 let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder");
54- encoder.set_bitrate(bitrate as u32);61+ encoder.set_bitrate(bitrate(profile));
55 encoder.set_bandwidth(Some(Bandwidth::Full));62 encoder.set_bandwidth(Some(Bandwidth::Full));
56 encoder.set_analysis(true);63 encoder.set_analysis(true);
57 encoder.set_inband_fec(true);64 encoder.set_inband_fec(true);
@@ -166,7 +173,7 @@ pub struct Engine {
166 gate: f32,173 gate: f32,
167 input_gain: f32,174 input_gain: f32,
168 output_gain: f32,175 output_gain: f32,
169- push_to_talk: bool,176+ activation: Activation,
170 talking: bool,177 talking: bool,
171 hangover: u32,178 hangover: u32,
172 sending: bool,179 sending: bool,
@@ -197,7 +204,7 @@ impl Engine {
197 gate: 0.0,204 gate: 0.0,
198 input_gain: 1.0,205 input_gain: 1.0,
199 output_gain: 1.0,206 output_gain: 1.0,
200- push_to_talk: false,207+ activation: Activation::VoiceActivity,
201 talking: false,208 talking: false,
202 hangover: 0,209 hangover: 0,
203 sending: false,210 sending: false,
@@ -227,10 +234,9 @@ impl Engine {
227 if loud >= self.gate {234 if loud >= self.gate {
228 self.hangover = HANGOVER_FRAMES;235 self.hangover = HANGOVER_FRAMES;
229 }236 }
230- let talking = if self.push_to_talk {237+ let talking = match self.activation {
231- self.talking238+ Activation::PushToTalk => self.talking,
232- } else {239+ Activation::VoiceActivity => self.hangover > 0,
233- self.hangover > 0
234 };240 };
235 self.hangover = self.hangover.saturating_sub(1);241 self.hangover = self.hangover.saturating_sub(1);
236 let speaking = talking && !self.muted && !self.deafened;242 let speaking = talking && !self.muted && !self.deafened;
@@ -276,18 +282,13 @@ impl Engine {
276 let now = Instant::now();282 let now = Instant::now();
277 self.received_bytes += datagram.len();283 self.received_bytes += datagram.len();
278 284
279- let stale = self285+ let speaker = self
280 .speakers286 .speakers
281- .get(&user_id)287+ .entry(user_id)
282- .is_none_or(|speaker| now.duration_since(speaker.last_heard) > RESTART_AFTER);288+ .or_insert_with(|| Speaker::new(sequence, now));
283- if stale {289+ if now.duration_since(speaker.last_heard) > RESTART_AFTER {
284- self.speakers290+ *speaker = Speaker::new(sequence, now);
285- .insert(user_id.clone(), Speaker::new(sequence, now));
286 }291 }
287-
288- let Some(speaker) = self.speakers.get_mut(&user_id) else {
289- return;
290- };
291 speaker.last_heard = now;292 speaker.last_heard = now;
292 if payload.is_empty() || sequence < speaker.next {293 if payload.is_empty() || sequence < speaker.next {
293 return;294 return;
@@ -379,14 +380,7 @@ impl Engine {
379 }380 }
380 381
381 pub fn bitrate_kbps(&self) -> u32 {382 pub fn bitrate_kbps(&self) -> u32 {
382- match self.profile {383+ bitrate(self.profile) / 1000
383- Profile::Voice => VOICE_BITRATE as u32 / 1000,
384- Profile::Music => MUSIC_BITRATE as u32 / 1000,
385- }
386- }
387-
388- pub fn forget(&mut self, user_id: &str) {
389- self.speakers.remove(user_id);
390 }384 }
391 385
392 pub fn set_muted(&mut self, muted: bool) {386 pub fn set_muted(&mut self, muted: bool) {
@@ -402,13 +396,13 @@ impl Engine {
402 sensitivity_db: f32,396 sensitivity_db: f32,
403 input_volume: f32,397 input_volume: f32,
404 output_volume: f32,398 output_volume: f32,
405- push_to_talk: bool,399+ activation: Activation,
406 profile: Profile,400 profile: Profile,
407 ) {401 ) {
408 self.gate = 10f32.powf(sensitivity_db / 20.0);402 self.gate = 10f32.powf(sensitivity_db / 20.0);
409 self.input_gain = input_volume / 100.0;403 self.input_gain = input_volume / 100.0;
410 self.output_gain = output_volume / 100.0;404 self.output_gain = output_volume / 100.0;
411- self.push_to_talk = push_to_talk;405+ self.activation = activation;
412 if profile != self.profile {406 if profile != self.profile {
413 self.encoder = encoder(profile);407 self.encoder = encoder(profile);
414 self.profile = profile;408 self.profile = profile;
@@ -422,10 +416,6 @@ impl Engine {
422 pub fn level_db(&self) -> f32 {416 pub fn level_db(&self) -> f32 {
423 self.level_db417 self.level_db
424 }418 }
425-
426- pub fn output_gain(&self) -> f32 {
427- self.output_gain
428- }
429 }419 }
430 420
431 #[cfg(test)]421 #[cfg(test)]
crates/client/src/voice/mod.rsmodified+37 -74
@@ -19,7 +19,7 @@ use tracing::warn;
19 pub mod audio;19 pub mod audio;
20 pub mod engine;20 pub mod engine;
21 21
22-use crate::settings::{Activation, VoiceSettings};22+use crate::settings::VoiceSettings;
23 use audio::{Audio, Choice};23 use audio::{Audio, Choice};
24 use engine::{Engine, SILENT_DB, Traffic};24 use engine::{Engine, SILENT_DB, Traffic};
25 25
@@ -127,8 +127,6 @@ fn plops(plops: &[Plop], seconds: f32) -> Vec<f32> {
127 reverb(dry, rate)127 reverb(dry, rate)
128 }128 }
129 129
130-const YUMUSH_SECONDS: f32 = 0.9;
131-const RING_SECONDS: f32 = 1.3;
132 const DETUNE: [f32; 2] = [0.998, 1.002];130 const DETUNE: [f32; 2] = [0.998, 1.002];
133 const PITCH_SETTLE: f32 = 0.04;131 const PITCH_SETTLE: f32 = 0.04;
134 const ATTACK: f32 = 0.004;132 const ATTACK: f32 = 0.004;
@@ -145,52 +143,28 @@ struct Plop {
145 gain: f32,143 gain: f32,
146 }144 }
147 145
148-const YUMUSH: [Plop; 2] = [146+const fn plop(start: f32, from: f32, rise: f32, decay: f32, gain: f32) -> Plop {
149- Plop {
150- start: 0.0,
151- from: 620.0,
152- rise: 0.6,
153- decay: 0.07,
154- gain: 1.0,
155- },
156 Plop {147 Plop {
157- start: 0.13,148+ start,
158- from: 400.0,149+ from,
159- rise: 0.45,150+ rise,
160- decay: 0.14,151+ decay,
161- gain: 0.9,152+ gain,
162- },153+ }
154+}
155+
156+const YUMUSH_SECONDS: f32 = 0.9;
157+const YUMUSH: [Plop; 2] = [
158+ plop(0.0, 620.0, 0.6, 0.07, 1.0),
159+ plop(0.13, 400.0, 0.45, 0.14, 0.9),
163 ];160 ];
164 161
162+const RING_SECONDS: f32 = 1.3;
165 const RING: [Plop; 4] = [163 const RING: [Plop; 4] = [
166- Plop {164+ plop(0.0, 400.0, 0.45, 0.1, 0.9),
167- start: 0.0,165+ plop(0.14, 500.0, 0.45, 0.1, 0.9),
168- from: 400.0,166+ plop(0.28, 620.0, 0.6, 0.12, 1.0),
169- rise: 0.45,167+ plop(0.5, 620.0, 0.6, 0.2, 0.8),
170- decay: 0.1,
171- gain: 0.9,
172- },
173- Plop {
174- start: 0.14,
175- from: 500.0,
176- rise: 0.45,
177- decay: 0.1,
178- gain: 0.9,
179- },
180- Plop {
181- start: 0.28,
182- from: 620.0,
183- rise: 0.6,
184- decay: 0.12,
185- gain: 1.0,
186- },
187- Plop {
188- start: 0.5,
189- from: 620.0,
190- rise: 0.6,
191- decay: 0.2,
192- gain: 0.8,
193- },
194 ];168 ];
195 169
196 impl Plop {170 impl Plop {
@@ -302,34 +276,33 @@ impl Voice {
302 self.choice = settings.choice.clone();276 self.choice = settings.choice.clone();
303 }277 }
304 278
305- if let Ok(mut engine) = self.engine.lock() {279+ self.with_engine((), |engine| {
306 engine.configure(280 engine.configure(
307 settings.sensitivity_db,281 settings.sensitivity_db,
308 settings.input_volume,282 settings.input_volume,
309 settings.output_volume,283 settings.output_volume,
310- settings.activation == Activation::PushToTalk,284+ settings.activation,
311 settings.profile,285 settings.profile,
312- );286+ )
313- }287+ });
288+ }
289+
290+ fn with_engine<T>(&self, default: T, f: impl FnOnce(&mut Engine) -> T) -> T {
291+ self.engine
292+ .lock()
293+ .map_or(default, |mut engine| f(&mut engine))
314 }294 }
315 295
316 pub fn receive(&self, datagram: &[u8]) {296 pub fn receive(&self, datagram: &[u8]) {
317- if let Ok(mut engine) = self.engine.lock() {297+ self.with_engine((), |engine| engine.receive(datagram));
318- engine.receive(datagram);
319- }
320 }298 }
321 299
322 pub fn speaking(&self) -> Vec<String> {300 pub fn speaking(&self) -> Vec<String> {
323- self.engine301+ self.with_engine(Vec::new(), |engine| engine.speaking())
324- .lock()
325- .map(|engine| engine.speaking())
326- .unwrap_or_default()
327 }302 }
328 303
329 pub fn level_db(&self) -> f32 {304 pub fn level_db(&self) -> f32 {
330- self.engine305+ self.with_engine(SILENT_DB, |engine| engine.level_db())
331- .lock()
332- .map_or(SILENT_DB, |engine| engine.level_db())
333 }306 }
334 307
335 pub fn sample(&self) -> VoiceSample {308 pub fn sample(&self) -> VoiceSample {
@@ -337,33 +310,23 @@ impl Voice {
337 .connection310 .connection
338 .as_ref()311 .as_ref()
339 .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0);312 .map_or(0.0, |connection| connection.rtt().as_secs_f32() * 1000.0);
340- let Ok(mut engine) = self.engine.lock() else {313+ self.with_engine(VoiceSample::default(), |engine| VoiceSample {
341- return VoiceSample::default();
342- };
343-
344- VoiceSample {
345 ping_ms,314 ping_ms,
346 traffic: engine.take_traffic(),315 traffic: engine.take_traffic(),
347 bitrate_kbps: engine.bitrate_kbps(),316 bitrate_kbps: engine.bitrate_kbps(),
348- }317+ })
349 }318 }
350 319
351 pub fn set_muted(&self, muted: bool) {320 pub fn set_muted(&self, muted: bool) {
352- if let Ok(mut engine) = self.engine.lock() {321+ self.with_engine((), |engine| engine.set_muted(muted));
353- engine.set_muted(muted);
354- }
355 }322 }
356 323
357 pub fn set_deafened(&self, deafened: bool) {324 pub fn set_deafened(&self, deafened: bool) {
358- if let Ok(mut engine) = self.engine.lock() {325+ self.with_engine((), |engine| engine.set_deafened(deafened));
359- engine.set_deafened(deafened);
360- }
361 }326 }
362 327
363 pub fn set_talking(&self, talking: bool) {328 pub fn set_talking(&self, talking: bool) {
364- if let Ok(mut engine) = self.engine.lock() {329+ self.with_engine((), |engine| engine.set_talking(talking));
365- engine.set_talking(talking);
366- }
367 }330 }
368 }331 }
369 332
crates/common/src/event.rsmodified+4 -2
@@ -1,6 +1,8 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::model::{Community, Friends, Invitation, Member, Message, Presence, Rank, User};3+use crate::model::{
4+ Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, User,
5+};
4 6
5 #[derive(Debug, Clone, Encode, Decode)]7 #[derive(Debug, Clone, Encode, Decode)]
6 pub enum Event {8 pub enum Event {
@@ -25,7 +27,7 @@ pub enum Event {
25 Removed {27 Removed {
26 community_id: String,28 community_id: String,
27 community_name: String,29 community_name: String,
28- banned: bool,30+ sanction: Sanction,
29 reason: Option<String>,31 reason: Option<String>,
30 },32 },
31 FriendsUpdated(Friends),33 FriendsUpdated(Friends),
crates/common/src/model.rsmodified+117 -255
@@ -5,52 +5,57 @@ use crate::constant::{
5 MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH,5 MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH,
6 };6 };
7 7
8-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]8+#[macro_export]
9-pub enum Role {9+macro_rules! string_enum {
10- User,10+ ($(#[$meta:meta])* $name:ident { $($variant:ident => $text:literal),+ $(,)? }) => {
11- Builder,11+ $(#[$meta])*
12-}12+ pub enum $name {
13+ $($variant),+
14+ }
13 15
14-impl Role {16+ impl $name {
15- pub const ALL: [Self; 2] = [Role::User, Role::Builder];17+ pub const ALL: [Self; [$(stringify!($variant)),+].len()] = [$(Self::$variant),+];
16 18
17- pub fn as_str(self) -> &'static str {19+ pub const fn as_str(self) -> &'static str {
18- match self {20+ match self {
19- Role::User => "user",21+ $(Self::$variant => $text),+
20- Role::Builder => "builder",22+ }
23+ }
24+
25+ pub fn parse(text: &str) -> Option<Self> {
26+ Self::ALL.into_iter().find(|item| item.as_str() == text)
27+ }
21 }28 }
29+ };
30+}
31+
32+string_enum! {
33+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
34+ Role {
35+ User => "user",
36+ Builder => "builder",
22 }37 }
38+}
23 39
40+impl Role {
24 pub fn label(self) -> &'static str {41 pub fn label(self) -> &'static str {
25 match self {42 match self {
26 Role::User => "User",43 Role::User => "User",
27 Role::Builder => "Builder",44 Role::Builder => "Builder",
28 }45 }
29 }46 }
30-
31- pub fn parse(text: &str) -> Option<Self> {
32- Self::ALL.into_iter().find(|role| role.as_str() == text)
33- }
34 }47 }
35 48
36-#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]49+string_enum! {
37-pub enum Presence {50+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
38- Online,51+ Presence {
39- Busy,52+ Online => "online",
40- Offline,53+ Busy => "busy",
54+ Offline => "offline",
55+ }
41 }56 }
42 57
43 impl Presence {58 impl Presence {
44- pub const ALL: [Self; 3] = [Presence::Online, Presence::Busy, Presence::Offline];
45-
46- pub fn as_str(self) -> &'static str {
47- match self {
48- Presence::Online => "online",
49- Presence::Busy => "busy",
50- Presence::Offline => "offline",
51- }
52- }
53-
54 pub fn label(self) -> &'static str {59 pub fn label(self) -> &'static str {
55 match self {60 match self {
56 Presence::Online => "Online",61 Presence::Online => "Online",
@@ -58,42 +63,20 @@ impl Presence {
58 Presence::Offline => "Offline",63 Presence::Offline => "Offline",
59 }64 }
60 }65 }
61-
62- pub fn parse(text: &str) -> Option<Self> {
63- Self::ALL
64- .into_iter()
65- .find(|presence| presence.as_str() == text)
66- }
67 }66 }
68 67
69-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]68+string_enum! {
70-pub enum Rank {69+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
71- Member,70+ Rank {
72- Moderator,71+ Member => "member",
73- Admin,72+ Moderator => "moderator",
74- Owner,73+ Admin => "admin",
75- Builder,74+ Owner => "owner",
75+ Builder => "builder",
76+ }
76 }77 }
77 78
78 impl Rank {79 impl Rank {
79- pub const ALL: [Self; 5] = [
80- Rank::Member,
81- Rank::Moderator,
82- Rank::Admin,
83- Rank::Owner,
84- Rank::Builder,
85- ];
86-
87- pub fn as_str(self) -> &'static str {
88- match self {
89- Rank::Member => "member",
90- Rank::Moderator => "moderator",
91- Rank::Admin => "admin",
92- Rank::Owner => "owner",
93- Rank::Builder => "builder",
94- }
95- }
96-
97 pub fn label(self) -> &'static str {80 pub fn label(self) -> &'static str {
98 match self {81 match self {
99 Rank::Member => "Member",82 Rank::Member => "Member",
@@ -103,10 +86,6 @@ impl Rank {
103 Rank::Builder => "Builder",86 Rank::Builder => "Builder",
104 }87 }
105 }88 }
106-
107- pub fn parse(text: &str) -> Option<Self> {
108- Self::ALL.into_iter().find(|rank| rank.as_str() == text)
109- }
110 }89 }
111 90
112 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]91 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
@@ -147,6 +126,24 @@ pub enum CommunityKind {
147 Notes,126 Notes,
148 }127 }
149 128
129+impl CommunityKind {
130+ pub fn is_direct(&self) -> bool {
131+ matches!(self, Self::Direct { .. })
132+ }
133+}
134+
135+#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
136+pub enum Sanction {
137+ Kick,
138+ Ban,
139+}
140+
141+#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
142+pub enum BanScope {
143+ Account,
144+ AccountAndIp,
145+}
146+
150 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]147 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
151 pub struct Community {148 pub struct Community {
152 pub id: String,149 pub id: String,
@@ -250,114 +247,40 @@ pub enum AdminAction {
250 BackupDownloaded { name: String },247 BackupDownloaded { name: String },
251 }248 }
252 249
253-#[derive(Debug, Clone, Copy, PartialEq, Eq)]250+string_enum! {
254-pub enum AdminActionKind {251+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
255- RoleChanged,252+ AdminActionKind {
256- UserDeleted,253+ RoleChanged => "role_changed",
257- UserSuspended,254+ UserDeleted => "user_deleted",
258- UserUnsuspended,255+ UserSuspended => "user_suspended",
259- SessionsRevoked,256+ UserUnsuspended => "user_unsuspended",
260- PasswordReset,257+ SessionsRevoked => "sessions_revoked",
261- ProfileCleared,258+ PasswordReset => "password_reset",
262- UserCreated,259+ ProfileCleared => "profile_cleared",
263- CommunityDeleted,260+ UserCreated => "user_created",
264- OwnershipTransferred,261+ CommunityDeleted => "community_deleted",
265- SettingsChanged,262+ OwnershipTransferred => "ownership_transferred",
266- UserRenamed,263+ SettingsChanged => "settings_changed",
267- UserTimedOut,264+ UserRenamed => "user_renamed",
268- UserBanned,265+ UserTimedOut => "user_timed_out",
269- BanRemoved,266+ UserBanned => "user_banned",
270- InviteCreated,267+ BanRemoved => "ban_removed",
271- InviteDeleted,268+ InviteCreated => "invite_created",
272- ReportHandled,269+ InviteDeleted => "invite_deleted",
273- MessageDeleted,270+ ReportHandled => "report_handled",
274- UserPurged,271+ MessageDeleted => "message_deleted",
275- VoiceKicked,272+ UserPurged => "user_purged",
276- VoiceMuted,273+ VoiceKicked => "voice_kicked",
277- CommunityVoiceSet,274+ VoiceMuted => "voice_muted",
278- AttachmentDeleted,275+ CommunityVoiceSet => "community_voice_set",
279- GhostEnabled,276+ AttachmentDeleted => "attachment_deleted",
280- GhostDisabled,277+ GhostEnabled => "ghost_enabled",
281- GhostVisit,278+ GhostDisabled => "ghost_disabled",
282- GhostVoice,279+ GhostVisit => "ghost_visit",
283- BackupCreated,280+ GhostVoice => "ghost_voice",
284- BackupDeleted,281+ BackupCreated => "backup_created",
285- BackupDownloaded,282+ BackupDeleted => "backup_deleted",
286-}283+ BackupDownloaded => "backup_downloaded",
287-
288-impl AdminActionKind {
289- pub const ALL: [Self; 31] = [
290- AdminActionKind::RoleChanged,
291- AdminActionKind::UserDeleted,
292- AdminActionKind::UserSuspended,
293- AdminActionKind::UserUnsuspended,
294- AdminActionKind::SessionsRevoked,
295- AdminActionKind::PasswordReset,
296- AdminActionKind::ProfileCleared,
297- AdminActionKind::UserCreated,
298- AdminActionKind::CommunityDeleted,
299- AdminActionKind::OwnershipTransferred,
300- AdminActionKind::SettingsChanged,
301- AdminActionKind::UserRenamed,
302- AdminActionKind::UserTimedOut,
303- AdminActionKind::UserBanned,
304- AdminActionKind::BanRemoved,
305- AdminActionKind::InviteCreated,
306- AdminActionKind::InviteDeleted,
307- AdminActionKind::ReportHandled,
308- AdminActionKind::MessageDeleted,
309- AdminActionKind::UserPurged,
310- AdminActionKind::VoiceKicked,
311- AdminActionKind::VoiceMuted,
312- AdminActionKind::CommunityVoiceSet,
313- AdminActionKind::AttachmentDeleted,
314- AdminActionKind::GhostEnabled,
315- AdminActionKind::GhostDisabled,
316- AdminActionKind::GhostVisit,
317- AdminActionKind::GhostVoice,
318- AdminActionKind::BackupCreated,
319- AdminActionKind::BackupDeleted,
320- AdminActionKind::BackupDownloaded,
321- ];
322-
323- pub const fn as_str(self) -> &'static str {
324- match self {
325- AdminActionKind::RoleChanged => "role_changed",
326- AdminActionKind::UserDeleted => "user_deleted",
327- AdminActionKind::UserSuspended => "user_suspended",
328- AdminActionKind::UserUnsuspended => "user_unsuspended",
329- AdminActionKind::SessionsRevoked => "sessions_revoked",
330- AdminActionKind::PasswordReset => "password_reset",
331- AdminActionKind::ProfileCleared => "profile_cleared",
332- AdminActionKind::UserCreated => "user_created",
333- AdminActionKind::CommunityDeleted => "community_deleted",
334- AdminActionKind::OwnershipTransferred => "ownership_transferred",
335- AdminActionKind::SettingsChanged => "settings_changed",
336- AdminActionKind::UserRenamed => "user_renamed",
337- AdminActionKind::UserTimedOut => "user_timed_out",
338- AdminActionKind::UserBanned => "user_banned",
339- AdminActionKind::BanRemoved => "ban_removed",
340- AdminActionKind::InviteCreated => "invite_created",
341- AdminActionKind::InviteDeleted => "invite_deleted",
342- AdminActionKind::ReportHandled => "report_handled",
343- AdminActionKind::MessageDeleted => "message_deleted",
344- AdminActionKind::UserPurged => "user_purged",
345- AdminActionKind::VoiceKicked => "voice_kicked",
346- AdminActionKind::VoiceMuted => "voice_muted",
347- AdminActionKind::CommunityVoiceSet => "community_voice_set",
348- AdminActionKind::AttachmentDeleted => "attachment_deleted",
349- AdminActionKind::GhostEnabled => "ghost_enabled",
350- AdminActionKind::GhostDisabled => "ghost_disabled",
351- AdminActionKind::GhostVisit => "ghost_visit",
352- AdminActionKind::GhostVoice => "ghost_voice",
353- AdminActionKind::BackupCreated => "backup_created",
354- AdminActionKind::BackupDeleted => "backup_deleted",
355- AdminActionKind::BackupDownloaded => "backup_downloaded",
356- }
357- }
358-
359- pub fn parse(text: &str) -> Option<Self> {
360- Self::ALL.into_iter().find(|kind| kind.as_str() == text)
361 }284 }
362 }285 }
363 286
@@ -397,22 +320,10 @@ impl AdminAction {
397 AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded,320 AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded,
398 }321 }
399 }322 }
400-}
401 323
402-const fn action_names() -> [&'static str; 31] {324+ pub fn name(&self) -> &'static str {
403- let mut names = [""; 31];325+ self.kind().as_str()
404- let mut index = 0;
405- while index < 31 {
406- names[index] = AdminActionKind::ALL[index].as_str();
407- index += 1;
408 }326 }
409- names
410-}
411-
412-pub const ACTION_NAMES: [&str; 31] = action_names();
413-
414-pub fn action_name(action: &AdminAction) -> &'static str {
415- action.kind().as_str()
416 }327 }
417 328
418 pub fn action_detail(action: &AdminAction) -> Option<String> {329 pub fn action_detail(action: &AdminAction) -> Option<String> {
@@ -442,28 +353,16 @@ pub struct AdminLogEntry {
442 pub action: AdminAction,353 pub action: AdminAction,
443 }354 }
444 355
445-#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]356+string_enum! {
446-pub enum ReportStatus {357+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
447- Open,358+ ReportStatus {
448- Resolved,359+ Open => "open",
449- Dismissed,360+ Resolved => "resolved",
361+ Dismissed => "dismissed",
362+ }
450 }363 }
451 364
452 impl ReportStatus {365 impl ReportStatus {
453- pub const ALL: [Self; 3] = [
454- ReportStatus::Open,
455- ReportStatus::Resolved,
456- ReportStatus::Dismissed,
457- ];
458-
459- pub fn as_str(self) -> &'static str {
460- match self {
461- ReportStatus::Open => "open",
462- ReportStatus::Resolved => "resolved",
463- ReportStatus::Dismissed => "dismissed",
464- }
465- }
466-
467 pub fn label(self) -> &'static str {366 pub fn label(self) -> &'static str {
468 match self {367 match self {
469 ReportStatus::Open => "Open",368 ReportStatus::Open => "Open",
@@ -471,10 +370,6 @@ impl ReportStatus {
471 ReportStatus::Dismissed => "Dismissed",370 ReportStatus::Dismissed => "Dismissed",
472 }371 }
473 }372 }
474-
475- pub fn parse(text: &str) -> Option<Self> {
476- Self::ALL.into_iter().find(|status| status.as_str() == text)
477- }
478 }373 }
479 374
480 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]375 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
@@ -559,24 +454,11 @@ pub struct CommunityUsage {
559 pub count: u64,454 pub count: u64,
560 }455 }
561 456
562-#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]457+string_enum! {
563-pub enum ServerBanKind {458+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
564- Username,459+ ServerBanKind {
565- Ip,460+ Username => "username",
566-}461+ Ip => "ip",
567-
568-impl ServerBanKind {
569- pub const ALL: [Self; 2] = [ServerBanKind::Username, ServerBanKind::Ip];
570-
571- pub fn as_str(self) -> &'static str {
572- match self {
573- ServerBanKind::Username => "username",
574- ServerBanKind::Ip => "ip",
575- }
576- }
577-
578- pub fn parse(text: &str) -> Option<Self> {
579- Self::ALL.into_iter().find(|kind| kind.as_str() == text)
580 }462 }
581 }463 }
582 464
@@ -627,33 +509,13 @@ pub struct Friends {
627 pub outgoing: Vec<User>,509 pub outgoing: Vec<User>,
628 }510 }
629 511
630-#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]512+string_enum! {
631-pub enum AttachmentKind {513+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
632- Image,514+ AttachmentKind {
633- Video,515+ Image => "image",
634- Audio,516+ Video => "video",
635- File,517+ Audio => "audio",
636-}518+ File => "file",
637-
638-impl AttachmentKind {
639- pub const ALL: [Self; 4] = [
640- AttachmentKind::Image,
641- AttachmentKind::Video,
642- AttachmentKind::Audio,
643- AttachmentKind::File,
644- ];
645-
646- pub fn as_str(self) -> &'static str {
647- match self {
648- AttachmentKind::Image => "image",
649- AttachmentKind::Video => "video",
650- AttachmentKind::Audio => "audio",
651- AttachmentKind::File => "file",
652- }
653- }
654-
655- pub fn parse(text: &str) -> Option<Self> {
656- Self::ALL.into_iter().find(|kind| kind.as_str() == text)
657 }519 }
658 }520 }
659 521
crates/common/src/network.rsmodified+16 -47
@@ -8,7 +8,7 @@ use crate::{
8 },8 },
9 error::Error,9 error::Error,
10 event::Event,10 event::Event,
11- request::{DownloadRequest, Request, UploadHeader},11+ request::{Request, UploadHeader},
12 response::Response,12 response::Response,
13 };13 };
14 14
@@ -90,11 +90,8 @@ pub async fn receive_download_status(
90 DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))90 DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))
91 }91 }
92 92
93-pub async fn send_upload_header(93+async fn send_framed<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
94- header: &UploadHeader,94+ let payload = bitcode::encode(value);
95- send_stream: &mut SendStream,
96-) -> Result<(), Error> {
97- let payload = bitcode::encode(header);
98 send_stream95 send_stream
99 .write_all(&(payload.len() as u32).to_le_bytes())96 .write_all(&(payload.len() as u32).to_le_bytes())
100 .await?;97 .await?;
@@ -102,15 +99,18 @@ pub async fn send_upload_header(
102 Ok(())99 Ok(())
103 }100 }
104 101
105-pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result<UploadHeader, Error> {102+async fn receive_framed<T: DecodeOwned>(
103+ receive_stream: &mut RecvStream,
104+ maximum: usize,
105+) -> Result<T, Error> {
106 let mut length_bytes = [0u8; 4];106 let mut length_bytes = [0u8; 4];
107 receive_stream.read_exact(&mut length_bytes).await?;107 receive_stream.read_exact(&mut length_bytes).await?;
108 108
109 let length = u32::from_le_bytes(length_bytes) as usize;109 let length = u32::from_le_bytes(length_bytes) as usize;
110- if length > UPLOAD_HEADER_MAX_LENGTH {110+ if length > maximum {
111 return Err(Error::ReadBoundExceed {111 return Err(Error::ReadBoundExceed {
112 actual: length,112 actual: length,
113- maximum: UPLOAD_HEADER_MAX_LENGTH,113+ maximum,
114 });114 });
115 }115 }
116 116
@@ -119,21 +119,15 @@ pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result<Up
119 Ok(bitcode::decode(&payload)?)119 Ok(bitcode::decode(&payload)?)
120 }120 }
121 121
122-pub async fn send_download_request(122+pub async fn send_upload_header(
123- request: &DownloadRequest,123+ header: &UploadHeader,
124 send_stream: &mut SendStream,124 send_stream: &mut SendStream,
125 ) -> Result<(), Error> {125 ) -> Result<(), Error> {
126- send_stream.write_all(&bitcode::encode(request)).await?;126+ send_framed(header, send_stream).await
127- Ok(())
128 }127 }
129 128
130-pub async fn receive_download_request(129+pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result<UploadHeader, Error> {
131- receive_stream: &mut RecvStream,130+ receive_framed(receive_stream, UPLOAD_HEADER_MAX_LENGTH).await
132-) -> Result<DownloadRequest, Error> {
133- let bytes = receive_stream
134- .read_to_end(DOWNLOAD_REQUEST_MAX_READ_LENGTH)
135- .await?;
136- Ok(bitcode::decode(&bytes)?)
137 }131 }
138 132
139 pub async fn send_encoded<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {133 pub async fn send_encoded<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
@@ -155,13 +149,6 @@ pub async fn send_response(response: &Response, mut send_stream: SendStream) ->
155 Ok(())149 Ok(())
156 }150 }
157 151
158-pub async fn receive_request(
159- mut receive_stream: RecvStream,
160- limit: usize,
161-) -> Result<Request, Error> {
162- receive_decoded(&mut receive_stream, limit).await
163-}
164-
165 pub async fn send_request(152 pub async fn send_request(
166 request: &Request,153 request: &Request,
167 mut send_stream: SendStream,154 mut send_stream: SendStream,
@@ -175,27 +162,9 @@ pub async fn send_request(
175 }162 }
176 163
177 pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> {164 pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> {
178- let payload = bitcode::encode(event);165+ send_framed(event, send_stream).await
179- send_stream
180- .write_all(&(payload.len() as u32).to_le_bytes())
181- .await?;
182- send_stream.write_all(&payload).await?;
183- Ok(())
184 }166 }
185 167
186 pub async fn receive_event(receive_stream: &mut RecvStream) -> Result<Event, Error> {168 pub async fn receive_event(receive_stream: &mut RecvStream) -> Result<Event, Error> {
187- let mut length_bytes = [0u8; 4];169+ receive_framed(receive_stream, EVENT_MAX_ENCODED_LENGTH).await
188- receive_stream.read_exact(&mut length_bytes).await?;
189-
190- let length = u32::from_le_bytes(length_bytes) as usize;
191- if length > EVENT_MAX_ENCODED_LENGTH {
192- return Err(Error::ReadBoundExceed {
193- actual: length,
194- maximum: EVENT_MAX_ENCODED_LENGTH,
195- });
196- }
197-
198- let mut payload = vec![0u8; length];
199- receive_stream.read_exact(&mut payload).await?;
200- Ok(bitcode::decode(&payload)?)
201 }170 }
crates/common/src/permission.rsmodified+0 -8
@@ -4,10 +4,6 @@ pub fn is_builder(role: Role) -> bool {
4 role == Role::Builder4 role == Role::Builder
5 }5 }
6 6
7-pub fn bypasses_limits(role: Role) -> bool {
8- is_builder(role)
9-}
10-
11 pub fn effective_rank(role: Role, rank: Option<Rank>) -> Option<Rank> {7 pub fn effective_rank(role: Role, rank: Option<Rank>) -> Option<Rank> {
12 match role {8 match role {
13 Role::Builder => Some(Rank::Builder),9 Role::Builder => Some(Rank::Builder),
@@ -31,10 +27,6 @@ pub fn can_join(role: Role, banned: bool) -> bool {
31 !banned || is_builder(role)27 !banned || is_builder(role)
32 }28 }
33 29
34-pub fn can_edit_message(is_author: bool) -> bool {
35- is_author
36-}
37-
38 pub fn can_pin(actor: Option<Rank>, direct: bool) -> bool {30 pub fn can_pin(actor: Option<Rank>, direct: bool) -> bool {
39 actor >= Some(Rank::Moderator) || (direct && actor.is_some())31 actor >= Some(Rank::Moderator) || (direct && actor.is_some())
40 }32 }
crates/common/src/request.rsmodified+2 -2
@@ -1,6 +1,6 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::model::{Presence, Rank, ReportStatus, Role, ServerSettings};3+use crate::model::{BanScope, Presence, Rank, ReportStatus, Role, ServerSettings};
4 4
5 #[derive(Debug, Clone, Encode, Decode)]5 #[derive(Debug, Clone, Encode, Decode)]
6 pub struct UploadHeader {6 pub struct UploadHeader {
@@ -256,7 +256,7 @@ pub enum Request {
256 BanUser {256 BanUser {
257 user_id: String,257 user_id: String,
258 reason: Option<String>,258 reason: Option<String>,
259- ip: bool,259+ scope: BanScope,
260 },260 },
261 ServerBans,261 ServerBans,
262 RemoveServerBan {262 RemoveServerBan {
crates/common/src/time.rsmodified+10 -0
@@ -20,3 +20,13 @@ pub fn created_at_ms(id: &str) -> Option<u64> {
20 pub fn id_bound(ms: u64) -> String {20 pub fn id_bound(ms: u64) -> String {
21 format!("{:08x}-{:04x}", ms >> 16, ms & 0xffff)21 format!("{:08x}-{:04x}", ms >> 16, ms & 0xffff)
22 }22 }
23+
24+pub fn range_bounds(
25+ after_ms: Option<u64>,
26+ before_ms: Option<u64>,
27+) -> (Option<String>, Option<String>) {
28+ (
29+ after_ms.map(id_bound),
30+ before_ms.map(|before| id_bound(before + 1)),
31+ )
32+}
crates/common/src/validate.rsmodified+17 -15
@@ -27,6 +27,10 @@ fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), Inv
27 Ok(())27 Ok(())
28 }28 }
29 29
30+fn check_text(text: &str, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
31+ check_length(text.chars().count(), minimum, maximum)
32+}
33+
30 fn check(34 fn check(
31 input: &str,35 input: &str,
32 minimum: usize,36 minimum: usize,
@@ -75,21 +79,20 @@ pub fn validate_message_body(body: &str, maximum: usize) -> Result<(), Error> {
75 }79 }
76 80
77 pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> {81 pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> {
78- if attachments == 0 {82+ let minimum = if attachments == 0 {
79- return validate_message_body(body, maximum);83+ MINIMUM_MESSAGE_LENGTH
80- }84+ } else {
81-85+ 0
82- check(body, 0, maximum, false).map_err(Error::Message)86+ };
87+ check(body, minimum, maximum, false).map_err(Error::Message)
83 }88 }
84 89
85 pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> {90 pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> {
86- check_length(question.chars().count(), 1, MAXIMUM_POLL_QUESTION_LENGTH)91+ check_text(question, 1, MAXIMUM_POLL_QUESTION_LENGTH).map_err(Error::Message)?;
87- .map_err(Error::Message)?;
88 check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)92 check_length(options.len(), MINIMUM_POLL_OPTIONS, MAXIMUM_POLL_OPTIONS)
89 .map_err(Error::Message)?;93 .map_err(Error::Message)?;
90 for option in options {94 for option in options {
91- check_length(option.chars().count(), 1, MAXIMUM_POLL_OPTION_LENGTH)95+ check_text(option, 1, MAXIMUM_POLL_OPTION_LENGTH).map_err(Error::Message)?;
92- .map_err(Error::Message)?;
93 }96 }
94 97
95 Ok(())98 Ok(())
@@ -117,8 +120,7 @@ pub fn validate_reaction(emoji: &str) -> Result<(), Error> {
117 }120 }
118 121
119 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {122 pub fn validate_attachment_name(name: &str) -> Result<(), Error> {
120- check_length(name.chars().count(), 1, MAXIMUM_ATTACHMENT_NAME_LENGTH)123+ check_text(name, 1, MAXIMUM_ATTACHMENT_NAME_LENGTH).map_err(Error::AttachmentName)?;
121- .map_err(Error::AttachmentName)?;
122 124
123 if name.contains(['/', '\\']) || name.chars().any(char::is_control) {125 if name.contains(['/', '\\']) || name.chars().any(char::is_control) {
124 return Err(Error::AttachmentName(InvalidInput::ForbiddenCharacter));126 return Err(Error::AttachmentName(InvalidInput::ForbiddenCharacter));
@@ -186,7 +188,7 @@ pub fn validate_announcement(text: &str) -> Result<(), Error> {
186 return Err(Error::Announcement(InvalidInput::MultiLine));188 return Err(Error::Announcement(InvalidInput::MultiLine));
187 }189 }
188 190
189- check_length(text.chars().count(), 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(Error::Announcement)191+ check_text(text, 0, MAXIMUM_ANNOUNCEMENT_LENGTH).map_err(Error::Announcement)
190 }192 }
191 193
192 pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> {194 pub fn validate_server_settings(settings: &ServerSettings) -> Result<(), Error> {
@@ -214,7 +216,7 @@ pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {
214 if reason.contains(['\n', '\r']) {216 if reason.contains(['\n', '\r']) {
215 return Err(Error::Reason(InvalidInput::MultiLine));217 return Err(Error::Reason(InvalidInput::MultiLine));
216 }218 }
217- check_length(reason.chars().count(), 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason)219+ check_text(reason, 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason)
218 }220 }
219 221
220 pub fn validate_forward(count: usize) -> Result<(), Error> {222 pub fn validate_forward(count: usize) -> Result<(), Error> {
@@ -226,11 +228,11 @@ pub fn validate_status(status: &str) -> Result<(), Error> {
226 return Err(Error::Status(InvalidInput::MultiLine));228 return Err(Error::Status(InvalidInput::MultiLine));
227 }229 }
228 230
229- check_length(status.chars().count(), 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status)231+ check_text(status, 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status)
230 }232 }
231 233
232 pub fn validate_device(name: &str) -> Result<(), Error> {234 pub fn validate_device(name: &str) -> Result<(), Error> {
233- check_length(name.chars().count(), 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(Error::Device)235+ check_text(name, 1, MAXIMUM_DEVICE_NAME_LENGTH).map_err(Error::Device)
234 }236 }
235 237
236 pub fn validate_avatar_size(bytes: &[u8], maximum: u64) -> Result<(), Error> {238 pub fn validate_avatar_size(bytes: &[u8], maximum: u64) -> Result<(), Error> {
crates/server/src/admin_log.rsmodified+37 -44
@@ -1,8 +1,6 @@
1 use common::{1 use common::{
2 constant::LOG_PAGE_LIMIT,2 constant::LOG_PAGE_LIMIT,
3- model::{3+ model::{AdminAction, AdminLogEntry, ReportStatus, Role, action_detail},
4- AdminAction, AdminActionKind, AdminLogEntry, ReportStatus, Role, action_detail, action_name,
5- },
6 time,4 time,
7 };5 };
8 use turso::Connection;6 use turso::Connection;
@@ -10,53 +8,53 @@ use turso::Connection;
10 use crate::{database::new_id, error::Error, user};8 use crate::{database::new_id, error::Error, user};
11 9
12 fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {10 fn action_of(text: &str, detail: Option<String>) -> Option<AdminAction> {
13- let kind = AdminActionKind::parse(text)?;11+ Some(match text {
14- Some(match kind {12+ "role_changed" => AdminAction::RoleChanged {
15- AdminActionKind::RoleChanged => AdminAction::RoleChanged {
16 role: Role::parse(&detail?)?,13 role: Role::parse(&detail?)?,
17 },14 },
18- AdminActionKind::UserDeleted => AdminAction::UserDeleted,15+ "user_deleted" => AdminAction::UserDeleted,
19- AdminActionKind::UserSuspended => AdminAction::UserSuspended,16+ "user_suspended" => AdminAction::UserSuspended,
20- AdminActionKind::UserUnsuspended => AdminAction::UserUnsuspended,17+ "user_unsuspended" => AdminAction::UserUnsuspended,
21- AdminActionKind::SessionsRevoked => AdminAction::SessionsRevoked,18+ "sessions_revoked" => AdminAction::SessionsRevoked,
22- AdminActionKind::PasswordReset => AdminAction::PasswordReset,19+ "password_reset" => AdminAction::PasswordReset,
23- AdminActionKind::ProfileCleared => AdminAction::ProfileCleared,20+ "profile_cleared" => AdminAction::ProfileCleared,
24- AdminActionKind::UserCreated => AdminAction::UserCreated,21+ "user_created" => AdminAction::UserCreated,
25- AdminActionKind::CommunityDeleted => AdminAction::CommunityDeleted,22+ "community_deleted" => AdminAction::CommunityDeleted,
26- AdminActionKind::OwnershipTransferred => AdminAction::OwnershipTransferred,23+ "ownership_transferred" => AdminAction::OwnershipTransferred,
27- AdminActionKind::SettingsChanged => AdminAction::SettingsChanged,24+ "settings_changed" => AdminAction::SettingsChanged,
28- AdminActionKind::UserRenamed => AdminAction::UserRenamed { from: detail? },25+ "user_renamed" => AdminAction::UserRenamed { from: detail? },
29- AdminActionKind::UserTimedOut => AdminAction::UserTimedOut {26+ "user_timed_out" => AdminAction::UserTimedOut {
30 minutes: detail?.parse().ok()?,27 minutes: detail?.parse().ok()?,
31 },28 },
32- AdminActionKind::UserBanned => AdminAction::UserBanned { reason: detail },29+ "user_banned" => AdminAction::UserBanned { reason: detail },
33- AdminActionKind::BanRemoved => AdminAction::BanRemoved,30+ "ban_removed" => AdminAction::BanRemoved,
34- AdminActionKind::InviteCreated => AdminAction::InviteCreated,31+ "invite_created" => AdminAction::InviteCreated,
35- AdminActionKind::InviteDeleted => AdminAction::InviteDeleted,32+ "invite_deleted" => AdminAction::InviteDeleted,
36- AdminActionKind::ReportHandled => AdminAction::ReportHandled {33+ "report_handled" => AdminAction::ReportHandled {
37 status: ReportStatus::parse(&detail?)?,34 status: ReportStatus::parse(&detail?)?,
38 },35 },
39- AdminActionKind::MessageDeleted => AdminAction::MessageDeleted,36+ "message_deleted" => AdminAction::MessageDeleted,
40- AdminActionKind::UserPurged => AdminAction::UserPurged {37+ "user_purged" => AdminAction::UserPurged {
41 messages: detail?.parse().ok()?,38 messages: detail?.parse().ok()?,
42 },39 },
43- AdminActionKind::VoiceKicked => AdminAction::VoiceKicked,40+ "voice_kicked" => AdminAction::VoiceKicked,
44- AdminActionKind::VoiceMuted => AdminAction::VoiceMuted {41+ "voice_muted" => AdminAction::VoiceMuted {
45 muted: detail?.parse().ok()?,42 muted: detail?.parse().ok()?,
46 },43 },
47- AdminActionKind::CommunityVoiceSet => AdminAction::CommunityVoiceSet {44+ "community_voice_set" => AdminAction::CommunityVoiceSet {
48 enabled: detail?.parse().ok()?,45 enabled: detail?.parse().ok()?,
49 },46 },
50- AdminActionKind::AttachmentDeleted => AdminAction::AttachmentDeleted,47+ "attachment_deleted" => AdminAction::AttachmentDeleted,
51- AdminActionKind::GhostEnabled => AdminAction::GhostEnabled,48+ "ghost_enabled" => AdminAction::GhostEnabled,
52- AdminActionKind::GhostDisabled => AdminAction::GhostDisabled,49+ "ghost_disabled" => AdminAction::GhostDisabled,
53- AdminActionKind::GhostVisit => AdminAction::GhostVisit,50+ "ghost_visit" => AdminAction::GhostVisit,
54- AdminActionKind::GhostVoice => AdminAction::GhostVoice {51+ "ghost_voice" => AdminAction::GhostVoice {
55 seconds: detail?.parse().ok()?,52 seconds: detail?.parse().ok()?,
56 },53 },
57- AdminActionKind::BackupCreated => AdminAction::BackupCreated { name: detail? },54+ "backup_created" => AdminAction::BackupCreated { name: detail? },
58- AdminActionKind::BackupDeleted => AdminAction::BackupDeleted { name: detail? },55+ "backup_deleted" => AdminAction::BackupDeleted { name: detail? },
59- AdminActionKind::BackupDownloaded => AdminAction::BackupDownloaded { name: detail? },56+ "backup_downloaded" => AdminAction::BackupDownloaded { name: detail? },
57+ _ => return None,
60 })58 })
61 }59 }
62 60
@@ -76,7 +74,7 @@ pub async fn record(
76 actor_id,74 actor_id,
77 target_id,75 target_id,
78 community,76 community,
79- action_name(action),77+ action.name(),
80 detail.as_deref(),78 detail.as_deref(),
81 ),79 ),
82 )80 )
@@ -93,16 +91,11 @@ pub async fn list(
93 before_ms: Option<u64>,91 before_ms: Option<u64>,
94 conn: &Connection,92 conn: &Connection,
95 ) -> Result<Vec<AdminLogEntry>, Error> {93 ) -> Result<Vec<AdminLogEntry>, Error> {
94+ let (after, before) = time::range_bounds(after_ms, before_ms);
96 let mut rows = conn95 let mut rows = conn
97 .query(96 .query(
98 &format!("SELECT l.id, l.action, l.detail, {}, {}, l.community FROM admin_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.action = ?3) AND (?4 IS NULL OR l.id >= ?4) AND (?5 IS NULL OR l.id < ?5) ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")),97 &format!("SELECT l.id, l.action, l.detail, {}, {}, l.community FROM admin_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.action = ?3) AND (?4 IS NULL OR l.id >= ?4) AND (?5 IS NULL OR l.id < ?5) ORDER BY l.id DESC LIMIT {LOG_PAGE_LIMIT}", user::user_columns("a"), user::user_columns("t")),
99- (98+ (actor_id, target_id, action, after, before),
100- actor_id,
101- target_id,
102- action,
103- after_ms.map(time::id_bound),
104- before_ms.map(|before| time::id_bound(before + 1)),
105- ),
106 )99 )
107 .await?;100 .await?;
108 101
crates/server/src/attachment.rsmodified+98 -91
@@ -15,13 +15,13 @@ use common::{
15 Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User,15 Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, ServerSettings, Usage, User,
16 },16 },
17 network::{17 network::{
18- DownloadStatus, receive_download_request, receive_upload_header, send_download_status,18+ DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, receive_upload_header,
19- send_encoded, send_response,19+ send_download_status, send_encoded, send_response,
20 },20 },
21 permission,21 permission,
22 request::{DownloadRequest, UploadHeader},22 request::{DownloadRequest, UploadHeader},
23 response::Response,23 response::Response,
24- time::HOUR_MILLIS,24+ time::{self, HOUR_MILLIS},
25 validate::{validate_attachment_name, validate_attachment_size},25 validate::{validate_attachment_name, validate_attachment_size},
26 };26 };
27 use image::{ImageFormat, ImageReader, Limits};27 use image::{ImageFormat, ImageReader, Limits};
@@ -32,41 +32,45 @@ use tokio::{
32 };32 };
33 use tracing::error;33 use tracing::error;
34 use turso::{Connection, Row};34 use turso::{Connection, Row};
35-use uuid::{Timestamp, Uuid};
36 35
37 use crate::{36 use crate::{
38 community,37 community,
39 database::{self, DB, new_id},38 database::{self, DB, new_id},
40 error::Error,39 error::Error,
40+ message,
41 request::{actor_rank, ensure},41 request::{actor_rank, ensure},
42 server_settings, user,42 server_settings, user,
43 };43 };
44 44
45 const COLLECT_INTERVAL: Duration = Duration::from_secs(600);45 const COLLECT_INTERVAL: Duration = Duration::from_secs(600);
46-const STALE_AGE: Duration = Duration::from_millis(HOUR_MILLIS);
47 const MAXIMUM_IMAGE_SIDE: u32 = 16384;46 const MAXIMUM_IMAGE_SIDE: u32 = 16384;
48 const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024;47 const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024;
49 const LIST_LIMIT: i64 = 200;48 const LIST_LIMIT: i64 = 200;
50 const USAGE_LIMIT: i64 = 50;49 const USAGE_LIMIT: i64 = 50;
50+const THUMB_SUFFIX: &str = ".thumb";
51+const PART_SUFFIX: &str = ".part";
51 52
52 pub struct Stored {53 pub struct Stored {
53 pub attachment: Attachment,54 pub attachment: Attachment,
54 pub uploader_id: String,55 pub uploader_id: String,
55 pub community_id: String,56 pub community_id: String,
56 pub message_id: Option<String>,57 pub message_id: Option<String>,
57- pub bound: bool,
58 }58 }
59 59
60-pub fn directory(database_path: &str) -> Result<PathBuf, Error> {60+pub fn sibling_directory(database_path: &str, name: &str) -> Result<PathBuf, Error> {
61 let directory = Path::new(database_path)61 let directory = Path::new(database_path)
62 .parent()62 .parent()
63 .unwrap_or_else(|| Path::new(""))63 .unwrap_or_else(|| Path::new(""))
64- .join("attachments");64+ .join(name);
65 std::fs::create_dir_all(&directory)?;65 std::fs::create_dir_all(&directory)?;
66 66
67 Ok(directory)67 Ok(directory)
68 }68 }
69 69
70+pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
71+ sibling_directory(database_path, "attachments")
72+}
73+
70 fn from_row(row: &Row) -> Result<Attachment, Error> {74 fn from_row(row: &Row) -> Result<Attachment, Error> {
71 let size: i64 = row.get(2)?;75 let size: i64 = row.get(2)?;
72 let kind: String = row.get(3)?;76 let kind: String = row.get(3)?;
@@ -121,14 +125,20 @@ pub async fn bind(
121 (message_id, attachment_id.as_str(), user_id, community_id),125 (message_id, attachment_id.as_str(), user_id, community_id),
122 )126 )
123 .await?;127 .await?;
124- if bound != 1 {128+ message::expect_one(bound)?;
125- return Err(CommonError::NotFound.into());
126- }
127 }129 }
128 130
129 Ok(())131 Ok(())
130 }132 }
131 133
134+fn thumb_path(directory: &Path, id: &str) -> PathBuf {
135+ directory.join(format!("{id}{THUMB_SUFFIX}"))
136+}
137+
138+fn part_path(directory: &Path, id: &str) -> PathBuf {
139+ directory.join(format!("{id}{PART_SUFFIX}"))
140+}
141+
132 fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> {142 fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> {
133 std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop))143 std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop))
134 }144 }
@@ -142,6 +152,17 @@ async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> {
142 Ok(())152 Ok(())
143 }153 }
144 154
155+async fn duplicate_if_exists(source: PathBuf, target: PathBuf) -> Result<(), Error> {
156+ if tokio::fs::try_exists(&source)
157+ .await
158+ .map_err(|_| CommonError::Server)?
159+ {
160+ duplicate(source, target).await?;
161+ }
162+
163+ Ok(())
164+}
165+
145 pub async fn copy(166 pub async fn copy(
146 attachment: &Attachment,167 attachment: &Attachment,
147 message_id: &str,168 message_id: &str,
@@ -170,31 +191,20 @@ pub async fn copy(
170 .await?;191 .await?;
171 192
172 duplicate(directory.join(&attachment.id), directory.join(&id)).await?;193 duplicate(directory.join(&attachment.id), directory.join(&id)).await?;
173- let thumbnail = directory.join(format!("{}.thumb", attachment.id));194+ duplicate_if_exists(
174- if tokio::fs::try_exists(&thumbnail)195+ thumb_path(directory, &attachment.id),
175- .await196+ thumb_path(directory, &id),
176- .map_err(|_| CommonError::Server)?197+ )
177- {198+ .await
178- duplicate(thumbnail, directory.join(format!("{id}.thumb"))).await?;
179- }
180-
181- Ok(())
182 }199 }
183 200
184 pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {201 pub async fn ids_of_message(message_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
185- let mut rows = conn202+ message::ids_where(
186- .query(203+ "SELECT id FROM attachment WHERE message_id = ?1",
187- "SELECT id FROM attachment WHERE message_id = ?1",204+ message_id,
188- (message_id,),205+ conn,
189- )206+ )
190- .await?;207+ .await
191-
192- let mut ids = Vec::new();
193- while let Some(row) = rows.next().await? {
194- ids.push(row.get(0)?);
195- }
196-
197- Ok(ids)
198 }208 }
199 209
200 pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), Error> {210 pub async fn delete(attachment_id: &str, conn: &Connection) -> Result<(), Error> {
@@ -278,15 +288,24 @@ pub async fn usage(conn: &Connection) -> Result<(Vec<Usage>, Vec<CommunityUsage>
278 Ok((users, communities))288 Ok((users, communities))
279 }289 }
280 290
281-async fn bytes_of(sql: &str, id: &str, conn: &Connection) -> Result<u64, Error> {291+async fn over_quota(
282- let mut rows = conn.query(sql, (id,)).await?;292+ sql: &str,
293+ key: &str,
294+ limit: u64,
295+ size: u64,
296+ conn: &Connection,
297+) -> Result<bool, Error> {
298+ if limit == 0 {
299+ return Ok(false);
300+ }
301+ let mut rows = conn.query(sql, (key,)).await?;
283 let row = rows302 let row = rows
284 .next()303 .next()
285 .await?304 .await?
286 .ok_or(turso::Error::QueryReturnedNoRows)?;305 .ok_or(turso::Error::QueryReturnedNoRows)?;
287- let bytes: i64 = row.get(0)?;306+ let used: i64 = row.get(0)?;
288 307
289- Ok(bytes as u64)308+ Ok(used as u64 + size > limit)
290 }309 }
291 310
292 async fn ensure_quota(311 async fn ensure_quota(
@@ -296,47 +315,39 @@ async fn ensure_quota(
296 settings: &ServerSettings,315 settings: &ServerSettings,
297 conn: &Connection,316 conn: &Connection,
298 ) -> Result<(), Error> {317 ) -> Result<(), Error> {
299- if settings.user_quota_bytes > 0 {318+ if over_quota(
300- let used = bytes_of(319+ "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1",
301- "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1",320+ user_id,
302- user_id,321+ settings.user_quota_bytes,
303- conn,322+ size,
304- )323+ conn,
305- .await?;324+ )
306- if used + size > settings.user_quota_bytes {325+ .await?
307- return Err(CommonError::QuotaExceeded.into());326+ {
308- }327+ return Err(CommonError::QuotaExceeded.into());
309 }328 }
310-329+ if over_quota(
311- if settings.community_quota_bytes > 0 {330+ "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?1",
312- let used = bytes_of(331+ community_id,
313- "SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?1",332+ settings.community_quota_bytes,
314- community_id,333+ size,
315- conn,334+ conn,
316- )335+ )
317- .await?;336+ .await?
318- if used + size > settings.community_quota_bytes {337+ {
319- return Err(CommonError::QuotaExceeded.into());338+ return Err(CommonError::QuotaExceeded.into());
320- }
321 }339 }
322 340
323 Ok(())341 Ok(())
324 }342 }
325 343
326 pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {344 pub async fn uploads_of(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
327- let mut rows = conn345+ message::ids_where(
328- .query(346+ "SELECT id FROM attachment WHERE uploader_id = ?1",
329- "SELECT id FROM attachment WHERE uploader_id = ?1",347+ user_id,
330- (user_id,),348+ conn,
331- )349+ )
332- .await?;350+ .await
333-
334- let mut ids = Vec::new();
335- while let Some(row) = rows.next().await? {
336- ids.push(row.get(0)?);
337- }
338-
339- Ok(ids)
340 }351 }
341 352
342 pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Error> {353 pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Error> {
@@ -349,26 +360,24 @@ pub async fn delete_uploads(user_id: &str, conn: &Connection) -> Result<(), Erro
349 pub fn remove_files(attachment_ids: &[String], directory: &Path) {360 pub fn remove_files(attachment_ids: &[String], directory: &Path) {
350 for id in attachment_ids {361 for id in attachment_ids {
351 let _ = std::fs::remove_file(directory.join(id));362 let _ = std::fs::remove_file(directory.join(id));
352- let _ = std::fs::remove_file(directory.join(format!("{id}.thumb")));363+ let _ = std::fs::remove_file(thumb_path(directory, id));
353 }364 }
354 }365 }
355 366
356 pub async fn read(attachment_id: &str, conn: &Connection) -> Result<Stored, Error> {367 pub async fn read(attachment_id: &str, conn: &Connection) -> Result<Stored, Error> {
357 let mut rows = conn368 let mut rows = conn
358 .query(369 .query(
359- "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id IS NOT NULL, message_id FROM attachment WHERE id = ?1",370+ "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id FROM attachment WHERE id = ?1",
360 (attachment_id,),371 (attachment_id,),
361 )372 )
362 .await?;373 .await?;
363 let row = rows.next().await?.ok_or(CommonError::NotFound)?;374 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
364- let bound: i64 = row.get(8)?;
365 375
366 Ok(Stored {376 Ok(Stored {
367 attachment: from_row(&row)?,377 attachment: from_row(&row)?,
368 uploader_id: row.get(6)?,378 uploader_id: row.get(6)?,
369 community_id: row.get(7)?,379 community_id: row.get(7)?,
370- message_id: row.get(9)?,380+ message_id: row.get(8)?,
371- bound: bound != 0,
372 })381 })
373 }382 }
374 383
@@ -488,7 +497,7 @@ pub async fn store<R: AsyncRead + Unpin>(
488 .await?;497 .await?;
489 498
490 let id = new_id();499 let id = new_id();
491- let part = directory.join(format!("{id}.part"));500+ let part = part_path(directory, &id);
492 let path = directory.join(&id);501 let path = directory.join(&id);
493 let head = match receive_body(reader, &part, header.size).await {502 let head = match receive_body(reader, &part, header.size).await {
494 Ok(head) => head,503 Ok(head) => head,
@@ -501,7 +510,7 @@ pub async fn store<R: AsyncRead + Unpin>(
501 510
502 let described = if is_image(&head) {511 let described = if is_image(&head) {
503 let source = path.clone();512 let source = path.clone();
504- let thumbnail = directory.join(format!("{id}.thumb"));513+ let thumbnail = thumb_path(directory, &id);
505 tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail))514 tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail))
506 .await515 .await
507 .ok()516 .ok()
@@ -571,10 +580,10 @@ async fn locate(
571 580
572 let rank = actor_rank(user, &stored.community_id, &conn).await?;581 let rank = actor_rank(user, &stored.community_id, &conn).await?;
573 ensure(permission::can_read(rank))?;582 ensure(permission::can_read(rank))?;
574- ensure(stored.bound || stored.uploader_id == user.id)?;583+ ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?;
575 584
576 let path = if request.thumbnail {585 let path = if request.thumbnail {
577- directory.join(format!("{}.thumb", stored.attachment.id))586+ thumb_path(directory, &stored.attachment.id)
578 } else {587 } else {
579 directory.join(&stored.attachment.id)588 directory.join(&stored.attachment.id)
580 };589 };
@@ -606,7 +615,8 @@ pub async fn download(
606 db: &DB,615 db: &DB,
607 directory: &Path,616 directory: &Path,
608 ) -> Result<(), Error> {617 ) -> Result<(), Error> {
609- let request = receive_download_request(&mut receive_stream).await?;618+ let request: DownloadRequest =
619+ receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?;
610 620
611 match locate(user, &request, db, directory).await {621 match locate(user, &request, db, directory).await {
612 Ok((path, length)) => {622 Ok((path, length)) => {
@@ -637,12 +647,9 @@ pub async fn collect(db: DB, directory: PathBuf) {
637 647
638 async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> {648 async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> {
639 let conn = database::connect(db).await?;649 let conn = database::connect(db).await?;
640- let stale_at = SystemTime::now() - STALE_AGE;650+ let stale_ms = time::now_ms().saturating_sub(HOUR_MILLIS);
641- let stale_secs = stale_at651+ let stale_at = SystemTime::UNIX_EPOCH + Duration::from_millis(stale_ms);
642- .duration_since(SystemTime::UNIX_EPOCH)652+ let stale_id = time::id_bound(stale_ms);
643- .unwrap_or_default()
644- .as_secs();
645- let stale_id = Uuid::new_v7(Timestamp::from_unix_time(stale_secs, 0, 0, 0)).to_string();
646 653
647 conn.execute(654 conn.execute(
648 "DELETE FROM attachment WHERE message_id IS NULL AND id < ?1",655 "DELETE FROM attachment WHERE message_id IS NULL AND id < ?1",
@@ -661,8 +668,8 @@ async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> {
661 let entry = entry?;668 let entry = entry?;
662 let name = entry.file_name().to_string_lossy().into_owned();669 let name = entry.file_name().to_string_lossy().into_owned();
663 let id = name670 let id = name
664- .strip_suffix(".thumb")671+ .strip_suffix(THUMB_SUFFIX)
665- .or_else(|| name.strip_suffix(".part"))672+ .or_else(|| name.strip_suffix(PART_SUFFIX))
666 .unwrap_or(&name);673 .unwrap_or(&name);
667 let stale = entry.metadata()?.modified()? < stale_at;674 let stale = entry.metadata()?.modified()? < stale_at;
668 675
@@ -685,7 +692,7 @@ mod tests {
685 use image::{ImageFormat, RgbImage};692 use image::{ImageFormat, RgbImage};
686 693
687 use crate::{694 use crate::{
688- attachment::store,695+ attachment::{store, thumb_path},
689 community, database, message,696 community, database, message,
690 network::{Services, State},697 network::{Services, State},
691 request::handle,698 request::handle,
@@ -749,6 +756,6 @@ mod tests {
749 assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height));756 assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height));
750 757
751 std::fs::remove_file(directory.join(&attachment.id)).unwrap();758 std::fs::remove_file(directory.join(&attachment.id)).unwrap();
752- std::fs::remove_file(directory.join(format!("{}.thumb", attachment.id))).unwrap();759+ std::fs::remove_file(thumb_path(directory, &attachment.id)).unwrap();
753 }760 }
754 }761 }
crates/server/src/authentication.rsmodified+3 -12
@@ -124,7 +124,7 @@ pub async fn create_account(
124 validate_username(username)?;124 validate_username(username)?;
125 validate_password(password)?;125 validate_password(password)?;
126 126
127- if user::by_username(username, conn).await?.is_some() {127+ if user::is_taken(username, None, conn).await? {
128 return Err(CommonError::Taken.into());128 return Err(CommonError::Taken.into());
129 }129 }
130 130
@@ -176,7 +176,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> {
176 if user::suspended(&user.id, conn).await? {176 if user::suspended(&user.id, conn).await? {
177 return Err(CommonError::Suspended.into());177 return Err(CommonError::Suspended.into());
178 }178 }
179- if !permission::bypasses_limits(user.role) && server_settings::read(conn).await?.maintenance {179+ if !permission::is_builder(user.role) && server_settings::read(conn).await?.maintenance {
180 return Err(CommonError::Maintenance.into());180 return Err(CommonError::Maintenance.into());
181 }181 }
182 182
@@ -184,16 +184,7 @@ async fn admit(user: &User, conn: &Connection) -> Result<(), Error> {
184 }184 }
185 185
186 pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> {186 pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> {
187- let user = {187+ let user = user::by_session_token(token, conn).await?;
188- let mut rows = conn
189- .query(
190- &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user::user_columns("user")),
191- (token,),
192- )
193- .await?;
194- let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?;
195- user::from_row(&row)?
196- };
197 admit(&user, conn).await?;188 admit(&user, conn).await?;
198 seen(&user.id, token, conn).await?;189 seen(&user.id, token, conn).await?;
199 190
crates/server/src/backup.rsmodified+5 -10
@@ -4,7 +4,7 @@ use common::{
4 error::Error as CommonError,4 error::Error as CommonError,
5 model::{AdminAction, BackupInfo, User},5 model::{AdminAction, BackupInfo, User},
6 network::{6 network::{
7- DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_request, send_download_status,7+ DOWNLOAD_REQUEST_MAX_READ_LENGTH, DownloadStatus, receive_decoded, send_download_status,
8 send_encoded,8 send_encoded,
9 },9 },
10 permission,10 permission,
@@ -27,13 +27,7 @@ const PREFIX: &str = "yumush-";
27 const EXTENSION: &str = ".db";27 const EXTENSION: &str = ".db";
28 28
29 pub fn directory(database_path: &str) -> Result<PathBuf, Error> {29 pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
30- let directory = Path::new(database_path)30+ attachment::sibling_directory(database_path, "backups")
31- .parent()
32- .unwrap_or_else(|| Path::new(""))
33- .join("backups");
34- std::fs::create_dir_all(&directory)?;
35-
36- Ok(directory)
37 }31 }
38 32
39 fn created_secs(name: &str) -> Option<u64> {33 fn created_secs(name: &str) -> Option<u64> {
@@ -125,12 +119,13 @@ async fn locate(
125 119
126 pub async fn download(120 pub async fn download(
127 user: Option<&User>,121 user: Option<&User>,
128- receive_stream: RecvStream,122+ mut receive_stream: RecvStream,
129 mut send_stream: SendStream,123 mut send_stream: SendStream,
130 db: &DB,124 db: &DB,
131 directory: &Path,125 directory: &Path,
132 ) -> Result<(), Error> {126 ) -> Result<(), Error> {
133- let request = receive_request(receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?;127+ let request: Request =
128+ receive_decoded(&mut receive_stream, DOWNLOAD_REQUEST_MAX_READ_LENGTH).await?;
134 129
135 match locate(user, request, db, directory).await {130 match locate(user, request, db, directory).await {
136 Ok((path, length)) => {131 Ok((path, length)) => {
crates/server/src/community.rsmodified+17 -35
@@ -1,32 +1,19 @@
1 use common::{1 use common::{
2 error::Error as CommonError,2 error::Error as CommonError,
3 model::{Community, CommunityKind, User},3 model::{Community, CommunityKind, User},
4+ string_enum,
4 validate::validate_community_name,5 validate::validate_community_name,
5 };6 };
6 use turso::{Connection, Row};7 use turso::{Connection, Row};
7 8
8 use crate::{database::new_id, error::Error, user};9 use crate::{database::new_id, error::Error, user};
9 10
10-#[derive(Debug, Clone, Copy, PartialEq, Eq)]11+string_enum! {
11-pub enum Kind {12+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12- Group,13+ Kind {
13- Direct,14+ Group => "group",
14- Notes,15+ Direct => "direct",
15-}16+ Notes => "notes",
16-
17-impl Kind {
18- const ALL: [Self; 3] = [Kind::Group, Kind::Direct, Kind::Notes];
19-
20- pub fn as_str(self) -> &'static str {
21- match self {
22- Kind::Group => "group",
23- Kind::Direct => "direct",
24- Kind::Notes => "notes",
25- }
26- }
27-
28- fn parse(text: &str) -> Option<Self> {
29- Self::ALL.into_iter().find(|kind| kind.as_str() == text)
30 }17 }
31 }18 }
32 19
@@ -35,14 +22,13 @@ type Raw = (String, String, Kind, Option<String>, bool);
35 fn raw_of(row: &Row) -> Result<Raw, Error> {22 fn raw_of(row: &Row) -> Result<Raw, Error> {
36 let text: String = row.get(2)?;23 let text: String = row.get(2)?;
37 let kind = Kind::parse(&text).ok_or(CommonError::Server)?;24 let kind = Kind::parse(&text).ok_or(CommonError::Server)?;
38- let voice_enabled: i64 = row.get(4)?;
39 25
40 Ok((26 Ok((
41 row.get(0)?,27 row.get(0)?,
42 row.get(1)?,28 row.get(1)?,
43 kind,29 kind,
44 row.get(3)?,30 row.get(3)?,
45- voice_enabled != 0,31+ user::bool_at(row, 4)?,
46 ))32 ))
47 }33 }
48 34
@@ -191,20 +177,20 @@ pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Comm
191 pub async fn groups(conn: &Connection) -> Result<Vec<Community>, Error> {177 pub async fn groups(conn: &Connection) -> Result<Vec<Community>, Error> {
192 let mut rows = conn178 let mut rows = conn
193 .query(179 .query(
194- "SELECT id, name, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE",180+ "SELECT id, name, kind, avatar_id, voice_enabled FROM community WHERE kind = ?1 ORDER BY name COLLATE NOCASE",
195 (Kind::Group.as_str(),),181 (Kind::Group.as_str(),),
196 )182 )
197 .await?;183 .await?;
198 184
199 let mut communities = Vec::new();185 let mut communities = Vec::new();
200 while let Some(row) = rows.next().await? {186 while let Some(row) = rows.next().await? {
201- let voice_enabled: i64 = row.get(3)?;187+ let (id, name, _, avatar_id, voice_enabled) = raw_of(&row)?;
202 communities.push(Community {188 communities.push(Community {
203- id: row.get(0)?,189+ id,
204- name: row.get(1)?,190+ name,
205 kind: CommunityKind::Group,191 kind: CommunityKind::Group,
206- avatar_id: row.get(2)?,192+ avatar_id,
207- voice_enabled: voice_enabled != 0,193+ voice_enabled,
208 });194 });
209 }195 }
210 196
@@ -290,10 +276,7 @@ pub async fn is_direct(community_id: &str, conn: &Connection) -> Result<bool, Er
290 }276 }
291 277
292 pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result<bool, Error> {278 pub async fn is_fixed(community_id: &str, conn: &Connection) -> Result<bool, Error> {
293- Ok(matches!(279+ Ok(kind(community_id, conn).await? != Kind::Group)
294- kind(community_id, conn).await?,
295- Kind::Direct | Kind::Notes
296- ))
297 }280 }
298 281
299 pub async fn set_voice_enabled(282 pub async fn set_voice_enabled(
@@ -303,7 +286,7 @@ pub async fn set_voice_enabled(
303 ) -> Result<(), Error> {286 ) -> Result<(), Error> {
304 conn.execute(287 conn.execute(
305 "UPDATE community SET voice_enabled = ?2 WHERE id = ?1",288 "UPDATE community SET voice_enabled = ?2 WHERE id = ?1",
306- (community_id, enabled as i64),289+ (community_id, i64::from(enabled)),
307 )290 )
308 .await?;291 .await?;
309 292
@@ -318,9 +301,8 @@ pub async fn voice_enabled(community_id: &str, conn: &Connection) -> Result<bool
318 )301 )
319 .await?;302 .await?;
320 let row = rows.next().await?.ok_or(CommonError::NotFound)?;303 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
321- let enabled: i64 = row.get(0)?;
322 304
323- Ok(enabled != 0)305+ user::bool_at(&row, 0)
324 }306 }
325 307
326 pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> {308 pub async fn label(community_id: &str, conn: &Connection) -> Result<String, Error> {
crates/server/src/database.rsmodified+14 -0
@@ -306,6 +306,20 @@ pub async fn connect(db: &DB) -> Result<Connection, Error> {
306 Ok(conn)306 Ok(conn)
307 }307 }
308 308
309+pub async fn scalar_i64(
310+ conn: &Connection,
311+ sql: &str,
312+ params: impl turso::IntoParams,
313+) -> Result<i64, Error> {
314+ let mut rows = conn.query(sql, params).await?;
315+ let row = rows
316+ .next()
317+ .await?
318+ .ok_or(turso::Error::QueryReturnedNoRows)?;
319+
320+ Ok(row.get(0)?)
321+}
322+
309 async fn migrate(db: &DB) -> Result<(), Error> {323 async fn migrate(db: &DB) -> Result<(), Error> {
310 let mut conn = connect(db).await?;324 let mut conn = connect(db).await?;
311 let applied = user_version(&conn).await?;325 let applied = user_version(&conn).await?;
crates/server/src/direct.rsmodified+11 -15
@@ -1,10 +1,7 @@
1-use common::{1+use common::model::{Community, Rank};
2- error::Error as CommonError,
3- model::{Community, Rank},
4-};
5 use turso::Connection;2 use turso::Connection;
6 3
7-use crate::{community, error::Error, user, user_community};4+use crate::{community, error::Error, request::ensure, user, user_community};
8 5
9 async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result<Option<String>, Error> {6 async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result<Option<String>, Error> {
10 let mut rows = conn7 let mut rows = conn
@@ -17,14 +14,13 @@ async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result<Option<St
17 Ok(rows.next().await?.map(|row| row.get(0)).transpose()?)14 Ok(rows.next().await?.map(|row| row.get(0)).transpose()?)
18 }15 }
19 16
20-pub async fn open(17+pub enum Opening {
21- me: &str,18+ Created(Community),
22- other: &str,19+ Existing(Community),
23- conn: &mut Connection,20+}
24-) -> Result<(Community, bool), Error> {21+
25- if me == other {22+pub async fn open(me: &str, other: &str, conn: &mut Connection) -> Result<Opening, Error> {
26- return Err(CommonError::Forbidden.into());23+ ensure(me != other)?;
27- }
28 user::read(other, conn).await?;24 user::read(other, conn).await?;
29 25
30 let (user_a, user_b) = if me < other { (me, other) } else { (other, me) };26 let (user_a, user_b) = if me < other { (me, other) } else { (other, me) };
@@ -33,7 +29,7 @@ pub async fn open(
33 let community = community::read(&community_id, me, &tx).await?;29 let community = community::read(&community_id, me, &tx).await?;
34 tx.commit().await?;30 tx.commit().await?;
35 31
36- return Ok((community, false));32+ return Ok(Opening::Existing(community));
37 }33 }
38 34
39 let community_id = community::create_direct(&tx).await?;35 let community_id = community::create_direct(&tx).await?;
@@ -47,5 +43,5 @@ pub async fn open(
47 let community = community::read(&community_id, me, &tx).await?;43 let community = community::read(&community_id, me, &tx).await?;
48 tx.commit().await?;44 tx.commit().await?;
49 45
50- Ok((community, true))46+ Ok(Opening::Created(community))
51 }47 }
crates/server/src/friend.rsmodified+7 -10
@@ -4,7 +4,7 @@ use common::{
4 };4 };
5 use turso::Connection;5 use turso::Connection;
6 6
7-use crate::{error::Error, user};7+use crate::{database, error::Error, request::ensure_with, user};
8 8
9 async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result<Vec<User>, Error> {9 async fn users(sql: &str, user_id: &str, conn: &Connection) -> Result<Vec<User>, Error> {
10 let mut rows = conn.query(sql, (user_id,)).await?;10 let mut rows = conn.query(sql, (user_id,)).await?;
@@ -23,9 +23,7 @@ async fn pair_exists(
23 second: &str,23 second: &str,
24 conn: &Connection,24 conn: &Connection,
25 ) -> Result<bool, Error> {25 ) -> Result<bool, Error> {
26- let mut rows = conn.query(sql, (first, second)).await?;26+ let count = database::scalar_i64(conn, sql, (first, second)).await?;
27- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
28- let count: i64 = row.get(0)?;
29 27
30 Ok(count > 0)28 Ok(count > 0)
31 }29 }
@@ -94,15 +92,14 @@ pub async fn state(user_id: &str, conn: &Connection) -> Result<Friends, Error> {
94 }92 }
95 93
96 pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {94 pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
97- if me == other {95+ ensure_with(me != other, CommonError::Forbidden)?;
98- return Err(CommonError::Forbidden.into());
99- }
100 user::read(other, conn).await?;96 user::read(other, conn).await?;
101 97
102 let tx = conn.transaction().await?;98 let tx = conn.transaction().await?;
103- if is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await? {99+ ensure_with(
104- return Err(CommonError::Taken.into());100+ !(is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await?),
105- }101+ CommonError::Taken,
102+ )?;
106 if is_requested(other, me, &tx).await? {103 if is_requested(other, me, &tx).await? {
107 befriend(me, other, &tx).await?;104 befriend(me, other, &tx).await?;
108 } else {105 } else {
crates/server/src/invitation.rsmodified+14 -17
@@ -1,7 +1,7 @@
1 use common::{error::Error as CommonError, model::Invitation};1 use common::{error::Error as CommonError, model::Invitation};
2 use turso::Connection;2 use turso::Connection;
3 3
4-use crate::{community, error::Error, user};4+use crate::{community, database, error::Error, user};
5 5
6 pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Error> {6 pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Error> {
7 let pairs = {7 let pairs = {
@@ -32,14 +32,12 @@ pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Err
32 }32 }
33 33
34 pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result<bool, Error> {34 pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result<bool, Error> {
35- let mut rows = conn35+ let count = database::scalar_i64(
36- .query(36+ conn,
37- "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2",37+ "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2",
38- (community_id, user_id),38+ (community_id, user_id),
39- )39+ )
40- .await?;40+ .await?;
41- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
42- let count: i64 = row.get(0)?;
43 41
44 Ok(count > 0)42 Ok(count > 0)
45 }43 }
@@ -60,14 +58,13 @@ pub async fn insert(
60 }58 }
61 59
62 pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), Error> {60 pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), Error> {
63- if !exists(community_id, user_id, conn).await? {61+ let mut rows = conn
64- return Err(CommonError::NotFound.into());62+ .query(
65- }63+ "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2 RETURNING community_id",
66- conn.execute(64+ (community_id, user_id),
67- "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2",65+ )
68- (community_id, user_id),66+ .await?;
69- )67+ rows.next().await?.ok_or(CommonError::NotFound)?;
70- .await?;
71 68
72 Ok(())69 Ok(())
73 }70 }
crates/server/src/lib.rsmodified+12 -16
@@ -29,7 +29,7 @@ pub mod voice;
29 #[cfg(test)]29 #[cfg(test)]
30 mod test;30 mod test;
31 31
32-use common::{config::Config, model::Role};32+use common::{config::Config, error::Error as CommonError, model::Role};
33 33
34 use crate::error::Error;34 use crate::error::Error;
35 35
@@ -45,23 +45,16 @@ pub struct ServerConfig {
45 pub key_path: String,45 pub key_path: String,
46 }46 }
47 47
48-impl ServerConfig {
49- fn parse(content: &str) -> Result<Self, Error> {
50- let config = Config::parse(content)?;
51-
52- Ok(Self {
53- database_path: config.get("database_path")?,
54- server_address: config.get("server_address")?,
55- certificate_path: config.get("certificate_path")?,
56- key_path: config.get("key_path")?,
57- })
58- }
59-}
60-
61 fn load_config() -> Result<ServerConfig, Error> {48 fn load_config() -> Result<ServerConfig, Error> {
62 let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?;49 let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?;
50+ let config = Config::parse(&content)?;
63 51
64- ServerConfig::parse(&content)52+ Ok(ServerConfig {
53+ database_path: config.get("database_path")?,
54+ server_address: config.get("server_address")?,
55+ certificate_path: config.get("certificate_path")?,
56+ key_path: config.get("key_path")?,
57+ })
65 }58 }
66 59
67 pub async fn showtime() -> Result<(), Error> {60 pub async fn showtime() -> Result<(), Error> {
@@ -90,7 +83,10 @@ pub async fn set_role(username: &str, role: Role) -> Result<(), Error> {
90 let config = load_config()?;83 let config = load_config()?;
91 let database = database::open(&config.database_path).await?;84 let database = database::open(&config.database_path).await?;
92 let conn = database::connect(&database).await?;85 let conn = database::connect(&database).await?;
93- user::set_role(username, role, &conn).await?;86+ let user = user::by_username(username, &conn)
87+ .await?
88+ .ok_or(CommonError::NotFound)?;
89+ user::set_role_by_id(&user.id, role, &conn).await?;
94 90
95 Ok(())91 Ok(())
96 }92 }
crates/server/src/message.rsmodified+38 -22
@@ -259,6 +259,25 @@ async fn insert(
259 Ok(message_id)259 Ok(message_id)
260 }260 }
261 261
262+pub fn expect_one(affected: u64) -> Result<(), Error> {
263+ if affected != 1 {
264+ return Err(CommonError::NotFound.into());
265+ }
266+
267+ Ok(())
268+}
269+
270+pub async fn ids_where(sql: &str, value: &str, conn: &Connection) -> Result<Vec<String>, Error> {
271+ let mut rows = conn.query(sql, (value,)).await?;
272+
273+ let mut ids = Vec::new();
274+ while let Some(row) = rows.next().await? {
275+ ids.push(row.get(0)?);
276+ }
277+
278+ Ok(ids)
279+}
280+
262 pub async fn ensure_in_community(281 pub async fn ensure_in_community(
263 message_id: &str,282 message_id: &str,
264 community_id: &str,283 community_id: &str,
@@ -410,9 +429,7 @@ pub async fn close_poll(message_id: &str, conn: &Connection) -> Result<Message,
410 (message_id,),429 (message_id,),
411 )430 )
412 .await?;431 .await?;
413- if updated == 0 {432+ expect_one(updated)?;
414- return Err(CommonError::NotFound.into());
415- }
416 433
417 read(message_id, conn).await434 read(message_id, conn).await
418 }435 }
@@ -476,9 +493,7 @@ pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<M
476 (message_id, body),493 (message_id, body),
477 )494 )
478 .await?;495 .await?;
479- if updated == 0 {496+ expect_one(updated)?;
480- return Err(CommonError::NotFound.into());
481- }
482 497
483 read(message_id, conn).await498 read(message_id, conn).await
484 }499 }
@@ -492,16 +507,7 @@ pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Erro
492 }507 }
493 508
494 pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {509 pub async fn ids_of_user(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
495- let mut rows = conn510+ ids_where("SELECT id FROM message WHERE user_id = ?1", user_id, conn).await
496- .query("SELECT id FROM message WHERE user_id = ?1", (user_id,))
497- .await?;
498-
499- let mut ids = Vec::new();
500- while let Some(row) = rows.next().await? {
501- ids.push(row.get(0)?);
502- }
503-
504- Ok(ids)
505 }511 }
506 512
507 pub async fn search(513 pub async fn search(
@@ -512,6 +518,7 @@ pub async fn search(
512 before_ms: Option<u64>,518 before_ms: Option<u64>,
513 conn: &Connection,519 conn: &Connection,
514 ) -> Result<Vec<MessageHit>, Error> {520 ) -> Result<Vec<MessageHit>, Error> {
521+ let (after, before) = time::range_bounds(after_ms, before_ms);
515 let mut rows = conn522 let mut rows = conn
516 .query(523 .query(
517 "SELECT id FROM message WHERE (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR id >= ?4) AND (?5 IS NULL OR id < ?5) ORDER BY id DESC LIMIT ?6",524 "SELECT id FROM message WHERE (?1 IS NULL OR instr(lower(body), lower(?1)) > 0) AND (?2 IS NULL OR user_id = ?2) AND (?3 IS NULL OR community_id = ?3) AND (?4 IS NULL OR id >= ?4) AND (?5 IS NULL OR id < ?5) ORDER BY id DESC LIMIT ?6",
@@ -519,8 +526,8 @@ pub async fn search(
519 text,526 text,
520 user_id,527 user_id,
521 community_id,528 community_id,
522- after_ms.map(time::id_bound),529+ after,
523- before_ms.map(|before| time::id_bound(before + 1)),530+ before,
524 SEARCH_LIMIT as i64,531 SEARCH_LIMIT as i64,
525 ),532 ),
526 )533 )
@@ -548,7 +555,10 @@ pub async fn search(
548 }555 }
549 556
550 async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, Error> {557 async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, Error> {
551- let community_id = &sources[0].community_id;558+ let Some(first) = sources.first() else {
559+ return Ok(None);
560+ };
561+ let community_id = &first.community_id;
552 if sources562 if sources
553 .iter()563 .iter()
554 .any(|source| &source.community_id != community_id)564 .any(|source| &source.community_id != community_id)
@@ -632,15 +642,21 @@ async fn write_snippet(
632 Ok(())642 Ok(())
633 }643 }
634 644
645+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
646+pub enum ForwardMode {
647+ Copy,
648+ Snippet,
649+}
650+
635 pub async fn forward(651 pub async fn forward(
636 user: &User,652 user: &User,
637 community_id: &str,653 community_id: &str,
638 sources: &[Message],654 sources: &[Message],
639- snippet: bool,655+ mode: ForwardMode,
640 directory: &Path,656 directory: &Path,
641 conn: &Connection,657 conn: &Connection,
642 ) -> Result<Vec<Message>, Error> {658 ) -> Result<Vec<Message>, Error> {
643- if !snippet {659+ if mode == ForwardMode::Copy {
644 let mut created = Vec::new();660 let mut created = Vec::new();
645 for source in sources {661 for source in sources {
646 let message_id = insert(&user.id, community_id, &source.body, None, conn).await?;662 let message_id = insert(&user.id, community_id, &source.body, None, conn).await?;
@@ -840,7 +856,7 @@ mod tests {
840 &user,856 &user,
841 &community.id,857 &community.id,
842 &[first, second],858 &[first, second],
843- true,859+ message::ForwardMode::Snippet,
844 &test::directory(),860 &test::directory(),
845 &conn,861 &conn,
846 )862 )
crates/server/src/network.rsmodified+35 -50
@@ -8,9 +8,10 @@ use common::{
8 event::Event as Push,8 event::Event as Push,
9 model::User,9 model::User,
10 network::{10 network::{
11- REQUEST_MAX_READ_LENGTH, StreamKind, receive_request, receive_stream_kind, send_event,11+ REQUEST_MAX_READ_LENGTH, StreamKind, receive_decoded, receive_stream_kind, send_event,
12 send_response,12 send_response,
13 },13 },
14+ request::Request,
14 voice::decode_packet,15 voice::decode_packet,
15 };16 };
16 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};17 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};
@@ -30,7 +31,11 @@ use crate::{
30 const CHANNEL_LENGTH: usize = 2048;31 const CHANNEL_LENGTH: usize = 2048;
31 const SESSION_LENGTH: usize = 64;32 const SESSION_LENGTH: usize = 64;
32 33
33-type Signed = (String, String, Connection);34+struct Signed {
35+ user_id: String,
36+ token: String,
37+ connection: Connection,
38+}
34 39
35 #[derive(Clone, Default)]40 #[derive(Clone, Default)]
36 pub struct Presence(Arc<Mutex<HashMap<usize, Signed>>>);41 pub struct Presence(Arc<Mutex<HashMap<usize, Signed>>>);
@@ -91,7 +96,11 @@ impl Presence {
91 pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) {96 pub fn sign_in(&self, connection: &Connection, user_id: &str, token: &str) {
92 self.0.lock().unwrap().insert(97 self.0.lock().unwrap().insert(
93 connection.stable_id(),98 connection.stable_id(),
94- (user_id.to_string(), token.to_string(), connection.clone()),99+ Signed {
100+ user_id: user_id.to_string(),
101+ token: token.to_string(),
102+ connection: connection.clone(),
103+ },
95 );104 );
96 }105 }
97 106
@@ -105,7 +114,7 @@ impl Presence {
105 .lock()114 .lock()
106 .unwrap()115 .unwrap()
107 .values()116 .values()
108- .map(|(user_id, _, _)| user_id.clone())117+ .map(|signed| signed.user_id.clone())
109 .collect();118 .collect();
110 user_ids.sort();119 user_ids.sort();
111 user_ids.dedup();120 user_ids.dedup();
@@ -117,46 +126,30 @@ impl Presence {
117 self.user_ids().len()126 self.user_ids().len()
118 }127 }
119 128
120- pub fn disconnect(&self, user_id: &str) {129+ fn close_where(&self, matches: impl Fn(&Signed) -> bool, reason: &[u8]) {
121 let connections: Vec<Connection> = self130 let connections: Vec<Connection> = self
122 .0131 .0
123 .lock()132 .lock()
124 .unwrap()133 .unwrap()
125 .values()134 .values()
126- .filter(|(signed_id, _, _)| signed_id == user_id)135+ .filter(|signed| matches(signed))
127- .map(|(_, _, connection)| connection.clone())136+ .map(|signed| signed.connection.clone())
128 .collect();137 .collect();
129 for connection in connections {138 for connection in connections {
130- connection.close(0u32.into(), b"signed out");139+ connection.close(0u32.into(), reason);
131 }140 }
132 }141 }
133 142
143+ pub fn disconnect(&self, user_id: &str) {
144+ self.close_where(|signed| signed.user_id == user_id, b"signed out");
145+ }
146+
134 pub fn disconnect_except(&self, keep: &[String], reason: &[u8]) {147 pub fn disconnect_except(&self, keep: &[String], reason: &[u8]) {
135- let connections: Vec<Connection> = self148+ self.close_where(|signed| !keep.contains(&signed.user_id), reason);
136- .0
137- .lock()
138- .unwrap()
139- .values()
140- .filter(|(signed_id, _, _)| !keep.contains(signed_id))
141- .map(|(_, _, connection)| connection.clone())
142- .collect();
143- for connection in connections {
144- connection.close(0u32.into(), reason);
145- }
146 }149 }
147 150
148 pub fn disconnect_token(&self, token: &str) {151 pub fn disconnect_token(&self, token: &str) {
149- let connections: Vec<Connection> = self152+ self.close_where(|signed| signed.token == token, b"session revoked");
150- .0
151- .lock()
152- .unwrap()
153- .values()
154- .filter(|(_, signed_token, _)| signed_token == token)
155- .map(|(_, _, connection)| connection.clone())
156- .collect();
157- for connection in connections {
158- connection.close(0u32.into(), b"session revoked");
159- }
160 }153 }
161 }154 }
162 155
@@ -279,12 +272,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro
279 .await?;272 .await?;
280 broadcasts273 broadcasts
281 .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?);274 .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?);
282- for broadcast in broadcasts {275+ publish(&shared, broadcasts).await;
283- let _ = shared
284- .event_sender
285- .send(Event::Broadcast(Box::new(broadcast)))
286- .await;
287- }
288 }276 }
289 277
290 Ok(())278 Ok(())
@@ -347,10 +335,10 @@ async fn route(
347 async fn answer(335 async fn answer(
348 connection: Connection,336 connection: Connection,
349 state: Arc<Mutex<State>>,337 state: Arc<Mutex<State>>,
350- (send_stream, receive_stream): (SendStream, RecvStream),338+ (send_stream, mut receive_stream): (SendStream, RecvStream),
351 shared: Shared,339 shared: Shared,
352 ) -> Result<(), Error> {340 ) -> Result<(), Error> {
353- let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?;341+ let request: Request = receive_decoded(&mut receive_stream, REQUEST_MAX_READ_LENGTH).await?;
354 342
355 let before = signed_in(&state);343 let before = signed_in(&state);
356 let (response, broadcasts) = request::handle(344 let (response, broadcasts) = request::handle(
@@ -393,16 +381,20 @@ async fn answer(
393 }381 }
394 }382 }
395 383
384+ publish(&shared, broadcasts).await;
385+
386+ send_response(&response, send_stream).await?;
387+
388+ Ok(())
389+}
390+
391+async fn publish(shared: &Shared, broadcasts: Vec<Broadcast>) {
396 for broadcast in broadcasts {392 for broadcast in broadcasts {
397 let _ = shared393 let _ = shared
398 .event_sender394 .event_sender
399 .send(Event::Broadcast(Box::new(broadcast)))395 .send(Event::Broadcast(Box::new(broadcast)))
400 .await;396 .await;
401 }397 }
402-
403- send_response(&response, send_stream).await?;
404-
405- Ok(())
406 }398 }
407 399
408 async fn broadcast_presence(shared: &Shared, user_id: &str) {400 async fn broadcast_presence(shared: &Shared, user_id: &str) {
@@ -411,14 +403,7 @@ async fn broadcast_presence(shared: &Shared, user_id: &str) {
411 Err(error) => Err(error),403 Err(error) => Err(error),
412 };404 };
413 match broadcasts {405 match broadcasts {
414- Ok(broadcasts) => {406+ Ok(broadcasts) => publish(shared, broadcasts).await,
415- for broadcast in broadcasts {
416- let _ = shared
417- .event_sender
418- .send(Event::Broadcast(Box::new(broadcast)))
419- .await;
420- }
421- }
422 Err(error) => warn!("presence: {error}"),407 Err(error) => warn!("presence: {error}"),
423 }408 }
424 }409 }
crates/server/src/report.rsmodified+11 -12
@@ -5,7 +5,11 @@ use common::{
5 };5 };
6 use turso::Connection;6 use turso::Connection;
7 7
8-use crate::{database::new_id, error::Error, user};8+use crate::{
9+ database::{self, new_id},
10+ error::Error,
11+ user,
12+};
9 13
10 pub async fn is_open(14 pub async fn is_open(
11 reporter_id: &str,15 reporter_id: &str,
@@ -13,17 +17,12 @@ pub async fn is_open(
13 message_id: Option<&str>,17 message_id: Option<&str>,
14 conn: &Connection,18 conn: &Connection,
15 ) -> Result<bool, Error> {19 ) -> Result<bool, Error> {
16- let mut rows = conn20+ let found = database::scalar_i64(
17- .query(21+ conn,
18- "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND COALESCE(message_id, '') = COALESCE(?3, '') AND status = ?4)",22+ "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)",
19- (reporter_id, target_id, message_id, ReportStatus::Open.as_str()),23+ (reporter_id, target_id, message_id, ReportStatus::Open.as_str()),
20- )24+ )
21- .await?;25+ .await?;
22- let row = rows
23- .next()
24- .await?
25- .ok_or(turso::Error::QueryReturnedNoRows)?;
26- let found: i64 = row.get(0)?;
27 26
28 Ok(found != 0)27 Ok(found != 0)
29 }28 }
crates/server/src/request.rsmodified+374 -433
@@ -8,8 +8,8 @@ use common::{
8 error::Error as CommonError,8 error::Error as CommonError,
9 event::Event,9 event::Event,
10 model::{10 model::{
11- AdminAction, CallLog, CommunityKind, CommunitySummary, LogAction, Member, Presence, Rank,11+ AdminAction, BanScope, CallLog, CommunitySummary, LogAction, Member, Message, Presence,
12- ReportStatus, ServerBanKind, ServerSettings, User, VoiceRoom,12+ Rank, ReportStatus, Sanction, ServerBanKind, ServerSettings, User, VoiceRoom,
13 },13 },
14 permission,14 permission,
15 request::Request,15 request::Request,
@@ -32,7 +32,7 @@ use crate::{
32 notes, overview,32 notes, overview,
33 rate_limit::RateLimit,33 rate_limit::RateLimit,
34 report, server_ban, server_settings, stats, user, user_community,34 report, server_ban, server_settings, stats, user, user_community,
35- voice::{CallEnd, GhostChange, Left, Voice},35+ voice::{CallEnd, Left, Voice},
36 };36 };
37 37
38 pub struct Broadcast {38 pub struct Broadcast {
@@ -109,7 +109,8 @@ async fn dispatch(
109 (Response::Done, broadcasts)109 (Response::Done, broadcasts)
110 }110 }
111 Request::Logout => {111 Request::Logout => {
112- let (_, token) = authenticated(state, &conn).await?;112+ authenticated(state, &conn).await?;
113+ let token = session_token(state)?;
113 authentication::logout(&token, &conn).await?;114 authentication::logout(&token, &conn).await?;
114 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;115 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
115 set_state(state, State::Anonymous);116 set_state(state, State::Anonymous);
@@ -123,15 +124,9 @@ async fn dispatch(
123 )124 )
124 }125 }
125 Request::UpdateUser { username } => {126 Request::UpdateUser { username } => {
126- let (me, token) = authenticated(state, &conn).await?;127+ let me = authenticated(state, &conn).await?;
127 let user = user::update(&me.id, &username, &conn).await?;128 let user = user::update(&me.id, &username, &conn).await?;
128- set_state(129+ cache_user(state, user.clone());
129- state,
130- State::Authenticated {
131- user: user.clone(),
132- token,
133- },
134- );
135 let broadcasts = user_updated(&user, &conn).await?;130 let broadcasts = user_updated(&user, &conn).await?;
136 (Response::User(user), broadcasts)131 (Response::User(user), broadcasts)
137 }132 }
@@ -140,8 +135,7 @@ async fn dispatch(
140 Vec::new(),135 Vec::new(),
141 ),136 ),
142 Request::UpdateServerSettings { settings } => {137 Request::UpdateServerSettings { settings } => {
143- let (me, _) = authenticated(state, &conn).await?;138+ let me = builder(state, &conn).await?;
144- ensure(permission::is_builder(me.role))?;
145 validate_server_settings(&settings)?;139 validate_server_settings(&settings)?;
146 let previous = server_settings::read(&conn).await?;140 let previous = server_settings::read(&conn).await?;
147 server_settings::update(&settings, &conn).await?;141 server_settings::update(&settings, &conn).await?;
@@ -170,12 +164,13 @@ async fn dispatch(
170 (Response::ServerSettings(settings), broadcasts)164 (Response::ServerSettings(settings), broadcasts)
171 }165 }
172 Request::SetDevice { name } => {166 Request::SetDevice { name } => {
173- let (_, token) = authenticated(state, &conn).await?;167+ authenticated(state, &conn).await?;
168+ let token = session_token(state)?;
174 authentication::set_device(&token, &name, &conn).await?;169 authentication::set_device(&token, &name, &conn).await?;
175 (Response::Done, Vec::new())170 (Response::Done, Vec::new())
176 }171 }
177 Request::Sessions { user_id } => {172 Request::Sessions { user_id } => {
178- let (me, _) = authenticated(state, &conn).await?;173+ let me = authenticated(state, &conn).await?;
179 managed(&me, &user_id, &conn).await?;174 managed(&me, &user_id, &conn).await?;
180 (175 (
181 Response::Sessions(authentication::sessions(&user_id, &conn).await?),176 Response::Sessions(authentication::sessions(&user_id, &conn).await?),
@@ -186,7 +181,7 @@ async fn dispatch(
186 user_id,181 user_id,
187 session_id,182 session_id,
188 } => {183 } => {
189- let (me, _) = authenticated(state, &conn).await?;184+ let me = authenticated(state, &conn).await?;
190 managed(&me, &user_id, &conn).await?;185 managed(&me, &user_id, &conn).await?;
191 let token = authentication::revoke_session(&user_id, &session_id, &conn).await?;186 let token = authentication::revoke_session(&user_id, &session_id, &conn).await?;
192 presence.disconnect_token(&token);187 presence.disconnect_token(&token);
@@ -201,7 +196,7 @@ async fn dispatch(
201 (Response::Done, Vec::new())196 (Response::Done, Vec::new())
202 }197 }
203 Request::RenameUser { user_id, username } => {198 Request::RenameUser { user_id, username } => {
204- let (me, _) = authenticated(state, &conn).await?;199+ let me = authenticated(state, &conn).await?;
205 let target = managed(&me, &user_id, &conn).await?;200 let target = managed(&me, &user_id, &conn).await?;
206 let user = user::update(&user_id, &username, &conn).await?;201 let user = user::update(&user_id, &username, &conn).await?;
207 admin_log::record(202 admin_log::record(
@@ -218,8 +213,7 @@ async fn dispatch(
218 (Response::User(user), broadcasts)213 (Response::User(user), broadcasts)
219 }214 }
220 Request::CreateUser { username, password } => {215 Request::CreateUser { username, password } => {
221- let (me, _) = authenticated(state, &conn).await?;216+ let me = builder(state, &conn).await?;
222- ensure(permission::is_builder(me.role))?;
223 let user = authentication::create_account(&username, &password, &conn).await?;217 let user = authentication::create_account(&username, &password, &conn).await?;
224 admin_log::record(218 admin_log::record(
225 Some(&me.id),219 Some(&me.id),
@@ -232,8 +226,7 @@ async fn dispatch(
232 (Response::User(user), Vec::new())226 (Response::User(user), Vec::new())
233 }227 }
234 Request::Users => {228 Request::Users => {
235- let (me, _) = authenticated(state, &conn).await?;229+ builder(state, &conn).await?;
236- ensure(permission::is_builder(me.role))?;
237 (Response::Users(user::all(&conn).await?), Vec::new())230 (Response::Users(user::all(&conn).await?), Vec::new())
238 }231 }
239 Request::AdminLogs {232 Request::AdminLogs {
@@ -243,8 +236,7 @@ async fn dispatch(
243 after_ms,236 after_ms,
244 before_ms,237 before_ms,
245 } => {238 } => {
246- let (me, _) = authenticated(state, &conn).await?;239+ builder(state, &conn).await?;
247- ensure(permission::is_builder(me.role))?;
248 (240 (
249 Response::AdminLogs(241 Response::AdminLogs(
250 admin_log::list(242 admin_log::list(
@@ -261,23 +253,21 @@ async fn dispatch(
261 )253 )
262 }254 }
263 Request::DailyStats { days } => {255 Request::DailyStats { days } => {
264- let (me, _) = authenticated(state, &conn).await?;256+ builder(state, &conn).await?;
265- ensure(permission::is_builder(me.role))?;
266 (257 (
267 Response::DailyStats(stats::daily(days, &conn).await?),258 Response::DailyStats(stats::daily(days, &conn).await?),
268 Vec::new(),259 Vec::new(),
269 )260 )
270 }261 }
271 Request::Overview => {262 Request::Overview => {
272- let (me, _) = authenticated(state, &conn).await?;263+ builder(state, &conn).await?;
273- ensure(permission::is_builder(me.role))?;
274 (264 (
275 Response::Overview(overview::read(presence, voice, &conn).await?),265 Response::Overview(overview::read(presence, voice, &conn).await?),
276 Vec::new(),266 Vec::new(),
277 )267 )
278 }268 }
279 Request::SuspendUser { user_id, suspended } => {269 Request::SuspendUser { user_id, suspended } => {
280- let (me, _) = authenticated(state, &conn).await?;270+ let me = authenticated(state, &conn).await?;
281 managed(&me, &user_id, &conn).await?;271 managed(&me, &user_id, &conn).await?;
282 user::set_suspended(&user_id, suspended, &conn).await?;272 user::set_suspended(&user_id, suspended, &conn).await?;
283 let action = if suspended {273 let action = if suspended {
@@ -293,7 +283,7 @@ async fn dispatch(
293 (Response::Done, Vec::new())283 (Response::Done, Vec::new())
294 }284 }
295 Request::RevokeSessions { user_id } => {285 Request::RevokeSessions { user_id } => {
296- let (me, _) = authenticated(state, &conn).await?;286+ let me = authenticated(state, &conn).await?;
297 managed(&me, &user_id, &conn).await?;287 managed(&me, &user_id, &conn).await?;
298 authentication::revoke_sessions(&user_id, &conn).await?;288 authentication::revoke_sessions(&user_id, &conn).await?;
299 presence.disconnect(&user_id);289 presence.disconnect(&user_id);
@@ -308,7 +298,7 @@ async fn dispatch(
308 (Response::Done, Vec::new())298 (Response::Done, Vec::new())
309 }299 }
310 Request::ResetPassword { user_id, password } => {300 Request::ResetPassword { user_id, password } => {
311- let (me, _) = authenticated(state, &conn).await?;301+ let me = authenticated(state, &conn).await?;
312 managed(&me, &user_id, &conn).await?;302 managed(&me, &user_id, &conn).await?;
313 authentication::reset_password(&user_id, &password, &conn).await?;303 authentication::reset_password(&user_id, &password, &conn).await?;
314 presence.disconnect(&user_id);304 presence.disconnect(&user_id);
@@ -323,9 +313,9 @@ async fn dispatch(
323 (Response::Done, Vec::new())313 (Response::Done, Vec::new())
324 }314 }
325 Request::ClearProfile { user_id } => {315 Request::ClearProfile { user_id } => {
326- let (me, _) = authenticated(state, &conn).await?;316+ let me = authenticated(state, &conn).await?;
327 managed(&me, &user_id, &conn).await?;317 managed(&me, &user_id, &conn).await?;
328- user::remove_avatar(&user_id, &mut conn).await?;318+ user::set_avatar(&user_id, None, &mut conn).await?;
329 let user = user::update_status(&user_id, "", &conn).await?;319 let user = user::update_status(&user_id, "", &conn).await?;
330 admin_log::record(320 admin_log::record(
331 Some(&me.id),321 Some(&me.id),
@@ -339,7 +329,7 @@ async fn dispatch(
339 (Response::User(user), broadcasts)329 (Response::User(user), broadcasts)
340 }330 }
341 Request::SetRole { user_id, role } => {331 Request::SetRole { user_id, role } => {
342- let (me, _) = authenticated(state, &conn).await?;332+ let me = authenticated(state, &conn).await?;
343 ensure(permission::can_set_role(me.role, me.id == user_id))?;333 ensure(permission::can_set_role(me.role, me.id == user_id))?;
344 let user = user::set_role_by_id(&user_id, role, &conn).await?;334 let user = user::set_role_by_id(&user_id, role, &conn).await?;
345 admin_log::record(335 admin_log::record(
@@ -357,26 +347,20 @@ async fn dispatch(
357 (Response::User(user), broadcasts)347 (Response::User(user), broadcasts)
358 }348 }
359 Request::UpdateStatus { status } => {349 Request::UpdateStatus { status } => {
360- let (me, token) = authenticated(state, &conn).await?;350+ let me = authenticated(state, &conn).await?;
361 let user = user::update_status(&me.id, &status, &conn).await?;351 let user = user::update_status(&me.id, &status, &conn).await?;
362- set_state(352+ cache_user(state, user.clone());
363- state,
364- State::Authenticated {
365- user: user.clone(),
366- token,
367- },
368- );
369 let broadcasts = user_updated(&user, &conn).await?;353 let broadcasts = user_updated(&user, &conn).await?;
370 (Response::User(user), broadcasts)354 (Response::User(user), broadcasts)
371 }355 }
372 Request::UpdatePresence { presence: chosen } => {356 Request::UpdatePresence { presence: chosen } => {
373- let (me, _) = authenticated(state, &conn).await?;357+ let me = authenticated(state, &conn).await?;
374 user::update_presence(&me.id, chosen, &conn).await?;358 user::update_presence(&me.id, chosen, &conn).await?;
375 let broadcasts = presence_changed(presence, &me.id, &conn).await?;359 let broadcasts = presence_changed(presence, &me.id, &conn).await?;
376 (Response::Done, broadcasts)360 (Response::Done, broadcasts)
377 }361 }
378 Request::ReadPresences => {362 Request::ReadPresences => {
379- let (me, _) = authenticated(state, &conn).await?;363+ let me = authenticated(state, &conn).await?;
380 let mut presences = Vec::new();364 let mut presences = Vec::new();
381 for user_id in related_user_ids(&me.id, &conn).await? {365 for user_id in related_user_ids(&me.id, &conn).await? {
382 let effective = effective_presence(presence, &user_id, &conn).await?;366 let effective = effective_presence(presence, &user_id, &conn).await?;
@@ -387,29 +371,17 @@ async fn dispatch(
387 (Response::Presences(presences), Vec::new())371 (Response::Presences(presences), Vec::new())
388 }372 }
389 Request::UpdateAvatar { image } => {373 Request::UpdateAvatar { image } => {
390- let (me, token) = authenticated(state, &conn).await?;374+ let me = authenticated(state, &conn).await?;
391 validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?;375 validate_avatar_size(&image, server_settings::read(&conn).await?.max_avatar_bytes)?;
392- let user = user::set_avatar(&me.id, &image, &mut conn).await?;376+ let user = user::set_avatar(&me.id, Some(&image), &mut conn).await?;
393- set_state(377+ cache_user(state, user.clone());
394- state,
395- State::Authenticated {
396- user: user.clone(),
397- token,
398- },
399- );
400 let broadcasts = user_updated(&user, &conn).await?;378 let broadcasts = user_updated(&user, &conn).await?;
401 (Response::User(user), broadcasts)379 (Response::User(user), broadcasts)
402 }380 }
403 Request::RemoveAvatar => {381 Request::RemoveAvatar => {
404- let (me, token) = authenticated(state, &conn).await?;382+ let me = authenticated(state, &conn).await?;
405- let user = user::remove_avatar(&me.id, &mut conn).await?;383+ let user = user::set_avatar(&me.id, None, &mut conn).await?;
406- set_state(384+ cache_user(state, user.clone());
407- state,
408- State::Authenticated {
409- user: user.clone(),
410- token,
411- },
412- );
413 let broadcasts = user_updated(&user, &conn).await?;385 let broadcasts = user_updated(&user, &conn).await?;
414 (Response::User(user), broadcasts)386 (Response::User(user), broadcasts)
415 }387 }
@@ -421,7 +393,7 @@ async fn dispatch(
421 )393 )
422 }394 }
423 Request::DeleteUser { user_id } => {395 Request::DeleteUser { user_id } => {
424- let (me, _) = authenticated(state, &conn).await?;396+ let me = authenticated(state, &conn).await?;
425 let target = user::read(&user_id, &conn).await?;397 let target = user::read(&user_id, &conn).await?;
426 ensure(permission::can_delete_user(398 ensure(permission::can_delete_user(
427 me.role,399 me.role,
@@ -445,19 +417,19 @@ async fn dispatch(
445 broadcasts.extend(voice_closed(voice, &community_id, &tx).await?);417 broadcasts.extend(voice_closed(voice, &community_id, &tx).await?);
446 community::delete(&community_id, &user_id, &tx).await?;418 community::delete(&community_id, &user_id, &tx).await?;
447 let event = Event::CommunityDeleted { community_id };419 let event = Event::CommunityDeleted { community_id };
448- broadcasts.extend(broadcast(event, &members));420+ broadcasts.push(broadcast(event, &members));
449 }421 }
450 for community in community::communities_of(&user_id, &tx).await? {422 for community in community::communities_of(&user_id, &tx).await? {
451 let members = user_community::members(&community.id, &tx).await?;423 let members = user_community::members(&community.id, &tx).await?;
452- if matches!(community.kind, CommunityKind::Direct { .. }) {424+ if community.kind.is_direct() {
453 community::delete(&community.id, &user_id, &tx).await?;425 community::delete(&community.id, &user_id, &tx).await?;
454 }426 }
455 let event = Event::UserDeleted {427 let event = Event::UserDeleted {
456 user_id: user_id.clone(),428 user_id: user_id.clone(),
457 };429 };
458- broadcasts.extend(broadcast(event, &members));430+ broadcasts.push(broadcast(event, &members));
459 }431 }
460- broadcasts.extend(leave_voice(voice, &user_id, &tx).await?);432+ broadcasts.extend(leave_user_voice(voice, &user_id, &tx).await?);
461 let deleted = user::delete(&user_id, &tx).await?;433 let deleted = user::delete(&user_id, &tx).await?;
462 tx.commit().await?;434 tx.commit().await?;
463 if me.id == user_id {435 if me.id == user_id {
@@ -466,10 +438,10 @@ async fn dispatch(
466 (Response::User(deleted), broadcasts)438 (Response::User(deleted), broadcasts)
467 }439 }
468 Request::CreateCommunity { name } => {440 Request::CreateCommunity { name } => {
469- let (me, _) = authenticated(state, &conn).await?;441+ let me = authenticated(state, &conn).await?;
470 let limit = server_settings::read(&conn).await?.max_communities_per_user;442 let limit = server_settings::read(&conn).await?.max_communities_per_user;
471 let owned = user_community::owned_groups(&me.id, &conn).await?;443 let owned = user_community::owned_groups(&me.id, &conn).await?;
472- ensure_or(444+ ensure_with(
473 limit == 0 || owned < limit as usize,445 limit == 0 || owned < limit as usize,
474 CommonError::LimitReached,446 CommonError::LimitReached,
475 )?;447 )?;
@@ -481,21 +453,17 @@ async fn dispatch(
481 (Response::Community(community), Vec::new())453 (Response::Community(community), Vec::new())
482 }454 }
483 Request::ReadCommunity { community_id } => {455 Request::ReadCommunity { community_id } => {
484- let (me, _) = authenticated(state, &conn).await?;456+ let me = authenticated(state, &conn).await?;
485- ensure(permission::can_read(457+ allowed(&me, &community_id, &conn, permission::can_read).await?;
486- actor_rank(&me, &community_id, &conn).await?,
487- ))?;
488 (458 (
489 Response::Community(community::read(&community_id, &me.id, &conn).await?),459 Response::Community(community::read(&community_id, &me.id, &conn).await?),
490 Vec::new(),460 Vec::new(),
491 )461 )
492 }462 }
493 Request::UpdateCommunity { community_id, name } => {463 Request::UpdateCommunity { community_id, name } => {
494- let (me, _) = authenticated(state, &conn).await?;464+ let me = authenticated(state, &conn).await?;
495- ensure(!community::is_fixed(&community_id, &conn).await?)?;465+ ensure_editable(&community_id, &conn).await?;
496- ensure(permission::can_rename_community(466+ allowed(&me, &community_id, &conn, permission::can_rename_community).await?;
497- actor_rank(&me, &community_id, &conn).await?,
498- ))?;
499 let updated = community::update(&community_id, &name, &me.id, &conn).await?;467 let updated = community::update(&community_id, &name, &me.id, &conn).await?;
500 let action = LogAction::Renamed {468 let action = LogAction::Renamed {
501 name: updated.name.clone(),469 name: updated.name.clone(),
@@ -503,17 +471,15 @@ async fn dispatch(
503 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;471 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
504 let members = user_community::members(&community_id, &conn).await?;472 let members = user_community::members(&community_id, &conn).await?;
505 let event = Event::CommunityUpdated(updated.clone());473 let event = Event::CommunityUpdated(updated.clone());
506- (Response::Community(updated), broadcast(event, &members))474+ (Response::Community(updated), vec![broadcast(event, &members)])
507 }475 }
508 Request::UpdateCommunityAvatar {476 Request::UpdateCommunityAvatar {
509 community_id,477 community_id,
510 image,478 image,
511 } => {479 } => {
512- let (me, _) = authenticated(state, &conn).await?;480+ let me = authenticated(state, &conn).await?;
513- ensure(!community::is_fixed(&community_id, &conn).await?)?;481+ ensure_editable(&community_id, &conn).await?;
514- ensure(permission::can_rename_community(482+ allowed(&me, &community_id, &conn, permission::can_rename_community).await?;
515- actor_rank(&me, &community_id, &conn).await?,
516- ))?;
517 if let Some(bytes) = &image {483 if let Some(bytes) = &image {
518 validate_avatar_size(bytes, server_settings::read(&conn).await?.max_avatar_bytes)?;484 validate_avatar_size(bytes, server_settings::read(&conn).await?.max_avatar_bytes)?;
519 }485 }
@@ -527,14 +493,12 @@ async fn dispatch(
527 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;493 log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
528 let members = user_community::members(&community_id, &conn).await?;494 let members = user_community::members(&community_id, &conn).await?;
529 let event = Event::CommunityUpdated(updated.clone());495 let event = Event::CommunityUpdated(updated.clone());
530- (Response::Community(updated), broadcast(event, &members))496+ (Response::Community(updated), vec![broadcast(event, &members)])
531 }497 }
532 Request::DeleteCommunity { community_id } => {498 Request::DeleteCommunity { community_id } => {
533- let (me, _) = authenticated(state, &conn).await?;499+ let me = authenticated(state, &conn).await?;
534- ensure(!community::is_fixed(&community_id, &conn).await?)?;500+ ensure_editable(&community_id, &conn).await?;
535- ensure(permission::can_delete_community(501+ allowed(&me, &community_id, &conn, permission::can_delete_community).await?;
536- actor_rank(&me, &community_id, &conn).await?,
537- ))?;
538 let tx = conn.transaction().await?;502 let tx = conn.transaction().await?;
539 let members = user_community::members(&community_id, &tx).await?;503 let members = user_community::members(&community_id, &tx).await?;
540 let owned =504 let owned =
@@ -555,15 +519,13 @@ async fn dispatch(
555 let event = Event::CommunityDeleted {519 let event = Event::CommunityDeleted {
556 community_id: deleted.id.clone(),520 community_id: deleted.id.clone(),
557 };521 };
558- broadcasts.extend(broadcast(event, &members));522+ broadcasts.push(broadcast(event, &members));
559 (Response::Community(deleted), broadcasts)523 (Response::Community(deleted), broadcasts)
560 }524 }
561 Request::LeaveCommunity { community_id } => {525 Request::LeaveCommunity { community_id } => {
562- let (me, _) = authenticated(state, &conn).await?;526+ let me = authenticated(state, &conn).await?;
563- ensure(!community::is_fixed(&community_id, &conn).await?)?;527+ ensure_editable(&community_id, &conn).await?;
564- ensure(permission::can_leave(528+ allowed(&me, &community_id, &conn, permission::can_leave).await?;
565- actor_rank(&me, &community_id, &conn).await?,
566- ))?;
567 let tx = conn.transaction().await?;529 let tx = conn.transaction().await?;
568 user_community::leave(&me.id, &community_id, &tx).await?;530 user_community::leave(&me.id, &community_id, &tx).await?;
569 log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?;531 log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?;
@@ -572,26 +534,24 @@ async fn dispatch(
572 community::delete(&community_id, &me.id, &tx).await?;534 community::delete(&community_id, &me.id, &tx).await?;
573 }535 }
574 tx.commit().await?;536 tx.commit().await?;
575- let mut broadcasts = voice_leave(voice, &community_id, &me.id, &conn).await?;537+ let mut broadcasts = leave_room_voice(voice, &community_id, &me.id, &conn).await?;
576 let event = Event::MemberLeft {538 let event = Event::MemberLeft {
577 community_id,539 community_id,
578 user_id: me.id,540 user_id: me.id,
579 };541 };
580- broadcasts.extend(broadcast(event, &members));542+ broadcasts.push(broadcast(event, &members));
581 (Response::Done, broadcasts)543 (Response::Done, broadcasts)
582 }544 }
583 Request::Communities => {545 Request::Communities => {
584- let (me, _) = authenticated(state, &conn).await?;546+ let me = authenticated(state, &conn).await?;
585 (547 (
586 Response::Communities(community::communities_of(&me.id, &conn).await?),548 Response::Communities(community::communities_of(&me.id, &conn).await?),
587 Vec::new(),549 Vec::new(),
588 )550 )
589 }551 }
590 Request::Members { community_id } => {552 Request::Members { community_id } => {
591- let (me, _) = authenticated(state, &conn).await?;553+ let me = authenticated(state, &conn).await?;
592- ensure(permission::can_read(554+ allowed(&me, &community_id, &conn, permission::can_read).await?;
593- actor_rank(&me, &community_id, &conn).await?,
594- ))?;
595 (555 (
596 Response::Members(user_community::members(&community_id, &conn).await?),556 Response::Members(user_community::members(&community_id, &conn).await?),
597 Vec::new(),557 Vec::new(),
@@ -602,14 +562,14 @@ async fn dispatch(
602 user_id,562 user_id,
603 reason,563 reason,
604 } => {564 } => {
605- let (me, _) = authenticated(state, &conn).await?;565+ let me = authenticated(state, &conn).await?;
606 remove_member(566 remove_member(
607 &me,567 &me,
608 Removal {568 Removal {
609 community_id,569 community_id,
610 user_id,570 user_id,
611 reason,571 reason,
612- banned: false,572+ sanction: Sanction::Kick,
613 },573 },
614 voice,574 voice,
615 &mut conn,575 &mut conn,
@@ -621,14 +581,14 @@ async fn dispatch(
621 user_id,581 user_id,
622 reason,582 reason,
623 } => {583 } => {
624- let (me, _) = authenticated(state, &conn).await?;584+ let me = authenticated(state, &conn).await?;
625 remove_member(585 remove_member(
626 &me,586 &me,
627 Removal {587 Removal {
628 community_id,588 community_id,
629 user_id,589 user_id,
630 reason,590 reason,
631- banned: true,591+ sanction: Sanction::Ban,
632 },592 },
633 voice,593 voice,
634 &mut conn,594 &mut conn,
@@ -639,10 +599,8 @@ async fn dispatch(
639 community_id,599 community_id,
640 user_id,600 user_id,
641 } => {601 } => {
642- let (me, _) = authenticated(state, &conn).await?;602+ let me = authenticated(state, &conn).await?;
643- ensure(permission::can_unban(603+ allowed(&me, &community_id, &conn, permission::can_unban).await?;
644- actor_rank(&me, &community_id, &conn).await?,
645- ))?;
646 user_community::unban(&user_id, &community_id, &conn).await?;604 user_community::unban(&user_id, &community_id, &conn).await?;
647 log::record(605 log::record(
648 &community_id,606 &community_id,
@@ -655,10 +613,8 @@ async fn dispatch(
655 (Response::Done, Vec::new())613 (Response::Done, Vec::new())
656 }614 }
657 Request::Bans { community_id } => {615 Request::Bans { community_id } => {
658- let (me, _) = authenticated(state, &conn).await?;616+ let me = authenticated(state, &conn).await?;
659- ensure(permission::can_unban(617+ allowed(&me, &community_id, &conn, permission::can_unban).await?;
660- actor_rank(&me, &community_id, &conn).await?,
661- ))?;
662 (618 (
663 Response::Bans(user_community::bans(&community_id, &conn).await?),619 Response::Bans(user_community::bans(&community_id, &conn).await?),
664 Vec::new(),620 Vec::new(),
@@ -669,8 +625,8 @@ async fn dispatch(
669 user_id,625 user_id,
670 rank,626 rank,
671 } => {627 } => {
672- let (me, _) = authenticated(state, &conn).await?;628+ let me = authenticated(state, &conn).await?;
673- ensure(!community::is_fixed(&community_id, &conn).await?)?;629+ ensure_editable(&community_id, &conn).await?;
674 let target = user::read(&user_id, &conn).await?;630 let target = user::read(&user_id, &conn).await?;
675 ensure(permission::can_set_rank(631 ensure(permission::can_set_rank(
676 actor_rank(&me, &community_id, &conn).await?,632 actor_rank(&me, &community_id, &conn).await?,
@@ -692,7 +648,7 @@ async fn dispatch(
692 user_id,648 user_id,
693 rank,649 rank,
694 };650 };
695- (Response::Done, broadcast(event, &members))651+ (Response::Done, vec![broadcast(event, &members)])
696 }652 }
697 Request::CreateMessage {653 Request::CreateMessage {
698 community_id,654 community_id,
@@ -700,7 +656,7 @@ async fn dispatch(
700 attachments,656 attachments,
701 reply_to,657 reply_to,
702 } => {658 } => {
703- let (me, _) = authenticated(state, &conn).await?;659+ let me = authenticated(state, &conn).await?;
704 let settings = server_settings::read(&conn).await?;660 let settings = server_settings::read(&conn).await?;
705 limit_messages(&me, rate_limit, &settings)?;661 limit_messages(&me, rate_limit, &settings)?;
706 validate_new_message(662 validate_new_message(
@@ -708,9 +664,7 @@ async fn dispatch(
708 attachments.len(),664 attachments.len(),
709 settings.max_message_length as usize,665 settings.max_message_length as usize,
710 )?;666 )?;
711- ensure(permission::can_post(667+ allowed(&me, &community_id, &conn, permission::can_post).await?;
712- actor_rank(&me, &community_id, &conn).await?,
713- ))?;
714 let tx = conn.transaction().await?;668 let tx = conn.transaction().await?;
715 let created = message::create(669 let created = message::create(
716 &me.id,670 &me.id,
@@ -723,19 +677,16 @@ async fn dispatch(
723 .await?;677 .await?;
724 stats::mark_active(&me.id, &tx).await?;678 stats::mark_active(&me.id, &tx).await?;
725 tx.commit().await?;679 tx.commit().await?;
726- let members = user_community::members(&community_id, &conn).await?;680+ let broadcast =
727- let event = Event::MessageCreated(created.clone());681+ message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?;
728- (682+ (Response::Message(created), vec![broadcast])
729- Response::Message(created),
730- broadcast_with(event, &members, &me.id),
731- )
732 }683 }
733 Request::ForwardMessages {684 Request::ForwardMessages {
734 message_ids,685 message_ids,
735 community_id,686 community_id,
736 snippet,687 snippet,
737 } => {688 } => {
738- let (me, _) = authenticated(state, &conn).await?;689+ let me = authenticated(state, &conn).await?;
739 limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?;690 limit_messages(&me, rate_limit, &server_settings::read(&conn).await?)?;
740 validate_forward(message_ids.len())?;691 validate_forward(message_ids.len())?;
741 ensure(permission::can_post(692 ensure(permission::can_post(
@@ -750,32 +701,34 @@ async fn dispatch(
750 ))?;701 ))?;
751 sources.push(source);702 sources.push(source);
752 }703 }
704+ let mode = if snippet {
705+ message::ForwardMode::Snippet
706+ } else {
707+ message::ForwardMode::Copy
708+ };
753 let created =709 let created =
754- message::forward(&me, &community_id, &sources, snippet, directory, &tx).await?;710+ message::forward(&me, &community_id, &sources, mode, directory, &tx).await?;
755 tx.commit().await?;711 tx.commit().await?;
756 let members = user_community::members(&community_id, &conn).await?;712 let members = user_community::members(&community_id, &conn).await?;
757 let mut broadcasts = Vec::new();713 let mut broadcasts = Vec::new();
758 for message in &created {714 for message in &created {
759 let event = Event::MessageCreated(message.clone());715 let event = Event::MessageCreated(message.clone());
760- broadcasts.extend(broadcast_with(event, &members, &me.id));716+ broadcasts.push(broadcast_with(event, &members, &me.id));
761 }717 }
762 (Response::Messages(created), broadcasts)718 (Response::Messages(created), broadcasts)
763 }719 }
764 Request::UpdateMessage { message_id, body } => {720 Request::UpdateMessage { message_id, body } => {
765- let (me, _) = authenticated(state, &conn).await?;721+ let me = authenticated(state, &conn).await?;
766 let existing = message::read(&message_id, &conn).await?;722 let existing = message::read(&message_id, &conn).await?;
767- ensure(permission::can_edit_message(existing.user_id == me.id))?;723+ ensure(existing.user_id == me.id)?;
768 validate_message_body(724 validate_message_body(
769 &body,725 &body,
770 server_settings::read(&conn).await?.max_message_length as usize,726 server_settings::read(&conn).await?.max_message_length as usize,
771 )?;727 )?;
772 let updated = message::update(&message_id, &body, &conn).await?;728 let updated = message::update(&message_id, &body, &conn).await?;
773- let members = user_community::members(&updated.community_id, &conn).await?;729+ let broadcast =
774- let event = Event::MessageUpdated(updated.clone());730+ message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?;
775- (731+ (Response::Message(updated), vec![broadcast])
776- Response::Message(updated),
777- broadcast_with(event, &members, &me.id),
778- )
779 }732 }
780 Request::CreatePoll {733 Request::CreatePoll {
781 community_id,734 community_id,
@@ -783,31 +736,26 @@ async fn dispatch(
783 options,736 options,
784 multiple,737 multiple,
785 } => {738 } => {
786- let (me, _) = authenticated(state, &conn).await?;739+ let me = authenticated(state, &conn).await?;
787 let settings = server_settings::read(&conn).await?;740 let settings = server_settings::read(&conn).await?;
788 limit_messages(&me, rate_limit, &settings)?;741 limit_messages(&me, rate_limit, &settings)?;
789 validate_poll(&question, &options)?;742 validate_poll(&question, &options)?;
790- ensure(permission::can_post(743+ allowed(&me, &community_id, &conn, permission::can_post).await?;
791- actor_rank(&me, &community_id, &conn).await?,
792- ))?;
793 let tx = conn.transaction().await?;744 let tx = conn.transaction().await?;
794 let created =745 let created =
795 message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx)746 message::create_poll(&me.id, &community_id, &question, &options, multiple, &tx)
796 .await?;747 .await?;
797 stats::mark_active(&me.id, &tx).await?;748 stats::mark_active(&me.id, &tx).await?;
798 tx.commit().await?;749 tx.commit().await?;
799- let members = user_community::members(&community_id, &conn).await?;750+ let broadcast =
800- let event = Event::MessageCreated(created.clone());751+ message_broadcast(&created, Event::MessageCreated, &me.id, &conn).await?;
801- (752+ (Response::Message(created), vec![broadcast])
802- Response::Message(created),
803- broadcast_with(event, &members, &me.id),
804- )
805 }753 }
806 Request::Vote {754 Request::Vote {
807 message_id,755 message_id,
808 positions,756 positions,
809 } => {757 } => {
810- let (me, _) = authenticated(state, &conn).await?;758+ let me = authenticated(state, &conn).await?;
811 let existing = message::read(&message_id, &conn).await?;759 let existing = message::read(&message_id, &conn).await?;
812 ensure(permission::can_read(760 ensure(permission::can_read(
813 actor_rank(&me, &existing.community_id, &conn).await?,761 actor_rank(&me, &existing.community_id, &conn).await?,
@@ -815,36 +763,36 @@ async fn dispatch(
815 let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?;763 let poll = existing.poll.as_ref().ok_or(CommonError::NotFound)?;
816 validate_vote(poll, &positions)?;764 validate_vote(poll, &positions)?;
817 let updated = message::vote(&message_id, &me.id, &positions, &conn).await?;765 let updated = message::vote(&message_id, &me.id, &positions, &conn).await?;
818- let members = user_community::members(&updated.community_id, &conn).await?;766+ let broadcast =
819- let event = Event::MessageUpdated(updated);767+ message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?;
820- (Response::Done, broadcast_with(event, &members, &me.id))768+ (Response::Done, vec![broadcast])
821 }769 }
822 Request::ClosePoll { message_id } => {770 Request::ClosePoll { message_id } => {
823- let (me, _) = authenticated(state, &conn).await?;771+ let me = authenticated(state, &conn).await?;
824 let existing = message::read(&message_id, &conn).await?;772 let existing = message::read(&message_id, &conn).await?;
825 ensure(permission::can_close_poll(773 ensure(permission::can_close_poll(
826 actor_rank(&me, &existing.community_id, &conn).await?,774 actor_rank(&me, &existing.community_id, &conn).await?,
827 existing.user_id == me.id,775 existing.user_id == me.id,
828 ))?;776 ))?;
829 let updated = message::close_poll(&message_id, &conn).await?;777 let updated = message::close_poll(&message_id, &conn).await?;
830- let members = user_community::members(&updated.community_id, &conn).await?;778+ let broadcast =
831- let event = Event::MessageUpdated(updated);779+ message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?;
832- (Response::Done, broadcast_with(event, &members, &me.id))780+ (Response::Done, vec![broadcast])
833 }781 }
834 Request::React { message_id, emoji } => {782 Request::React { message_id, emoji } => {
835- let (me, _) = authenticated(state, &conn).await?;783+ let me = authenticated(state, &conn).await?;
836 validate_reaction(&emoji)?;784 validate_reaction(&emoji)?;
837 let existing = message::read(&message_id, &conn).await?;785 let existing = message::read(&message_id, &conn).await?;
838 ensure(permission::can_read(786 ensure(permission::can_read(
839 actor_rank(&me, &existing.community_id, &conn).await?,787 actor_rank(&me, &existing.community_id, &conn).await?,
840 ))?;788 ))?;
841 let updated = message::react(&message_id, &me.id, &emoji, &conn).await?;789 let updated = message::react(&message_id, &me.id, &emoji, &conn).await?;
842- let members = user_community::members(&updated.community_id, &conn).await?;790+ let broadcast =
843- let event = Event::MessageUpdated(updated);791+ message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?;
844- (Response::Done, broadcast_with(event, &members, &me.id))792+ (Response::Done, vec![broadcast])
845 }793 }
846 Request::Pin { message_id, pinned } => {794 Request::Pin { message_id, pinned } => {
847- let (me, _) = authenticated(state, &conn).await?;795+ let me = authenticated(state, &conn).await?;
848 let existing = message::read(&message_id, &conn).await?;796 let existing = message::read(&message_id, &conn).await?;
849 let direct = community::is_direct(&existing.community_id, &conn).await?;797 let direct = community::is_direct(&existing.community_id, &conn).await?;
850 ensure(permission::can_pin(798 ensure(permission::can_pin(
@@ -852,12 +800,12 @@ async fn dispatch(
852 direct,800 direct,
853 ))?;801 ))?;
854 let updated = message::pin(&message_id, pinned, &conn).await?;802 let updated = message::pin(&message_id, pinned, &conn).await?;
855- let members = user_community::members(&updated.community_id, &conn).await?;803+ let broadcast =
856- let event = Event::MessageUpdated(updated);804+ message_broadcast(&updated, Event::MessageUpdated, &me.id, &conn).await?;
857- (Response::Done, broadcast_with(event, &members, &me.id))805+ (Response::Done, vec![broadcast])
858 }806 }
859 Request::Unreads => {807 Request::Unreads => {
860- let (me, _) = authenticated(state, &conn).await?;808+ let me = authenticated(state, &conn).await?;
861 (809 (
862 Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?),810 Response::Unreads(user_community::unreads(&me.id, &me.username, &conn).await?),
863 Vec::new(),811 Vec::new(),
@@ -867,28 +815,22 @@ async fn dispatch(
867 community_id,815 community_id,
868 message_id,816 message_id,
869 } => {817 } => {
870- let (me, _) = authenticated(state, &conn).await?;818+ let me = authenticated(state, &conn).await?;
871- ensure(819+ ensure(!is_outsider(&me.id, &community_id, &conn).await?)?;
872- user_community::rank(&me.id, &community_id, &conn)
873- .await?
874- .is_some(),
875- )?;
876 message::ensure_in_community(&message_id, &community_id, &conn).await?;820 message::ensure_in_community(&message_id, &community_id, &conn).await?;
877 user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?;821 user_community::mark_read(&me.id, &community_id, &message_id, &conn).await?;
878 (Response::Done, Vec::new())822 (Response::Done, Vec::new())
879 }823 }
880 Request::Pins { community_id } => {824 Request::Pins { community_id } => {
881- let (me, _) = authenticated(state, &conn).await?;825+ let me = authenticated(state, &conn).await?;
882- ensure(permission::can_read(826+ allowed(&me, &community_id, &conn, permission::can_read).await?;
883- actor_rank(&me, &community_id, &conn).await?,
884- ))?;
885 (827 (
886 Response::Messages(message::pinned(&community_id, &conn).await?),828 Response::Messages(message::pinned(&community_id, &conn).await?),
887 Vec::new(),829 Vec::new(),
888 )830 )
889 }831 }
890 Request::DeleteMessage { message_id } => {832 Request::DeleteMessage { message_id } => {
891- let (me, _) = authenticated(state, &conn).await?;833+ let me = authenticated(state, &conn).await?;
892 let existing = message::read(&message_id, &conn).await?;834 let existing = message::read(&message_id, &conn).await?;
893 let author = user::read(&existing.user_id, &conn).await?;835 let author = user::read(&existing.user_id, &conn).await?;
894 ensure(permission::can_delete_message(836 ensure(permission::can_delete_message(
@@ -918,24 +860,17 @@ async fn dispatch(
918 )860 )
919 .await?;861 .await?;
920 }862 }
921- let members = user_community::members(&deleted.community_id, &conn).await?;863+ let broadcast =
922- let event = Event::MessageDeleted(deleted.clone());864+ message_broadcast(&deleted, Event::MessageDeleted, &me.id, &conn).await?;
923- (865+ (Response::Message(deleted), vec![broadcast])
924- Response::Message(deleted),
925- broadcast_with(event, &members, &me.id),
926- )
927 }866 }
928 Request::ReadMessages {867 Request::ReadMessages {
929 community_id,868 community_id,
930 before,869 before,
931 } => {870 } => {
932- let (me, _) = authenticated(state, &conn).await?;871+ let me = authenticated(state, &conn).await?;
933- ensure(permission::can_read(872+ allowed(&me, &community_id, &conn, permission::can_read).await?;
934- actor_rank(&me, &community_id, &conn).await?,873+ let outsider = is_outsider(&me.id, &community_id, &conn).await?;
935- ))?;
936- let outsider = user_community::rank(&me.id, &community_id, &conn)
937- .await?
938- .is_none();
939 if before.is_none()874 if before.is_none()
940 && let Some(connection) = connection875 && let Some(connection) = connection
941 {876 {
@@ -966,10 +901,8 @@ async fn dispatch(
966 (Response::Messages(messages), Vec::new())901 (Response::Messages(messages), Vec::new())
967 }902 }
968 Request::JoinVoice { community_id } => {903 Request::JoinVoice { community_id } => {
969- let (me, _) = authenticated(state, &conn).await?;904+ let me = authenticated(state, &conn).await?;
970- ensure(permission::can_join_voice(905+ allowed(&me, &community_id, &conn, permission::can_join_voice).await?;
971- actor_rank(&me, &community_id, &conn).await?,
972- ))?;
973 ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?;906 ensure(community::kind(&community_id, &conn).await? != community::Kind::Notes)?;
974 ensure(907 ensure(
975 permission::is_builder(me.role)908 permission::is_builder(me.role)
@@ -980,9 +913,7 @@ async fn dispatch(
980 };913 };
981 let members = user_community::members(&community_id, &conn).await?;914 let members = user_community::members(&community_id, &conn).await?;
982 let muted = user::voice_muted(&me.id, &conn).await?;915 let muted = user::voice_muted(&me.id, &conn).await?;
983- let outsider = user_community::rank(&me.id, &community_id, &conn)916+ let outsider = is_outsider(&me.id, &community_id, &conn).await?;
984- .await?
985- .is_none();
986 let ghost = outsider || user::is_ghost(&me.id, &conn).await?;917 let ghost = outsider || user::is_ghost(&me.id, &conn).await?;
987 let starts_call = !ghost918 let starts_call = !ghost
988 && community::is_direct(&community_id, &conn).await?919 && community::is_direct(&community_id, &conn).await?
@@ -996,21 +927,10 @@ async fn dispatch(
996 let created =927 let created =
997 message::create_call_log(&community_id, &me.id, CallLog::Started, &conn)928 message::create_call_log(&community_id, &me.id, CallLog::Started, &conn)
998 .await?;929 .await?;
999- broadcasts.extend(broadcast(Event::MessageCreated(created), &members));930+ broadcasts.push(broadcast(Event::MessageCreated(created), &members));
1000 }931 }
1001 if !ghost {932 if !ghost {
1002- let event = Event::VoiceJoined {933+ broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members));
1003- community_id: community_id.clone(),
1004- user_id: me.id.clone(),
1005- };
1006- broadcasts.extend(broadcast(event, &members));
1007- if muted {
1008- let event = Event::VoiceMuted {
1009- user_id: me.id.clone(),
1010- muted,
1011- };
1012- broadcasts.extend(broadcast(event, &members));
1013- }
1014 }934 }
1015 (935 (
1016 Response::Voice(voice.participants(&community_id)),936 Response::Voice(voice.participants(&community_id)),
@@ -1018,10 +938,8 @@ async fn dispatch(
1018 )938 )
1019 }939 }
1020 Request::Typing { community_id } => {940 Request::Typing { community_id } => {
1021- let (me, _) = authenticated(state, &conn).await?;941+ let me = authenticated(state, &conn).await?;
1022- ensure(permission::can_read(942+ allowed(&me, &community_id, &conn, permission::can_read).await?;
1023- actor_rank(&me, &community_id, &conn).await?,
1024- ))?;
1025 let broadcasts = if user::is_ghost(&me.id, &conn).await? {943 let broadcasts = if user::is_ghost(&me.id, &conn).await? {
1026 Vec::new()944 Vec::new()
1027 } else {945 } else {
@@ -1034,7 +952,7 @@ async fn dispatch(
1034 community_id,952 community_id,
1035 user_id: me.id.clone(),953 user_id: me.id.clone(),
1036 };954 };
1037- broadcast(event, &members)955+ vec![broadcast(event, &members)]
1038 };956 };
1039 (Response::Done, broadcasts)957 (Response::Done, broadcasts)
1040 }958 }
@@ -1046,11 +964,9 @@ async fn dispatch(
1046 )964 )
1047 }965 }
1048 Request::DeclineCall { community_id } => {966 Request::DeclineCall { community_id } => {
1049- let (me, _) = authenticated(state, &conn).await?;967+ let me = authenticated(state, &conn).await?;
1050 ensure(community::is_direct(&community_id, &conn).await?)?;968 ensure(community::is_direct(&community_id, &conn).await?)?;
1051- ensure(permission::can_read(969+ allowed(&me, &community_id, &conn, permission::can_read).await?;
1052- actor_rank(&me, &community_id, &conn).await?,
1053- ))?;
1054 let participants = voice.participants(&community_id);970 let participants = voice.participants(&community_id);
1055 ensure(!participants.is_empty() && !participants.contains(&me.id))?;971 ensure(!participants.is_empty() && !participants.contains(&me.id))?;
1056 voice.decline(&community_id);972 voice.decline(&community_id);
@@ -1059,21 +975,19 @@ async fn dispatch(
1059 let members = user_community::members(&community_id, &conn).await?;975 let members = user_community::members(&community_id, &conn).await?;
1060 (976 (
1061 Response::Done,977 Response::Done,
1062- broadcast(Event::MessageCreated(created), &members),978+ vec![broadcast(Event::MessageCreated(created), &members)],
1063 )979 )
1064 }980 }
1065 Request::VoiceParticipants { community_id } => {981 Request::VoiceParticipants { community_id } => {
1066- let (me, _) = authenticated(state, &conn).await?;982+ let me = authenticated(state, &conn).await?;
1067- ensure(permission::can_read(983+ allowed(&me, &community_id, &conn, permission::can_read).await?;
1068- actor_rank(&me, &community_id, &conn).await?,
1069- ))?;
1070 (984 (
1071 Response::Voice(voice.participants(&community_id)),985 Response::Voice(voice.participants(&community_id)),
1072 Vec::new(),986 Vec::new(),
1073 )987 )
1074 }988 }
1075 Request::FindUser { username } => {989 Request::FindUser { username } => {
1076- let (me, _) = authenticated(state, &conn).await?;990+ let me = authenticated(state, &conn).await?;
1077 let found = user::by_username(&username, &conn)991 let found = user::by_username(&username, &conn)
1078 .await?992 .await?
1079 .filter(|found| found.id != me.id)993 .filter(|found| found.id != me.id)
@@ -1081,47 +995,51 @@ async fn dispatch(
1081 (Response::User(found), Vec::new())995 (Response::User(found), Vec::new())
1082 }996 }
1083 Request::OpenDirect { user_id } => {997 Request::OpenDirect { user_id } => {
1084- let (me, _) = authenticated(state, &conn).await?;998+ let me = authenticated(state, &conn).await?;
1085- let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?;999+ match direct::open(&me.id, &user_id, &mut conn).await? {
1086- let broadcasts = if created {1000+ direct::Opening::Created(community) => {
1087- let peer_view = community::read(&community.id, &user_id, &conn).await?;1001+ let peer_view = community::read(&community.id, &user_id, &conn).await?;
1088- vec![Broadcast {1002+ (
1089- event: Event::CommunityAdded(peer_view),1003+ Response::Community(community),
1090- user_ids: vec![user_id],1004+ vec![Broadcast {
1091- }]1005+ event: Event::CommunityAdded(peer_view),
1092- } else {1006+ user_ids: vec![user_id],
1093- Vec::new()1007+ }],
1094- };1008+ )
1095- (Response::Community(community), broadcasts)1009+ }
1010+ direct::Opening::Existing(community) => {
1011+ (Response::Community(community), Vec::new())
1012+ }
1013+ }
1096 }1014 }
1097 Request::OpenNotes => {1015 Request::OpenNotes => {
1098- let (me, _) = authenticated(state, &conn).await?;1016+ let me = authenticated(state, &conn).await?;
1099 (1017 (
1100 Response::Community(notes::open(&me.id, &mut conn).await?),1018 Response::Community(notes::open(&me.id, &mut conn).await?),
1101 Vec::new(),1019 Vec::new(),
1102 )1020 )
1103 }1021 }
1104 Request::Friends => {1022 Request::Friends => {
1105- let (me, _) = authenticated(state, &conn).await?;1023+ let me = authenticated(state, &conn).await?;
1106 (1024 (
1107 Response::Friends(friend::state(&me.id, &conn).await?),1025 Response::Friends(friend::state(&me.id, &conn).await?),
1108 Vec::new(),1026 Vec::new(),
1109 )1027 )
1110 }1028 }
1111 Request::AddFriend { user_id } => {1029 Request::AddFriend { user_id } => {
1112- let (me, _) = authenticated(state, &conn).await?;1030+ let me = authenticated(state, &conn).await?;
1113 friend::add(&me.id, &user_id, &mut conn).await?;1031 friend::add(&me.id, &user_id, &mut conn).await?;
1114 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;1032 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
1115 (Response::Done, broadcasts)1033 (Response::Done, broadcasts)
1116 }1034 }
1117 Request::AcceptFriend { user_id } => {1035 Request::AcceptFriend { user_id } => {
1118- let (me, _) = authenticated(state, &conn).await?;1036+ let me = authenticated(state, &conn).await?;
1119 friend::accept(&me.id, &user_id, &mut conn).await?;1037 friend::accept(&me.id, &user_id, &mut conn).await?;
1120 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;1038 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
1121 (Response::Done, broadcasts)1039 (Response::Done, broadcasts)
1122 }1040 }
1123 Request::RemoveFriend { user_id } => {1041 Request::RemoveFriend { user_id } => {
1124- let (me, _) = authenticated(state, &conn).await?;1042+ let me = authenticated(state, &conn).await?;
1125 friend::remove(&me.id, &user_id, &mut conn).await?;1043 friend::remove(&me.id, &user_id, &mut conn).await?;
1126 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;1044 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
1127 (Response::Done, broadcasts)1045 (Response::Done, broadcasts)
@@ -1130,11 +1048,9 @@ async fn dispatch(
1130 community_id,1048 community_id,
1131 user_id,1049 user_id,
1132 } => {1050 } => {
1133- let (me, _) = authenticated(state, &conn).await?;1051+ let me = authenticated(state, &conn).await?;
1134- ensure(!community::is_fixed(&community_id, &conn).await?)?;1052+ ensure_editable(&community_id, &conn).await?;
1135- ensure(permission::can_read(1053+ allowed(&me, &community_id, &conn, permission::can_read).await?;
1136- actor_rank(&me, &community_id, &conn).await?,
1137- ))?;
1138 let target = user::read(&user_id, &conn).await?;1054 let target = user::read(&user_id, &conn).await?;
1139 if user_community::rank(&user_id, &community_id, &conn)1055 if user_community::rank(&user_id, &community_id, &conn)
1140 .await?1056 .await?
@@ -1160,14 +1076,14 @@ async fn dispatch(
1160 (Response::Done, vec![broadcast])1076 (Response::Done, vec![broadcast])
1161 }1077 }
1162 Request::Invitations => {1078 Request::Invitations => {
1163- let (me, _) = authenticated(state, &conn).await?;1079+ let me = authenticated(state, &conn).await?;
1164 (1080 (
1165 Response::Invitations(invitation::of(&me.id, &conn).await?),1081 Response::Invitations(invitation::of(&me.id, &conn).await?),
1166 Vec::new(),1082 Vec::new(),
1167 )1083 )
1168 }1084 }
1169 Request::AcceptInvitation { community_id } => {1085 Request::AcceptInvitation { community_id } => {
1170- let (me, _) = authenticated(state, &conn).await?;1086+ let me = authenticated(state, &conn).await?;
1171 let tx = conn.transaction().await?;1087 let tx = conn.transaction().await?;
1172 invitation::take(&community_id, &me.id, &tx).await?;1088 invitation::take(&community_id, &me.id, &tx).await?;
1173 let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;1089 let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;
@@ -1184,12 +1100,12 @@ async fn dispatch(
1184 rank: Rank::Member,1100 rank: Rank::Member,
1185 },1101 },
1186 };1102 };
1187- let mut broadcasts = broadcast(event, &members);1103+ let mut broadcasts = vec![broadcast(event, &members)];
1188 broadcasts.push(invitations_updated(&me.id, &conn).await?);1104 broadcasts.push(invitations_updated(&me.id, &conn).await?);
1189 (Response::Community(community), broadcasts)1105 (Response::Community(community), broadcasts)
1190 }1106 }
1191 Request::DeclineInvitation { community_id } => {1107 Request::DeclineInvitation { community_id } => {
1192- let (me, _) = authenticated(state, &conn).await?;1108+ let me = authenticated(state, &conn).await?;
1193 invitation::take(&community_id, &me.id, &conn).await?;1109 invitation::take(&community_id, &me.id, &conn).await?;
1194 (1110 (
1195 Response::Done,1111 Response::Done,
@@ -1197,18 +1113,15 @@ async fn dispatch(
1197 )1113 )
1198 }1114 }
1199 Request::Logs { community_id } => {1115 Request::Logs { community_id } => {
1200- let (me, _) = authenticated(state, &conn).await?;1116+ let me = authenticated(state, &conn).await?;
1201- ensure(permission::can_read_logs(1117+ allowed(&me, &community_id, &conn, permission::can_read_logs).await?;
1202- actor_rank(&me, &community_id, &conn).await?,
1203- ))?;
1204 (1118 (
1205 Response::Logs(log::list(&community_id, &conn).await?),1119 Response::Logs(log::list(&community_id, &conn).await?),
1206 Vec::new(),1120 Vec::new(),
1207 )1121 )
1208 }1122 }
1209 Request::AllCommunities => {1123 Request::AllCommunities => {
1210- let (me, _) = authenticated(state, &conn).await?;1124+ builder(state, &conn).await?;
1211- ensure(permission::is_builder(me.role))?;
1212 let mut summaries = Vec::new();1125 let mut summaries = Vec::new();
1213 for community in community::groups(&conn).await? {1126 for community in community::groups(&conn).await? {
1214 let members = user_community::members(&community.id, &conn).await?;1127 let members = user_community::members(&community.id, &conn).await?;
@@ -1228,11 +1141,9 @@ async fn dispatch(
1228 community_id,1141 community_id,
1229 user_id,1142 user_id,
1230 } => {1143 } => {
1231- let (me, _) = authenticated(state, &conn).await?;1144+ let me = authenticated(state, &conn).await?;
1232- ensure(!community::is_fixed(&community_id, &conn).await?)?;1145+ ensure_editable(&community_id, &conn).await?;
1233- ensure(permission::can_transfer_ownership(1146+ allowed(&me, &community_id, &conn, permission::can_transfer_ownership).await?;
1234- actor_rank(&me, &community_id, &conn).await?,
1235- ))?;
1236 let tx = conn.transaction().await?;1147 let tx = conn.transaction().await?;
1237 let members = user_community::members(&community_id, &tx).await?;1148 let members = user_community::members(&community_id, &tx).await?;
1238 let target = members1149 let target = members
@@ -1282,12 +1193,12 @@ async fn dispatch(
1282 user_id: changed_id,1193 user_id: changed_id,
1283 rank,1194 rank,
1284 };1195 };
1285- broadcasts.extend(broadcast(event, &members));1196+ broadcasts.push(broadcast(event, &members));
1286 }1197 }
1287 (Response::Done, broadcasts)1198 (Response::Done, broadcasts)
1288 }1199 }
1289 Request::TimeoutUser { user_id, minutes } => {1200 Request::TimeoutUser { user_id, minutes } => {
1290- let (me, _) = authenticated(state, &conn).await?;1201+ let me = authenticated(state, &conn).await?;
1291 managed(&me, &user_id, &conn).await?;1202 managed(&me, &user_id, &conn).await?;
1292 let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);1203 let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS);
1293 user::set_timeout(&user_id, until, &conn).await?;1204 user::set_timeout(&user_id, until, &conn).await?;
@@ -1308,9 +1219,9 @@ async fn dispatch(
1308 Request::BanUser {1219 Request::BanUser {
1309 user_id,1220 user_id,
1310 reason,1221 reason,
1311- ip,1222+ scope,
1312 } => {1223 } => {
1313- let (me, _) = authenticated(state, &conn).await?;1224+ let me = authenticated(state, &conn).await?;
1314 let target = managed(&me, &user_id, &conn).await?;1225 let target = managed(&me, &user_id, &conn).await?;
1315 validate_reason(reason.as_deref())?;1226 validate_reason(reason.as_deref())?;
1316 let tx = conn.transaction().await?;1227 let tx = conn.transaction().await?;
@@ -1324,7 +1235,9 @@ async fn dispatch(
1324 &tx,1235 &tx,
1325 )1236 )
1326 .await?;1237 .await?;
1327- if ip && let Some(address) = user::last_ip(&user_id, &tx).await? {1238+ if scope == BanScope::AccountAndIp
1239+ && let Some(address) = user::last_ip(&user_id, &tx).await?
1240+ {
1328 server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx)1241 server_ban::insert(ServerBanKind::Ip, &address, reason.as_deref(), &me.id, &tx)
1329 .await?;1242 .await?;
1330 }1243 }
@@ -1341,50 +1254,47 @@ async fn dispatch(
1341 (Response::Done, Vec::new())1254 (Response::Done, Vec::new())
1342 }1255 }
1343 Request::ServerBans => {1256 Request::ServerBans => {
1344- let (me, _) = authenticated(state, &conn).await?;1257+ builder(state, &conn).await?;
1345- ensure(permission::is_builder(me.role))?;
1346 (1258 (
1347 Response::ServerBans(server_ban::list(&conn).await?),1259 Response::ServerBans(server_ban::list(&conn).await?),
1348 Vec::new(),1260 Vec::new(),
1349 )1261 )
1350 }1262 }
1351 Request::RemoveServerBan { id } => {1263 Request::RemoveServerBan { id } => {
1352- let (me, _) = authenticated(state, &conn).await?;1264+ let me = builder(state, &conn).await?;
1353- ensure(permission::is_builder(me.role))?;
1354 server_ban::remove(&id, &conn).await?;1265 server_ban::remove(&id, &conn).await?;
1355 admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?;1266 admin_log::record(Some(&me.id), None, None, &AdminAction::BanRemoved, &conn).await?;
1356 (Response::Done, Vec::new())1267 (Response::Done, Vec::new())
1357 }1268 }
1358 Request::CreateInviteCode { uses, hours } => {1269 Request::CreateInviteCode { uses, hours } => {
1359- let (me, _) = authenticated(state, &conn).await?;1270+ let me = authenticated(state, &conn).await?;
1360 ensure(permission::is_builder(me.role) && uses > 0)?;1271 ensure(permission::is_builder(me.role) && uses > 0)?;
1361 let code = invite::create(uses, hours, &me, &conn).await?;1272 let code = invite::create(uses, hours, &me, &conn).await?;
1362 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?;1273 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteCreated, &conn).await?;
1363 (Response::InviteCode(code), Vec::new())1274 (Response::InviteCode(code), Vec::new())
1364 }1275 }
1365 Request::InviteCodes => {1276 Request::InviteCodes => {
1366- let (me, _) = authenticated(state, &conn).await?;1277+ builder(state, &conn).await?;
1367- ensure(permission::is_builder(me.role))?;
1368 (1278 (
1369 Response::InviteCodes(invite::list(&conn).await?),1279 Response::InviteCodes(invite::list(&conn).await?),
1370 Vec::new(),1280 Vec::new(),
1371 )1281 )
1372 }1282 }
1373 Request::DeleteInviteCode { code } => {1283 Request::DeleteInviteCode { code } => {
1374- let (me, _) = authenticated(state, &conn).await?;1284+ let me = builder(state, &conn).await?;
1375- ensure(permission::is_builder(me.role))?;
1376 invite::delete(&code, &conn).await?;1285 invite::delete(&code, &conn).await?;
1377 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?;1286 admin_log::record(Some(&me.id), None, None, &AdminAction::InviteDeleted, &conn).await?;
1378 (Response::Done, Vec::new())1287 (Response::Done, Vec::new())
1379 }1288 }
1380 Request::ReportMessage { message_id, reason } => {1289 Request::ReportMessage { message_id, reason } => {
1381- let (me, _) = authenticated(state, &conn).await?;1290+ let me = authenticated(state, &conn).await?;
1382 let message = message::read(&message_id, &conn).await?;1291 let message = message::read(&message_id, &conn).await?;
1383 let actor = actor_rank(&me, &message.community_id, &conn).await?;1292 let actor = actor_rank(&me, &message.community_id, &conn).await?;
1384 ensure(permission::can_read(actor) && me.id != message.user_id)?;1293 ensure(permission::can_read(actor) && me.id != message.user_id)?;
1385 validate_reason(Some(&reason))?;1294 validate_reason(Some(&reason))?;
1386- ensure_untaken(1295+ ensure_with(
1387- report::is_open(&me.id, &message.user_id, Some(&message_id), &conn).await?,1296+ !report::is_open(&me.id, &message.user_id, Some(&message_id), &conn).await?,
1297+ CommonError::Taken,
1388 )?;1298 )?;
1389 report::insert(1299 report::insert(
1390 &me.id,1300 &me.id,
@@ -1396,27 +1306,29 @@ async fn dispatch(
1396 &conn,1306 &conn,
1397 )1307 )
1398 .await?;1308 .await?;
1399- (Response::Done, report_created(&conn).await?)1309+ (Response::Done, vec![report_created(&conn).await?])
1400 }1310 }
1401 Request::ReportUser { user_id, reason } => {1311 Request::ReportUser { user_id, reason } => {
1402- let (me, _) = authenticated(state, &conn).await?;1312+ let me = authenticated(state, &conn).await?;
1403 user::read(&user_id, &conn).await?;1313 user::read(&user_id, &conn).await?;
1404 ensure(me.id != user_id)?;1314 ensure(me.id != user_id)?;
1405 validate_reason(Some(&reason))?;1315 validate_reason(Some(&reason))?;
1406- ensure_untaken(report::is_open(&me.id, &user_id, None, &conn).await?)?;1316+ ensure_with(
1317+ !report::is_open(&me.id, &user_id, None, &conn).await?,
1318+ CommonError::Taken,
1319+ )?;
1407 report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?;1320 report::insert(&me.id, &user_id, None, None, None, &reason, &conn).await?;
1408- (Response::Done, report_created(&conn).await?)1321+ (Response::Done, vec![report_created(&conn).await?])
1409 }1322 }
1410 Request::Reports { status } => {1323 Request::Reports { status } => {
1411- let (me, _) = authenticated(state, &conn).await?;1324+ builder(state, &conn).await?;
1412- ensure(permission::is_builder(me.role))?;
1413 (1325 (
1414 Response::Reports(report::list(status, &conn).await?),1326 Response::Reports(report::list(status, &conn).await?),
1415 Vec::new(),1327 Vec::new(),
1416 )1328 )
1417 }1329 }
1418 Request::HandleReport { report_id, status } => {1330 Request::HandleReport { report_id, status } => {
1419- let (me, _) = authenticated(state, &conn).await?;1331+ let me = authenticated(state, &conn).await?;
1420 ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?;1332 ensure(permission::is_builder(me.role) && status != ReportStatus::Open)?;
1421 let target = report::handle(&report_id, status, &me.id, &conn).await?;1333 let target = report::handle(&report_id, status, &me.id, &conn).await?;
1422 admin_log::record(1334 admin_log::record(
@@ -1436,8 +1348,7 @@ async fn dispatch(
1436 after_ms,1348 after_ms,
1437 before_ms,1349 before_ms,
1438 } => {1350 } => {
1439- let (me, _) = authenticated(state, &conn).await?;1351+ builder(state, &conn).await?;
1440- ensure(permission::is_builder(me.role))?;
1441 let hits = message::search(1352 let hits = message::search(
1442 text.as_deref(),1353 text.as_deref(),
1443 user_id.as_deref(),1354 user_id.as_deref(),
@@ -1450,16 +1361,14 @@ async fn dispatch(
1450 (Response::MessageHits(hits), Vec::new())1361 (Response::MessageHits(hits), Vec::new())
1451 }1362 }
1452 Request::SearchCommunity { community_id, text } => {1363 Request::SearchCommunity { community_id, text } => {
1453- let (me, _) = authenticated(state, &conn).await?;1364+ let me = authenticated(state, &conn).await?;
1454- ensure(permission::can_read(1365+ allowed(&me, &community_id, &conn, permission::can_read).await?;
1455- actor_rank(&me, &community_id, &conn).await?,
1456- ))?;
1457 let hits =1366 let hits =
1458 message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?;1367 message::search(Some(&text), None, Some(&community_id), None, None, &conn).await?;
1459 (Response::MessageHits(hits), Vec::new())1368 (Response::MessageHits(hits), Vec::new())
1460 }1369 }
1461 Request::PurgeUser { user_id } => {1370 Request::PurgeUser { user_id } => {
1462- let (me, _) = authenticated(state, &conn).await?;1371+ let me = authenticated(state, &conn).await?;
1463 managed(&me, &user_id, &conn).await?;1372 managed(&me, &user_id, &conn).await?;
1464 let tx = conn.transaction().await?;1373 let tx = conn.transaction().await?;
1465 let upload_ids = attachment::uploads_of(&user_id, &tx).await?;1374 let upload_ids = attachment::uploads_of(&user_id, &tx).await?;
@@ -1475,7 +1384,7 @@ async fn dispatch(
1475 }1384 }
1476 let community_members = &members[&deleted.community_id];1385 let community_members = &members[&deleted.community_id];
1477 let event = Event::MessageDeleted(deleted);1386 let event = Event::MessageDeleted(deleted);
1478- broadcasts.extend(broadcast(event, community_members));1387+ broadcasts.push(broadcast(event, community_members));
1479 }1388 }
1480 attachment::delete_uploads(&user_id, &tx).await?;1389 attachment::delete_uploads(&user_id, &tx).await?;
1481 admin_log::record(1390 admin_log::record(
@@ -1496,8 +1405,7 @@ async fn dispatch(
1496 user_id,1405 user_id,
1497 community_id,1406 community_id,
1498 } => {1407 } => {
1499- let (me, _) = authenticated(state, &conn).await?;1408+ builder(state, &conn).await?;
1500- ensure(permission::is_builder(me.role))?;
1501 (1409 (
1502 Response::AttachmentInfos(1410 Response::AttachmentInfos(
1503 attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?,1411 attachment::all(user_id.as_deref(), community_id.as_deref(), &conn).await?,
@@ -1506,8 +1414,7 @@ async fn dispatch(
1506 )1414 )
1507 }1415 }
1508 Request::DeleteAttachment { attachment_id } => {1416 Request::DeleteAttachment { attachment_id } => {
1509- let (me, _) = authenticated(state, &conn).await?;1417+ let me = builder(state, &conn).await?;
1510- ensure(permission::is_builder(me.role))?;
1511 let stored = attachment::read(&attachment_id, &conn).await?;1418 let stored = attachment::read(&attachment_id, &conn).await?;
1512 let community = community::label(&stored.community_id, &conn).await?;1419 let community = community::label(&stored.community_id, &conn).await?;
1513 let tx = conn.transaction().await?;1420 let tx = conn.transaction().await?;
@@ -1524,21 +1431,19 @@ async fn dispatch(
1524 if let Some(message_id) = &stored.message_id {1431 if let Some(message_id) = &stored.message_id {
1525 let updated = message::read(message_id, &tx).await?;1432 let updated = message::read(message_id, &tx).await?;
1526 let members = user_community::members(&updated.community_id, &tx).await?;1433 let members = user_community::members(&updated.community_id, &tx).await?;
1527- broadcasts = broadcast(Event::MessageUpdated(updated), &members);1434+ broadcasts = vec![broadcast(Event::MessageUpdated(updated), &members)];
1528 }1435 }
1529 tx.commit().await?;1436 tx.commit().await?;
1530 attachment::remove_files(&[attachment_id], directory);1437 attachment::remove_files(&[attachment_id], directory);
1531 (Response::Done, broadcasts)1438 (Response::Done, broadcasts)
1532 }1439 }
1533 Request::StorageUsage => {1440 Request::StorageUsage => {
1534- let (me, _) = authenticated(state, &conn).await?;1441+ builder(state, &conn).await?;
1535- ensure(permission::is_builder(me.role))?;
1536 let (users, communities) = attachment::usage(&conn).await?;1442 let (users, communities) = attachment::usage(&conn).await?;
1537 (Response::StorageUsage { users, communities }, Vec::new())1443 (Response::StorageUsage { users, communities }, Vec::new())
1538 }1444 }
1539 Request::CreateBackup => {1445 Request::CreateBackup => {
1540- let (me, _) = authenticated(state, &conn).await?;1446+ let me = builder(state, &conn).await?;
1541- ensure(permission::is_builder(me.role))?;
1542 let backup = backup::create(&conn, backups).await?;1447 let backup = backup::create(&conn, backups).await?;
1543 let action = AdminAction::BackupCreated {1448 let action = AdminAction::BackupCreated {
1544 name: backup.name.clone(),1449 name: backup.name.clone(),
@@ -1547,13 +1452,11 @@ async fn dispatch(
1547 (Response::Backup(backup), Vec::new())1452 (Response::Backup(backup), Vec::new())
1548 }1453 }
1549 Request::Backups => {1454 Request::Backups => {
1550- let (me, _) = authenticated(state, &conn).await?;1455+ builder(state, &conn).await?;
1551- ensure(permission::is_builder(me.role))?;
1552 (Response::Backups(backup::list(backups)?), Vec::new())1456 (Response::Backups(backup::list(backups)?), Vec::new())
1553 }1457 }
1554 Request::DeleteBackup { name } => {1458 Request::DeleteBackup { name } => {
1555- let (me, _) = authenticated(state, &conn).await?;1459+ let me = builder(state, &conn).await?;
1556- ensure(permission::is_builder(me.role))?;
1557 backup::delete(&name, backups)?;1460 backup::delete(&name, backups)?;
1558 let action = AdminAction::BackupDeleted { name };1461 let action = AdminAction::BackupDeleted { name };
1559 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;1462 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
@@ -1563,17 +1466,16 @@ async fn dispatch(
1563 return Err(CommonError::Server.into());1466 return Err(CommonError::Server.into());
1564 }1467 }
1565 Request::VoiceRooms => {1468 Request::VoiceRooms => {
1566- let (me, _) = authenticated(state, &conn).await?;1469+ builder(state, &conn).await?;
1567- ensure(permission::is_builder(me.role))?;
1568 (1470 (
1569 Response::VoiceRooms(voice_rooms(voice, &conn).await?),1471 Response::VoiceRooms(voice_rooms(voice, &conn).await?),
1570 Vec::new(),1472 Vec::new(),
1571 )1473 )
1572 }1474 }
1573 Request::KickFromVoice { user_id } => {1475 Request::KickFromVoice { user_id } => {
1574- let (me, _) = authenticated(state, &conn).await?;1476+ let me = authenticated(state, &conn).await?;
1575 managed(&me, &user_id, &conn).await?;1477 managed(&me, &user_id, &conn).await?;
1576- let broadcasts = leave_voice(voice, &user_id, &conn).await?;1478+ let broadcasts = leave_user_voice(voice, &user_id, &conn).await?;
1577 if !broadcasts.is_empty() {1479 if !broadcasts.is_empty() {
1578 admin_log::record(1480 admin_log::record(
1579 Some(&me.id),1481 Some(&me.id),
@@ -1587,7 +1489,7 @@ async fn dispatch(
1587 (Response::Done, broadcasts)1489 (Response::Done, broadcasts)
1588 }1490 }
1589 Request::ServerMute { user_id, muted } => {1491 Request::ServerMute { user_id, muted } => {
1590- let (me, _) = authenticated(state, &conn).await?;1492+ let me = authenticated(state, &conn).await?;
1591 managed(&me, &user_id, &conn).await?;1493 managed(&me, &user_id, &conn).await?;
1592 user::set_voice_muted(&user_id, muted, &conn).await?;1494 user::set_voice_muted(&user_id, muted, &conn).await?;
1593 admin_log::record(1495 admin_log::record(
@@ -1619,10 +1521,8 @@ async fn dispatch(
1619 community_id,1521 community_id,
1620 enabled,1522 enabled,
1621 } => {1523 } => {
1622- let (me, _) = authenticated(state, &conn).await?;1524+ let me = authenticated(state, &conn).await?;
1623- ensure(permission::can_manage_voice(1525+ allowed(&me, &community_id, &conn, permission::can_manage_voice).await?;
1624- actor_rank(&me, &community_id, &conn).await?,
1625- ))?;
1626 let tx = conn.transaction().await?;1526 let tx = conn.transaction().await?;
1627 community::set_voice_enabled(&community_id, enabled, &tx).await?;1527 community::set_voice_enabled(&community_id, enabled, &tx).await?;
1628 let updated = community::read(&community_id, &me.id, &tx).await?;1528 let updated = community::read(&community_id, &me.id, &tx).await?;
@@ -1643,13 +1543,12 @@ async fn dispatch(
1643 broadcasts.extend(voice_silenced(voice, &community_id, &conn).await?);1543 broadcasts.extend(voice_silenced(voice, &community_id, &conn).await?);
1644 }1544 }
1645 let event = Event::CommunityUpdated(updated.clone());1545 let event = Event::CommunityUpdated(updated.clone());
1646- broadcasts.extend(broadcast(event, &members));1546+ broadcasts.push(broadcast(event, &members));
1647 1547
1648 (Response::Community(updated), broadcasts)1548 (Response::Community(updated), broadcasts)
1649 }1549 }
1650 Request::SetGhost { enabled } => {1550 Request::SetGhost { enabled } => {
1651- let (me, _) = authenticated(state, &conn).await?;1551+ let me = builder(state, &conn).await?;
1652- ensure(permission::is_builder(me.role))?;
1653 user::set_ghost(&me.id, enabled, &conn).await?;1552 user::set_ghost(&me.id, enabled, &conn).await?;
1654 let action = if enabled {1553 let action = if enabled {
1655 AdminAction::GhostEnabled1554 AdminAction::GhostEnabled
@@ -1659,16 +1558,15 @@ async fn dispatch(
1659 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;1558 admin_log::record(Some(&me.id), None, None, &action, &conn).await?;
1660 let mut broadcasts = Vec::new();1559 let mut broadcasts = Vec::new();
1661 let outsider = match voice.room_of(&me.id) {1560 let outsider = match voice.room_of(&me.id) {
1662- Some(community_id) => user_community::rank(&me.id, &community_id, &conn)1561+ Some(community_id) => is_outsider(&me.id, &community_id, &conn).await?,
1663- .await?
1664- .is_none(),
1665 None => false,1562 None => false,
1666 };1563 };
1667 if !outsider1564 if !outsider
1668- && let Some(GhostChange {1565+ && let Some(Left {
1669 community_id,1566 community_id,
1670 ghost_seconds: seconds,1567 ghost_seconds: seconds,
1671 call,1568 call,
1569+ ..
1672 }) = voice.set_ghost(&me.id, enabled)1570 }) = voice.set_ghost(&me.id, enabled)
1673 {1571 {
1674 let members = user_community::members(&community_id, &conn).await?;1572 let members = user_community::members(&community_id, &conn).await?;
@@ -1687,32 +1585,10 @@ async fn dispatch(
1687 .collect(),1585 .collect(),
1688 });1586 });
1689 } else {1587 } else {
1690- broadcasts.extend(broadcast(1588+ let muted = user::voice_muted(&me.id, &conn).await?;
1691- Event::VoiceJoined {1589+ broadcasts.extend(joined_broadcasts(&community_id, &me.id, muted, &members));
1692- community_id: community_id.clone(),
1693- user_id: me.id.clone(),
1694- },
1695- &members,
1696- ));
1697- if user::voice_muted(&me.id, &conn).await? {
1698- broadcasts.extend(broadcast(
1699- Event::VoiceMuted {
1700- user_id: me.id.clone(),
1701- muted: true,
1702- },
1703- &members,
1704- ));
1705- }
1706 if let Some(seconds) = seconds {1590 if let Some(seconds) = seconds {
1707- let community = community::label(&community_id, &conn).await?;1591+ record_ghost_voice(&me.id, &community_id, seconds, &conn).await?;
1708- admin_log::record(
1709- Some(&me.id),
1710- None,
1711- Some(&community),
1712- &AdminAction::GhostVoice { seconds },
1713- &conn,
1714- )
1715- .await?;
1716 }1592 }
1717 }1593 }
1718 }1594 }
@@ -1749,25 +1625,15 @@ async fn voice_rooms(voice: &Voice, conn: &Connection) -> Result<Vec<VoiceRoom>,
1749 Ok(rooms)1625 Ok(rooms)
1750 }1626 }
1751 1627
1752-async fn report_created(conn: &Connection) -> Result<Vec<Broadcast>, Error> {1628+async fn report_created(conn: &Connection) -> Result<Broadcast, Error> {
1753- Ok(vec![Broadcast {1629+ Ok(Broadcast {
1754 event: Event::ReportCreated,1630 event: Event::ReportCreated,
1755 user_ids: user::builder_ids(conn).await?,1631 user_ids: user::builder_ids(conn).await?,
1756- }])1632+ })
1757-}
1758-
1759-fn ensure_or(allowed: bool, error: CommonError) -> Result<(), Error> {
1760- if allowed {
1761- return Ok(());
1762- }
1763-
1764- Err(error.into())
1765 }1633 }
1766 1634
1767-fn address(connection: Option<&quinn::Connection>) -> String {1635+fn ip_of(connection: Option<&quinn::Connection>) -> Option<String> {
1768- connection1636+ connection.map(|connection| connection.remote_address().ip().to_string())
1769- .map(|connection| connection.remote_address().ip().to_string())
1770- .unwrap_or_default()
1771 }1637 }
1772 1638
1773 async fn limit_logins(1639 async fn limit_logins(
@@ -1777,7 +1643,7 @@ async fn limit_logins(
1777 ) -> Result<(), Error> {1643 ) -> Result<(), Error> {
1778 let limit = server_settings::read(conn).await?.logins_per_minute;1644 let limit = server_settings::read(conn).await?.logins_per_minute;
1779 1645
1780- Ok(rate_limit.allow(&address(connection), limit)?)1646+ Ok(rate_limit.allow(&ip_of(connection).unwrap_or_default(), limit)?)
1781 }1647 }
1782 1648
1783 fn limit_messages(1649 fn limit_messages(
@@ -1785,33 +1651,20 @@ fn limit_messages(
1785 rate_limit: &RateLimit,1651 rate_limit: &RateLimit,
1786 settings: &ServerSettings,1652 settings: &ServerSettings,
1787 ) -> Result<(), Error> {1653 ) -> Result<(), Error> {
1788- if permission::bypasses_limits(me.role) {1654+ if permission::is_builder(me.role) {
1789 return Ok(());1655 return Ok(());
1790 }1656 }
1791 1657
1792 Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?)1658 Ok(rate_limit.allow(&me.id, settings.messages_per_minute)?)
1793 }1659 }
1794 1660
1795-fn ensure_untaken(taken: bool) -> Result<(), Error> {
1796- if taken {
1797- return Err(CommonError::Taken.into());
1798- }
1799-
1800- Ok(())
1801-}
1802-
1803 async fn record_address(1661 async fn record_address(
1804 user: &User,1662 user: &User,
1805 connection: Option<&quinn::Connection>,1663 connection: Option<&quinn::Connection>,
1806 conn: &Connection,1664 conn: &Connection,
1807 ) -> Result<(), Error> {1665 ) -> Result<(), Error> {
1808- if let Some(connection) = connection {1666+ if let Some(ip) = ip_of(connection) {
1809- user::set_last_ip(1667+ user::set_last_ip(&user.id, &ip, conn).await?;
1810- &user.id,
1811- &connection.remote_address().ip().to_string(),
1812- conn,
1813- )
1814- .await?;
1815 }1668 }
1816 1669
1817 Ok(())1670 Ok(())
@@ -1821,7 +1674,7 @@ struct Removal {
1821 community_id: String,1674 community_id: String,
1822 user_id: String,1675 user_id: String,
1823 reason: Option<String>,1676 reason: Option<String>,
1824- banned: bool,1677+ sanction: Sanction,
1825 }1678 }
1826 1679
1827 async fn remove_member(1680 async fn remove_member(
@@ -1834,10 +1687,10 @@ async fn remove_member(
1834 community_id,1687 community_id,
1835 user_id,1688 user_id,
1836 reason,1689 reason,
1837- banned,1690+ sanction,
1838 } = removal;1691 } = removal;
1839 validate_reason(reason.as_deref())?;1692 validate_reason(reason.as_deref())?;
1840- ensure(!community::is_fixed(&community_id, conn).await?)?;1693+ ensure_editable(&community_id, conn).await?;
1841 let target = user::read(&user_id, conn).await?;1694 let target = user::read(&user_id, conn).await?;
1842 ensure(permission::can_moderate(1695 ensure(permission::can_moderate(
1843 actor_rank(me, &community_id, conn).await?,1696 actor_rank(me, &community_id, conn).await?,
@@ -1847,24 +1700,25 @@ async fn remove_member(
1847 let tx = conn.transaction().await?;1700 let tx = conn.transaction().await?;
1848 let members = user_community::members(&community_id, &tx).await?;1701 let members = user_community::members(&community_id, &tx).await?;
1849 user_community::leave(&user_id, &community_id, &tx).await?;1702 user_community::leave(&user_id, &community_id, &tx).await?;
1850- let action = if banned {1703+ let action = match sanction {
1851- user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?;1704+ Sanction::Ban => {
1852- LogAction::Banned {1705+ user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?;
1853- reason: reason.clone(),1706+ LogAction::Banned {
1707+ reason: reason.clone(),
1708+ }
1854 }1709 }
1855- } else {1710+ Sanction::Kick => LogAction::Kicked {
1856- LogAction::Kicked {
1857 reason: reason.clone(),1711 reason: reason.clone(),
1858- }1712+ },
1859 };1713 };
1860 log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;1714 log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;
1861 tx.commit().await?;1715 tx.commit().await?;
1862- let mut broadcasts = voice_leave(voice, &community_id, &user_id, conn).await?;1716+ let mut broadcasts = leave_room_voice(voice, &community_id, &user_id, conn).await?;
1863 broadcasts.push(Broadcast {1717 broadcasts.push(Broadcast {
1864 event: Event::Removed {1718 event: Event::Removed {
1865 community_id: community_id.clone(),1719 community_id: community_id.clone(),
1866 community_name: community.name,1720 community_name: community.name,
1867- banned,1721+ sanction,
1868 reason,1722 reason,
1869 },1723 },
1870 user_ids: vec![user_id.clone()],1724 user_ids: vec![user_id.clone()],
@@ -1873,7 +1727,7 @@ async fn remove_member(
1873 community_id,1727 community_id,
1874 user_id,1728 user_id,
1875 };1729 };
1876- broadcasts.extend(broadcast(event, &members));1730+ broadcasts.push(broadcast(event, &members));
1877 1731
1878 Ok((Response::Done, broadcasts))1732 Ok((Response::Done, broadcasts))
1879 }1733 }
@@ -1946,7 +1800,7 @@ async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadca
1946 })1800 })
1947 }1801 }
1948 1802
1949-pub async fn leave_voice(1803+async fn leave_user_voice(
1950 voice: &Voice,1804 voice: &Voice,
1951 user_id: &str,1805 user_id: &str,
1952 conn: &Connection,1806 conn: &Connection,
@@ -1968,7 +1822,7 @@ pub async fn leave_connection_voice(
1968 }1822 }
1969 }1823 }
1970 1824
1971-async fn voice_leave(1825+async fn leave_room_voice(
1972 voice: &Voice,1826 voice: &Voice,
1973 community_id: &str,1827 community_id: &str,
1974 user_id: &str,1828 user_id: &str,
@@ -2053,16 +1907,18 @@ async fn call_ended(
2053 members: &[Member],1907 members: &[Member],
2054 conn: &Connection,1908 conn: &Connection,
2055 ) -> Result<Vec<Broadcast>, Error> {1909 ) -> Result<Vec<Broadcast>, Error> {
2056- let direct = match call {1910+ let Some(call) = call else {
2057- Some(_) => community::is_direct(community_id, conn).await?,1911+ return Ok(Vec::new());
2058- None => false,
2059 };1912 };
2060- let Some(call) = call.filter(|_| direct).and_then(call_log_of) else {1913+ if !community::is_direct(community_id, conn).await? {
1914+ return Ok(Vec::new());
1915+ }
1916+ let Some(call) = call_log_of(call) else {
2061 return Ok(Vec::new());1917 return Ok(Vec::new());
2062 };1918 };
2063 let created = message::create_call_log(community_id, user_id, call, conn).await?;1919 let created = message::create_call_log(community_id, user_id, call, conn).await?;
2064 1920
2065- Ok(broadcast(Event::MessageCreated(created), members))1921+ Ok(vec![broadcast(Event::MessageCreated(created), members)])
2066 }1922 }
2067 1923
2068 async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Error> {1924 async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
@@ -2074,19 +1930,11 @@ async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Err
2074 community_id: left.community_id,1930 community_id: left.community_id,
2075 user_id: left.user_id,1931 user_id: left.user_id,
2076 };1932 };
2077- broadcasts.extend(broadcast(event, &members));1933+ broadcasts.push(broadcast(event, &members));
2078 1934
2079 return Ok(broadcasts);1935 return Ok(broadcasts);
2080 };1936 };
2081- let community = community::label(&left.community_id, conn).await?;1937+ record_ghost_voice(&left.user_id, &left.community_id, seconds, conn).await?;
2082- admin_log::record(
2083- Some(&left.user_id),
2084- None,
2085- Some(&community),
2086- &AdminAction::GhostVoice { seconds },
2087- conn,
2088- )
2089- .await?;
2090 1938
2091 Ok(Vec::new())1939 Ok(Vec::new())
2092 }1940 }
@@ -2107,21 +1955,36 @@ fn set_state(state: &Mutex<State>, new_state: State) {
2107 *state.lock().unwrap() = new_state;1955 *state.lock().unwrap() = new_state;
2108 }1956 }
2109 1957
2110-async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<(User, String), Error> {1958+fn session(state: &Mutex<State>) -> Result<(User, String), Error> {
2111- let (cached, token) = match state.lock().unwrap().clone() {1959+ match state.lock().unwrap().clone() {
2112- State::Anonymous => return Err(CommonError::Unauthenticated.into()),1960+ State::Anonymous => Err(CommonError::Unauthenticated.into()),
2113- State::Authenticated { user, token } => (user, token),1961+ State::Authenticated { user, token } => Ok((user, token)),
2114- };1962+ }
1963+}
1964+
1965+fn session_token(state: &Mutex<State>) -> Result<String, Error> {
1966+ Ok(session(state)?.1)
1967+}
1968+
1969+fn cache_user(state: &Mutex<State>, user: User) {
1970+ if let State::Authenticated { user: cached, .. } = &mut *state.lock().unwrap() {
1971+ *cached = user;
1972+ }
1973+}
1974+
1975+async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<User, Error> {
1976+ let (cached, _) = session(state)?;
2115 let user = user::read(&cached.id, conn).await?;1977 let user = user::read(&cached.id, conn).await?;
2116- set_state(1978+ cache_user(state, user.clone());
2117- state,1979+
2118- State::Authenticated {1980+ Ok(user)
2119- user: user.clone(),1981+}
2120- token: token.clone(),
2121- },
2122- );
2123 1982
2124- Ok((user, token))1983+async fn builder(state: &Mutex<State>, conn: &Connection) -> Result<User, Error> {
1984+ let user = authenticated(state, conn).await?;
1985+ ensure(permission::is_builder(user.role))?;
1986+
1987+ Ok(user)
2125 }1988 }
2126 1989
2127 pub async fn actor_rank(1990 pub async fn actor_rank(
@@ -2146,31 +2009,109 @@ async fn managed(me: &User, user_id: &str, conn: &Connection) -> Result<User, Er
2146 }2009 }
2147 2010
2148 pub fn ensure(allowed: bool) -> Result<(), Error> {2011 pub fn ensure(allowed: bool) -> Result<(), Error> {
2012+ ensure_with(allowed, CommonError::Forbidden)
2013+}
2014+
2015+pub fn ensure_with(allowed: bool, error: CommonError) -> Result<(), Error> {
2149 if !allowed {2016 if !allowed {
2150- return Err(CommonError::Forbidden.into());2017+ return Err(error.into());
2151 }2018 }
2152 2019
2153 Ok(())2020 Ok(())
2154 }2021 }
2155 2022
2156-fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Vec<Broadcast> {2023+async fn allowed(
2157- let mut broadcasts = broadcast(event, members);2024+ me: &User,
2158- for broadcast in &mut broadcasts {2025+ community_id: &str,
2159- if !broadcast.user_ids.iter().any(|id| id == user_id) {2026+ conn: &Connection,
2160- broadcast.user_ids.push(user_id.to_string());2027+ check: fn(Option<Rank>) -> bool,
2161- }2028+) -> Result<(), Error> {
2029+ ensure(check(actor_rank(me, community_id, conn).await?))
2030+}
2031+
2032+async fn is_outsider(user_id: &str, community_id: &str, conn: &Connection) -> Result<bool, Error> {
2033+ Ok(user_community::rank(user_id, community_id, conn)
2034+ .await?
2035+ .is_none())
2036+}
2037+
2038+async fn ensure_editable(community_id: &str, conn: &Connection) -> Result<(), Error> {
2039+ ensure(!community::is_fixed(community_id, conn).await?)
2040+}
2041+
2042+fn broadcast_with(event: Event, members: &[Member], user_id: &str) -> Broadcast {
2043+ let mut sent = broadcast(event, members);
2044+ if !sent.user_ids.iter().any(|id| id == user_id) {
2045+ sent.user_ids.push(user_id.to_string());
2046+ }
2047+
2048+ sent
2049+}
2050+
2051+async fn message_broadcast(
2052+ message: &Message,
2053+ event: fn(Message) -> Event,
2054+ actor_id: &str,
2055+ conn: &Connection,
2056+) -> Result<Broadcast, Error> {
2057+ let members = user_community::members(&message.community_id, conn).await?;
2058+
2059+ Ok(broadcast_with(event(message.clone()), &members, actor_id))
2060+}
2061+
2062+fn joined_broadcasts(
2063+ community_id: &str,
2064+ user_id: &str,
2065+ muted: bool,
2066+ members: &[Member],
2067+) -> Vec<Broadcast> {
2068+ let mut broadcasts = vec![broadcast(
2069+ Event::VoiceJoined {
2070+ community_id: community_id.to_string(),
2071+ user_id: user_id.to_string(),
2072+ },
2073+ members,
2074+ )];
2075+ if muted {
2076+ broadcasts.push(broadcast(
2077+ Event::VoiceMuted {
2078+ user_id: user_id.to_string(),
2079+ muted,
2080+ },
2081+ members,
2082+ ));
2162 }2083 }
2084+
2163 broadcasts2085 broadcasts
2164 }2086 }
2165 2087
2166-fn broadcast(event: Event, members: &[Member]) -> Vec<Broadcast> {2088+async fn record_ghost_voice(
2167- vec![Broadcast {2089+ user_id: &str,
2090+ community_id: &str,
2091+ seconds: u64,
2092+ conn: &Connection,
2093+) -> Result<(), Error> {
2094+ let community = community::label(community_id, conn).await?;
2095+ admin_log::record(
2096+ Some(user_id),
2097+ None,
2098+ Some(&community),
2099+ &AdminAction::GhostVoice { seconds },
2100+ conn,
2101+ )
2102+ .await?;
2103+
2104+ Ok(())
2105+}
2106+
2107+fn broadcast(event: Event, members: &[Member]) -> Broadcast {
2108+ Broadcast {
2168 event,2109 event,
2169 user_ids: members2110 user_ids: members
2170 .iter()2111 .iter()
2171 .map(|member| member.user.id.clone())2112 .map(|member| member.user.id.clone())
2172 .collect(),2113 .collect(),
2173- }]2114+ }
2174 }2115 }
2175 2116
2176 #[cfg(test)]2117 #[cfg(test)]
crates/server/src/server_ban.rsmodified+11 -12
@@ -4,7 +4,11 @@ use common::{
4 };4 };
5 use turso::Connection;5 use turso::Connection;
6 6
7-use crate::{database::new_id, error::Error, user};7+use crate::{
8+ database::{self, new_id},
9+ error::Error,
10+ user,
11+};
8 12
9 pub async fn insert(13 pub async fn insert(
10 kind: ServerBanKind,14 kind: ServerBanKind,
@@ -47,17 +51,12 @@ pub async fn list(conn: &Connection) -> Result<Vec<ServerBan>, Error> {
47 }51 }
48 52
49 async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, Error> {53 async fn exists(kind: ServerBanKind, value: &str, conn: &Connection) -> Result<bool, Error> {
50- let mut rows = conn54+ let found = database::scalar_i64(
51- .query(55+ conn,
52- "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)",56+ "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)",
53- (kind.as_str(), value),57+ (kind.as_str(), value),
54- )58+ )
55- .await?;59+ .await?;
56- let row = rows
57- .next()
58- .await?
59- .ok_or(turso::Error::QueryReturnedNoRows)?;
60- let found: i64 = row.get(0)?;
61 60
62 Ok(found != 0)61 Ok(found != 0)
63 }62 }
crates/server/src/server_settings.rsmodified+15 -3
@@ -3,10 +3,21 @@ use turso::Connection;
3 3
4 use crate::error::Error;4 use crate::error::Error;
5 5
6+const COLUMNS: &str = "name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute";
7+
8+fn assignments() -> String {
9+ COLUMNS
10+ .split(", ")
11+ .enumerate()
12+ .map(|(index, column)| format!("{column} = ?{}", index + 1))
13+ .collect::<Vec<_>>()
14+ .join(", ")
15+}
16+
6 pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {17 pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
7 let mut rows = conn18 let mut rows = conn
8 .query(19 .query(
9- "SELECT name, registration_open, max_attachment_bytes, maintenance, user_quota_bytes, community_quota_bytes, message_retention_days, attachment_retention_days, announcement, max_communities_per_user, max_message_length, max_avatar_bytes, messages_per_minute, logins_per_minute FROM server_settings WHERE id = 1",20+ &format!("SELECT {COLUMNS} FROM server_settings WHERE id = 1"),
10 (),21 (),
11 )22 )
12 .await?;23 .await?;
@@ -21,6 +32,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
21 let community_quota_bytes: i64 = row.get(5)?;32 let community_quota_bytes: i64 = row.get(5)?;
22 let message_retention_days: i64 = row.get(6)?;33 let message_retention_days: i64 = row.get(6)?;
23 let attachment_retention_days: i64 = row.get(7)?;34 let attachment_retention_days: i64 = row.get(7)?;
35+ let announcement: String = row.get(8)?;
24 let max_communities_per_user: i64 = row.get(9)?;36 let max_communities_per_user: i64 = row.get(9)?;
25 let max_message_length: i64 = row.get(10)?;37 let max_message_length: i64 = row.get(10)?;
26 let max_avatar_bytes: i64 = row.get(11)?;38 let max_avatar_bytes: i64 = row.get(11)?;
@@ -36,7 +48,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
36 community_quota_bytes: community_quota_bytes as u64,48 community_quota_bytes: community_quota_bytes as u64,
37 message_retention_days: message_retention_days as u32,49 message_retention_days: message_retention_days as u32,
38 attachment_retention_days: attachment_retention_days as u32,50 attachment_retention_days: attachment_retention_days as u32,
39- announcement: row.get(8)?,51+ announcement,
40 max_communities_per_user: max_communities_per_user as u32,52 max_communities_per_user: max_communities_per_user as u32,
41 max_message_length: max_message_length as u32,53 max_message_length: max_message_length as u32,
42 max_avatar_bytes: max_avatar_bytes as u64,54 max_avatar_bytes: max_avatar_bytes as u64,
@@ -47,7 +59,7 @@ pub async fn read(conn: &Connection) -> Result<ServerSettings, Error> {
47 59
48 pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), Error> {60 pub async fn update(settings: &ServerSettings, conn: &Connection) -> Result<(), Error> {
49 conn.execute(61 conn.execute(
50- "UPDATE server_settings SET name = ?1, registration_open = ?2, max_attachment_bytes = ?3, maintenance = ?4, user_quota_bytes = ?5, community_quota_bytes = ?6, message_retention_days = ?7, attachment_retention_days = ?8, announcement = ?9, max_communities_per_user = ?10, max_message_length = ?11, max_avatar_bytes = ?12, messages_per_minute = ?13, logins_per_minute = ?14 WHERE id = 1",62+ &format!("UPDATE server_settings SET {} WHERE id = 1", assignments()),
51 (63 (
52 settings.name.as_str(),64 settings.name.as_str(),
53 i64::from(settings.registration_open),65 i64::from(settings.registration_open),
crates/server/src/stats.rsmodified+2 -9
@@ -4,7 +4,7 @@ use common::{
4 };4 };
5 use turso::Connection;5 use turso::Connection;
6 6
7-use crate::{error::Error, user};7+use crate::{database, error::Error, user};
8 8
9 const MAXIMUM_DAYS: u32 = 90;9 const MAXIMUM_DAYS: u32 = 90;
10 10
@@ -53,12 +53,5 @@ pub async fn daily(days: u32, conn: &Connection) -> Result<Vec<DayStat>, Error>
53 }53 }
54 54
55 async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result<u64, Error> {55 async fn count(conn: &Connection, sql: &str, params: impl turso::IntoParams) -> Result<u64, Error> {
56- let mut rows = conn.query(sql, params).await?;56+ Ok(database::scalar_i64(conn, sql, params).await? as u64)
57- let row = rows
58- .next()
59- .await?
60- .ok_or(turso::Error::QueryReturnedNoRows)?;
61- let value: i64 = row.get(0)?;
62-
63- Ok(value as u64)
64 }57 }
crates/server/src/user.rsmodified+128 -141
@@ -2,7 +2,7 @@ use common::{
2 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},2 constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},
3 error::{Error as CommonError, InvalidInput},3 error::{Error as CommonError, InvalidInput},
4 model::{Account, Presence, Role, User},4 model::{Account, Presence, Role, User},
5- time,5+ permission, time,
6 validate::{validate_avatar_size, validate_status, validate_username},6 validate::{validate_avatar_size, validate_status, validate_username},
7 };7 };
8 use image::ImageFormat;8 use image::ImageFormat;
@@ -33,45 +33,48 @@ pub fn from_row(row: &Row) -> Result<User, Error> {
33 Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?)33 Ok(from_row_at(row, 0)?.ok_or(CommonError::Server)?)
34 }34 }
35 35
36-pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {36+pub fn bool_at(row: &Row, index: usize) -> Result<bool, Error> {
37- let mut rows = conn37+ let flag: i64 = row.get(index)?;
38- .query(
39- &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")),
40- (
41- new_id(),
42- username,
43- password_hash,
44- Role::User.as_str(),
45- Role::Builder.as_str(),
46- ),
47- )
48- .await?;
49- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
50 38
51- from_row(&row)39+ Ok(flag != 0)
52 }40 }
53 41
54-pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {42+async fn one(sql: &str, params: impl turso::IntoParams, conn: &Connection) -> Result<User, Error> {
55- let mut rows = conn43+ let mut rows = conn.query(sql, params).await?;
56- .query(
57- &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")),
58- (user_id,),
59- )
60- .await?;
61 let row = rows.next().await?.ok_or(CommonError::NotFound)?;44 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
62 45
63 from_row(&row)46 from_row(&row)
64 }47 }
65 48
49+pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {
50+ one(
51+ &format!("INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING {}", user_columns("user")),
52+ (
53+ new_id(),
54+ username,
55+ password_hash,
56+ Role::User.as_str(),
57+ Role::Builder.as_str(),
58+ ),
59+ conn,
60+ )
61+ .await
62+}
63+
64+pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
65+ one(
66+ &format!("SELECT {} FROM user WHERE id = ?1", user_columns("user")),
67+ (user_id,),
68+ conn,
69+ )
70+ .await
71+}
72+
66 pub async fn any(conn: &Connection) -> Result<bool, Error> {73 pub async fn any(conn: &Connection) -> Result<bool, Error> {
67 let mut rows = conn.query("SELECT EXISTS (SELECT 1 FROM user)", ()).await?;74 let mut rows = conn.query("SELECT EXISTS (SELECT 1 FROM user)", ()).await?;
68- let row = rows75+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
69- .next()
70- .await?
71- .ok_or(turso::Error::QueryReturnedNoRows)?;
72- let exists: i64 = row.get(0)?;
73 76
74- Ok(exists != 0)77+ bool_at(&row, 0)
75 }78 }
76 79
77 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {80 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {
@@ -88,6 +91,28 @@ pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<Use
88 rows.next().await?.as_ref().map(from_row).transpose()91 rows.next().await?.as_ref().map(from_row).transpose()
89 }92 }
90 93
94+pub async fn is_taken(
95+ username: &str,
96+ except_id: Option<&str>,
97+ conn: &Connection,
98+) -> Result<bool, Error> {
99+ Ok(by_username(username, conn)
100+ .await?
101+ .is_some_and(|existing| Some(existing.id.as_str()) != except_id))
102+}
103+
104+pub async fn by_session_token(token: &str, conn: &Connection) -> Result<User, Error> {
105+ let mut rows = conn
106+ .query(
107+ &format!("SELECT {} FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1", user_columns("user")),
108+ (token,),
109+ )
110+ .await?;
111+ let row = rows.next().await?.ok_or(CommonError::WrongCredentials)?;
112+
113+ from_row(&row)
114+}
115+
91 pub async fn credentials(116 pub async fn credentials(
92 username: &str,117 username: &str,
93 conn: &Connection,118 conn: &Connection,
@@ -111,42 +136,33 @@ pub async fn credentials(
111 pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, Error> {136 pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, Error> {
112 validate_username(username)?;137 validate_username(username)?;
113 138
114- if by_username(username, conn)139+ if is_taken(username, Some(user_id), conn).await? {
115- .await?
116- .is_some_and(|existing| existing.id != user_id)
117- {
118 return Err(CommonError::Taken.into());140 return Err(CommonError::Taken.into());
119 }141 }
120 142
121- let mut rows = conn143+ one(
122- .query(144+ &format!(
123- &format!(145+ "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}",
124- "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING {}",146+ user_columns("user")
125- user_columns("user")147+ ),
126- ),148+ (user_id, username),
127- (user_id, username),149+ conn,
128- )150+ )
129- .await?;151+ .await
130- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
131-
132- from_row(&row)
133 }152 }
134 153
135 pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result<User, Error> {154 pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result<User, Error> {
136 validate_status(status)?;155 validate_status(status)?;
137 156
138- let mut rows = conn157+ one(
139- .query(158+ &format!(
140- &format!(159+ "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}",
141- "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING {}",160+ user_columns("user")
142- user_columns("user")161+ ),
143- ),162+ (user_id, status),
144- (user_id, status),163+ conn,
145- )164+ )
146- .await?;165+ .await
147- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
148-
149- from_row(&row)
150 }166 }
151 167
152 pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {168 pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {
@@ -163,29 +179,27 @@ pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {
163 Ok(())179 Ok(())
164 }180 }
165 181
166-pub async fn set_avatar(user_id: &str, bytes: &[u8], conn: &mut Connection) -> Result<User, Error> {182+pub async fn set_avatar(
167- check_avatar(bytes)?;183+ user_id: &str,
184+ avatar: Option<&[u8]>,
185+ conn: &mut Connection,
186+) -> Result<User, Error> {
187+ if let Some(bytes) = avatar {
188+ check_avatar(bytes)?;
189+ }
168 190
169- let avatar_id = new_id();191+ let avatar_id = avatar.map(|_| new_id());
170 let tx = conn.transaction().await?;192 let tx = conn.transaction().await?;
171 tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,))193 tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,))
172 .await?;194 .await?;
173- tx.execute(195+ if let (Some(avatar_id), Some(bytes)) = (&avatar_id, avatar) {
174- "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)",196+ tx.execute(
175- (avatar_id.as_str(), user_id, bytes),197+ "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)",
176- )198+ (avatar_id.as_str(), user_id, bytes),
177- .await?;199+ )
178- let user = set_avatar_id(user_id, Some(&avatar_id), &tx).await?;
179- tx.commit().await?;
180-
181- Ok(user)
182-}
183-
184-pub async fn remove_avatar(user_id: &str, conn: &mut Connection) -> Result<User, Error> {
185- let tx = conn.transaction().await?;
186- tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,))
187 .await?;200 .await?;
188- let user = set_avatar_id(user_id, None, &tx).await?;201+ }
202+ let user = set_avatar_id(user_id, avatar_id.as_deref(), &tx).await?;
189 tx.commit().await?;203 tx.commit().await?;
190 204
191 Ok(user)205 Ok(user)
@@ -196,18 +210,15 @@ async fn set_avatar_id(
196 avatar_id: Option<&str>,210 avatar_id: Option<&str>,
197 conn: &Connection,211 conn: &Connection,
198 ) -> Result<User, Error> {212 ) -> Result<User, Error> {
199- let mut rows = conn213+ one(
200- .query(214+ &format!(
201- &format!(215+ "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}",
202- "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING {}",216+ user_columns("user")
203- user_columns("user")217+ ),
204- ),218+ (user_id, avatar_id),
205- (user_id, avatar_id),219+ conn,
206- )220+ )
207- .await?;221+ .await
208- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
209-
210- from_row(&row)
211 }222 }
212 223
213 pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error> {224 pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error> {
@@ -222,34 +233,16 @@ pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error
222 Ok(row.get(0)?)233 Ok(row.get(0)?)
223 }234 }
224 235
225-pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<User, Error> {
226- let mut rows = conn
227- .query(
228- &format!(
229- "UPDATE user SET role = ?2 WHERE username = ?1 RETURNING {}",
230- user_columns("user")
231- ),
232- (username, role.as_str()),
233- )
234- .await?;
235- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
236-
237- from_row(&row)
238-}
239-
240 pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {236 pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {
241- let mut rows = conn237+ one(
242- .query(238+ &format!(
243- &format!(239+ "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}",
244- "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING {}",240+ user_columns("user")
245- user_columns("user")241+ ),
246- ),242+ (user_id, role.as_str()),
247- (user_id, role.as_str()),243+ conn,
248- )244+ )
249- .await?;245+ .await
250- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
251-
252- from_row(&row)
253 }246 }
254 247
255 pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error> {248 pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error> {
@@ -260,10 +253,9 @@ pub async fn suspended(user_id: &str, conn: &Connection) -> Result<bool, Error>
260 )253 )
261 .await?;254 .await?;
262 let row = rows.next().await?.ok_or(CommonError::NotFound)?;255 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
263- let flag: i64 = row.get(0)?;
264 let until: Option<i64> = row.get(1)?;256 let until: Option<i64> = row.get(1)?;
265 257
266- Ok(flag != 0 || until.is_some_and(|until| until as u64 > time::now_ms()))258+ Ok(bool_at(&row, 0)? || until.is_some_and(|until| until as u64 > time::now_ms()))
267 }259 }
268 260
269 pub async fn set_timeout(261 pub async fn set_timeout(
@@ -348,9 +340,8 @@ pub async fn is_ghost(user_id: &str, conn: &Connection) -> Result<bool, Error> {
348 let Some(row) = rows.next().await? else {340 let Some(row) = rows.next().await? else {
349 return Ok(false);341 return Ok(false);
350 };342 };
351- let flag: i64 = row.get(0)?;
352 343
353- Ok(flag != 0)344+ bool_at(&row, 0)
354 }345 }
355 346
356 pub async fn presence(user_id: &str, conn: &Connection) -> Result<Presence, Error> {347 pub async fn presence(user_id: &str, conn: &Connection) -> Result<Presence, Error> {
@@ -380,14 +371,15 @@ pub async fn update_presence(
380 pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> {371 pub async fn voice_muted(user_id: &str, conn: &Connection) -> Result<bool, Error> {
381 let mut rows = conn372 let mut rows = conn
382 .query(373 .query(
383- "SELECT voice_muted AND role != ?2 FROM user WHERE id = ?1",374+ "SELECT voice_muted, role FROM user WHERE id = ?1",
384- (user_id, Role::Builder.as_str()),375+ (user_id,),
385 )376 )
386 .await?;377 .await?;
387 let row = rows.next().await?.ok_or(CommonError::NotFound)?;378 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
388- let muted: i64 = row.get(0)?;379+ let role: String = row.get(1)?;
380+ let builder = Role::parse(&role).is_some_and(permission::is_builder);
389 381
390- Ok(muted != 0)382+ Ok(bool_at(&row, 0)? && !builder)
391 }383 }
392 384
393 pub async fn set_password_hash(385 pub async fn set_password_hash(
@@ -413,16 +405,14 @@ pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> {
413 .await?;405 .await?;
414 let mut accounts = Vec::new();406 let mut accounts = Vec::new();
415 while let Some(row) = rows.next().await? {407 while let Some(row) = rows.next().await? {
416- let flag: i64 = row.get(5)?;
417 let last_seen: Option<i64> = row.get(6)?;408 let last_seen: Option<i64> = row.get(6)?;
418 let suspended_until: Option<i64> = row.get(7)?;409 let suspended_until: Option<i64> = row.get(7)?;
419- let ghost: i64 = row.get(8)?;
420 accounts.push(Account {410 accounts.push(Account {
421 user: from_row(&row)?,411 user: from_row(&row)?,
422- suspended: flag != 0,412+ suspended: bool_at(&row, 5)?,
423 last_seen: last_seen.map(|millis| millis as u64),413 last_seen: last_seen.map(|millis| millis as u64),
424 suspended_until: suspended_until.map(|millis| millis as u64),414 suspended_until: suspended_until.map(|millis| millis as u64),
425- ghost: ghost != 0,415+ ghost: bool_at(&row, 8)?,
426 });416 });
427 }417 }
428 418
@@ -430,18 +420,15 @@ pub async fn all(conn: &Connection) -> Result<Vec<Account>, Error> {
430 }420 }
431 421
432 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {422 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
433- let mut rows = conn423+ one(
434- .query(424+ &format!(
435- &format!(425+ "DELETE FROM user WHERE id = ?1 RETURNING {}",
436- "DELETE FROM user WHERE id = ?1 RETURNING {}",426+ user_columns("user")
437- user_columns("user")427+ ),
438- ),428+ (user_id,),
439- (user_id,),429+ conn,
440- )430+ )
441- .await?;431+ .await
442- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
443-
444- from_row(&row)
445 }432 }
446 433
447 #[cfg(test)]434 #[cfg(test)]
@@ -468,9 +455,9 @@ mod tests {
468 let mut conn = database::connect(&db).await.unwrap();455 let mut conn = database::connect(&db).await.unwrap();
469 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();456 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();
470 457
471- let small = user::set_avatar(&created_user.id, &jpeg(AVATAR_SIZE / 2), &mut conn).await;458+ let small = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE / 2)), &mut conn).await;
472- let not_jpeg = user::set_avatar(&created_user.id, b"not a jpeg", &mut conn).await;459+ let not_jpeg = user::set_avatar(&created_user.id, Some(b"not a jpeg"), &mut conn).await;
473- let valid = user::set_avatar(&created_user.id, &jpeg(AVATAR_SIZE), &mut conn)460+ let valid = user::set_avatar(&created_user.id, Some(&jpeg(AVATAR_SIZE)), &mut conn)
474 .await461 .await
475 .unwrap();462 .unwrap();
476 463
crates/server/src/voice.rsmodified+54 -81
@@ -25,12 +25,6 @@ pub enum CallEnd {
25 Declined,25 Declined,
26 }26 }
27 27
28-pub struct GhostChange {
29- pub community_id: String,
30- pub ghost_seconds: Option<u64>,
31- pub call: Option<CallEnd>,
32-}
33-
34 pub struct Left {28 pub struct Left {
35 pub community_id: String,29 pub community_id: String,
36 pub user_id: String,30 pub user_id: String,
@@ -38,11 +32,16 @@ pub struct Left {
38 pub call: Option<CallEnd>,32 pub call: Option<CallEnd>,
39 }33 }
40 34
35+enum Outcome {
36+ Ringing,
37+ Declined,
38+ Answered,
39+}
40+
41 struct Room {41 struct Room {
42 participants: Vec<Participant>,42 participants: Vec<Participant>,
43 started_ms: u64,43 started_ms: u64,
44- answered: bool,44+ outcome: Outcome,
45- declined: bool,
46 }45 }
47 46
48 impl Room {47 impl Room {
@@ -50,8 +49,7 @@ impl Room {
50 Self {49 Self {
51 participants: Vec::new(),50 participants: Vec::new(),
52 started_ms: time::now_ms(),51 started_ms: time::now_ms(),
53- answered: false,52+ outcome: Outcome::Ringing,
54- declined: false,
55 }53 }
56 }54 }
57 55
@@ -63,23 +61,20 @@ impl Room {
63 61
64 fn admit(&mut self) {62 fn admit(&mut self) {
65 if self.occupied() {63 if self.occupied() {
66- self.answered = true;64+ self.outcome = Outcome::Answered;
67 } else {65 } else {
68 self.started_ms = time::now_ms();66 self.started_ms = time::now_ms();
69- self.answered = false;67+ self.outcome = Outcome::Ringing;
70- self.declined = false;
71 }68 }
72 }69 }
73 70
74 fn end(&self) -> CallEnd {71 fn end(&self) -> CallEnd {
75- if self.answered {72+ match self.outcome {
76- CallEnd::Answered {73+ Outcome::Answered => CallEnd::Answered {
77 seconds: time::now_ms().saturating_sub(self.started_ms) / 1000,74 seconds: time::now_ms().saturating_sub(self.started_ms) / 1000,
78- }75+ },
79- } else if self.declined {76+ Outcome::Declined => CallEnd::Declined,
80- CallEnd::Declined77+ Outcome::Ringing => CallEnd::Unanswered,
81- } else {
82- CallEnd::Unanswered
83 }78 }
84 }79 }
85 }80 }
@@ -118,60 +113,45 @@ impl Voice {
118 }113 }
119 114
120 pub fn decline(&self, community_id: &str) {115 pub fn decline(&self, community_id: &str) {
121- if let Some(room) = self.0.lock().unwrap().get_mut(community_id) {116+ if let Some(room) = self.0.lock().unwrap().get_mut(community_id)
122- room.declined = true;117+ && matches!(room.outcome, Outcome::Ringing)
118+ {
119+ room.outcome = Outcome::Declined;
123 }120 }
124 }121 }
125 122
126 pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> {123 pub fn set_muted(&self, user_id: &str, muted: bool) -> Option<String> {
127 let mut rooms = self.0.lock().unwrap();124 let mut rooms = self.0.lock().unwrap();
128- for (community_id, room) in rooms.iter_mut() {125+ let (community_id, index) = locate(&rooms, user_id)?;
129- if let Some(participant) = room126+ rooms.get_mut(&community_id)?.participants[index].muted = muted;
130- .participants
131- .iter_mut()
132- .find(|participant| participant.user_id == user_id)
133- {
134- participant.muted = muted;
135-
136- return Some(community_id.clone());
137- }
138- }
139 127
140- None128+ Some(community_id)
141 }129 }
142 130
143- pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<GhostChange> {131+ pub fn set_ghost(&self, user_id: &str, ghost: bool) -> Option<Left> {
144 let mut rooms = self.0.lock().unwrap();132 let mut rooms = self.0.lock().unwrap();
145- for (community_id, room) in rooms.iter_mut() {133+ let (community_id, index) = locate(&rooms, user_id)?;
146- let Some(index) = room134+ let room = rooms.get_mut(&community_id)?;
147- .participants135+ if room.participants[index].ghost == ghost {
148- .iter()136+ return None;
149- .position(|participant| participant.user_id == user_id)
150- else {
151- continue;
152- };
153- if room.participants[index].ghost == ghost {
154- return None;
155- }
156- if !ghost {
157- room.admit();
158- }
159- let participant = &mut room.participants[index];
160- let seconds = participant
161- .ghost
162- .then(|| participant.joined_at.elapsed().as_secs());
163- participant.ghost = ghost;
164- participant.joined_at = Instant::now();
165- let call = (ghost && !room.occupied()).then(|| room.end());
166-
167- return Some(GhostChange {
168- community_id: community_id.clone(),
169- ghost_seconds: seconds,
170- call,
171- });
172 }137 }
138+ if !ghost {
139+ room.admit();
140+ }
141+ let participant = &mut room.participants[index];
142+ let seconds = participant
143+ .ghost
144+ .then(|| participant.joined_at.elapsed().as_secs());
145+ participant.ghost = ghost;
146+ participant.joined_at = Instant::now();
147+ let call = (ghost && !room.occupied()).then(|| room.end());
173 148
174- None149+ Some(Left {
150+ community_id,
151+ user_id: user_id.to_string(),
152+ ghost_seconds: seconds,
153+ call,
154+ })
175 }155 }
176 156
177 pub fn room_users(&self, community_id: &str) -> Vec<String> {157 pub fn room_users(&self, community_id: &str) -> Vec<String> {
@@ -189,16 +169,7 @@ impl Voice {
189 }169 }
190 170
191 pub fn room_of(&self, user_id: &str) -> Option<String> {171 pub fn room_of(&self, user_id: &str) -> Option<String> {
192- self.0172+ locate(&self.0.lock().unwrap(), user_id).map(|(community_id, _)| community_id)
193- .lock()
194- .unwrap()
195- .iter()
196- .find(|(_, room)| {
197- room.participants
198- .iter()
199- .any(|participant| participant.user_id == user_id)
200- })
201- .map(|(community_id, _)| community_id.clone())
202 }173 }
203 174
204 pub fn leave(&self, user_id: &str) -> Option<Left> {175 pub fn leave(&self, user_id: &str) -> Option<Left> {
@@ -342,15 +313,17 @@ fn remove(rooms: &mut Rooms, community_id: &str, user_id: &str) -> Option<Left>
342 Some(left(community_id, participant, call))313 Some(left(community_id, participant, call))
343 }314 }
344 315
316+fn locate(rooms: &Rooms, user_id: &str) -> Option<(String, usize)> {
317+ rooms.iter().find_map(|(community_id, room)| {
318+ room.participants
319+ .iter()
320+ .position(|participant| participant.user_id == user_id)
321+ .map(|index| (community_id.clone(), index))
322+ })
323+}
324+
345 fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option<Left> {325 fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option<Left> {
346- let community_id = rooms326+ let (community_id, _) = locate(rooms, user_id)?;
347- .iter()
348- .find(|(_, room)| {
349- room.participants
350- .iter()
351- .any(|participant| participant.user_id == user_id)
352- })
353- .map(|(community_id, _)| community_id.clone())?;
354 327
355 remove(rooms, &community_id, user_id)328 remove(rooms, &community_id, user_id)
356 }329 }