forge
Explore
Log in

Don't you dare go Hollow

Add voice, media, social features, moderation and multiple accounts

Browse files at this commit

543f6119de52765d7b05a5b1077f5041f84bdd95Ahmet Kaan GümüşParent: c09f337
  • feat
    • add voice, media, social features, moderation and multiple accounts
Show full message
✨ feat: add voice, media, social features, moderation and multiple accounts

Voice: QUIC datagram voice with Opus, a jitter buffer and per-speaker mixing. Voice activity or push-to-talk (modifier keys included), input and output device selection, volume and sensitivity. Settings can loop the mic through the full call pipeline and play a speaker chime.

Media: attachments with image, audio and video playback, snippets and message forwarding. FLAC files that do not state their length get it from the last frame instead of a full scan.

Social: direct messages, friends, community invitations with a user lookup that shows existing members, and live user search. Messages from former members keep the original username.

Moderation: member ranks with a single permission module, kick, ban with reason and unban. Bans and a new community log (renames, picture changes, invites, joins, leaves, kicks, bans, rank changes, moderator deletions) open in popups with search and sorting.

Accounts: several saved accounts with session resume and auto login. A Detach request signs a connection out while keeping its session, and signing in leaves voice first.

UI: settings pages for user and community, profile cards, community and user pictures that drive the accent colour of headers, dialogs and inputs, and New community in the Communities tab context menu. The README gets screenshots.

New request, response and error variants are appended to keep wire indices stable.

68 changed files +15307 -899

Cargo.tomlmodified+3 -0
@@ -5,6 +5,9 @@ members = ["crates/client", "crates/common", "crates/server"]
5 [profile.dev]5 [profile.dev]
6 debug = "line-tables-only"6 debug = "line-tables-only"
7 7
8+[profile.dev.package."*"]
9+opt-level = 3
10+
8 [profile.release]11 [profile.release]
9 opt-level = 312 opt-level = 3
10 lto = "fat"13 lto = "fat"
README.mdmodified+13 -1
@@ -1,4 +1,16 @@
1 # Yumush(ju'muʃ)1 # Yumush(ju'muʃ)
2 Yumush is based from a Turkish word "Yumuş" which means request, word, message.2 Yumush is based from a Turkish word "Yumuş" which means request, word, message.
3 3
4-In this project no AI auto-code is allowed. Only I code. Just passion.4+Self-hosted chat with communities, direct messages and voice. Rust, QUIC, gpui.
5+
6+![Community](docs/screenshots/community.png)
7+![Direct messages](docs/screenshots/direct.png)
8+![Black theme](docs/screenshots/black.png)
9+
10+## Features
11+- Communities by invitation, with ranks, kick and ban with reasons, and pictures
12+- Direct messages and friends
13+- Reply, edit, forward, and forwarding multiple messages as one snippet
14+- Images, video, audio and file attachments
15+- Voice rooms
16+- Light, dark and black themes
crates/client/Cargo.tomlmodified+28 -0
@@ -9,8 +9,36 @@ tokio.workspace = true
9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }9 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
10 10
11 gpui-kit = "0.11.0"11 gpui-kit = "0.11.0"
12+ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
13+ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
14+ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
15+ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
16+ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
17+ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
18+ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
19+ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
20+ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
21+ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
22+ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
23+ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" }
24+ureq = "3.5.2"
25+bytes = "1.12.2"
12 tracing = "0.1.44"26 tracing = "0.1.44"
13 tracing-subscriber = "0.3.23"27 tracing-subscriber = "0.3.23"
28+uuid = "1.29.3"
29+jiff = "1.0.2"
30+dirs = "7.0.0"
31+image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] }
32+rtrb = "0.4.1"
33+
34+[target.'cfg(target_os = "linux")'.dependencies]
35+pipewire = { version = "0.10.1", features = ["v0_3_49"] }
36+
37+[target.'cfg(target_os = "windows")'.dependencies]
38+wasapi = "0.27.0"
39+
40+[target.'cfg(target_os = "macos")'.dependencies]
41+coreaudio-rs = "0.14.2"
14 42
15 [lints]43 [lints]
16 workspace = true44 workspace = true
crates/client/src/accounts.rsadded+132 -0
@@ -0,0 +1,132 @@
1+use std::{fs, path::PathBuf};
2+
3+use common::model::User;
4+use tracing::warn;
5+
6+#[derive(Debug, Clone, PartialEq, Eq)]
7+pub struct Account {
8+ pub user_id: String,
9+ pub username: String,
10+ pub token: String,
11+}
12+
13+#[derive(Debug, Clone, Default)]
14+pub struct Accounts {
15+ pub list: Vec<Account>,
16+ pub active: Option<String>,
17+}
18+
19+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> {
26+ self.list.iter().find(|account| account.user_id == user_id)
27+ }
28+
29+ pub fn others(&self) -> impl Iterator<Item = &Account> {
30+ self.list
31+ .iter()
32+ .filter(|account| Some(&account.user_id) != self.active.as_ref())
33+ }
34+
35+ pub fn sign_in(&mut self, user: &User, token: String) {
36+ self.remove(&user.id);
37+ self.list.push(Account {
38+ user_id: user.id.clone(),
39+ username: user.username.clone(),
40+ token,
41+ });
42+ self.active = Some(user.id.clone());
43+ save(self);
44+ }
45+
46+ pub fn rename(&mut self, user: &User) {
47+ if let Some(account) = self
48+ .list
49+ .iter_mut()
50+ .find(|account| account.user_id == user.id)
51+ {
52+ account.username = user.username.clone();
53+ save(self);
54+ }
55+ }
56+
57+ pub fn detach(&mut self) {
58+ self.active = None;
59+ save(self);
60+ }
61+
62+ pub fn forget(&mut self, user_id: &str) {
63+ self.remove(user_id);
64+ if self.active.as_deref() == Some(user_id) {
65+ self.active = None;
66+ }
67+ save(self);
68+ }
69+
70+ fn remove(&mut self, user_id: &str) {
71+ self.list.retain(|account| account.user_id != user_id);
72+ }
73+}
74+
75+fn path() -> Option<PathBuf> {
76+ dirs::config_dir().map(|dir| dir.join("yumush").join("accounts"))
77+}
78+
79+pub fn load() -> Accounts {
80+ let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else {
81+ return Accounts::default();
82+ };
83+ let mut accounts = Accounts::default();
84+
85+ for line in content.lines() {
86+ match line.split('\t').collect::<Vec<_>>().as_slice() {
87+ ["active", user_id] => accounts.active = Some(user_id.to_string()),
88+ [user_id, username, token] => accounts.list.push(Account {
89+ user_id: user_id.to_string(),
90+ username: username.to_string(),
91+ token: token.to_string(),
92+ }),
93+ _ => {}
94+ }
95+ }
96+
97+ accounts
98+}
99+
100+fn save(accounts: &Accounts) {
101+ let Some(path) = path() else {
102+ return;
103+ };
104+ let mut content: String = accounts
105+ .list
106+ .iter()
107+ .map(|account| {
108+ format!(
109+ "{}\t{}\t{}\n",
110+ account.user_id, account.username, account.token
111+ )
112+ })
113+ .collect();
114+ if let Some(active) = &accounts.active {
115+ content.push_str(&format!("active\t{active}\n"));
116+ }
117+
118+ if let Err(error) = write_private(&path, &content) {
119+ warn!("save accounts failed: {error}");
120+ }
121+}
122+
123+fn write_private(path: &PathBuf, content: &str) -> std::io::Result<()> {
124+ if let Some(parent) = path.parent() {
125+ fs::create_dir_all(parent)?;
126+ }
127+ let mut options = fs::OpenOptions::new();
128+ options.write(true).create(true).truncate(true);
129+ #[cfg(unix)]
130+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
131+ std::io::Write::write_all(&mut options.open(path)?, content.as_bytes())
132+}
crates/client/src/avatar.rsadded+88 -0
@@ -0,0 +1,88 @@
1+use common::{
2+ constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES},
3+ error::{Error, InvalidInput},
4+};
5+use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType};
6+
7+const QUALITIES: [u8; 3] = [85, 60, 40];
8+
9+pub fn prepare(bytes: &[u8]) -> Result<Vec<u8>, Error> {
10+ let image = image::load_from_memory(bytes).map_err(decode_error)?;
11+ let square = center_square(image)
12+ .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3)
13+ .to_rgb8();
14+
15+ let mut encoded = Vec::new();
16+ for quality in QUALITIES {
17+ encoded = encode(&square, quality)?;
18+ if encoded.len() <= MAXIMUM_AVATAR_BYTES {
19+ return Ok(encoded);
20+ }
21+ }
22+
23+ Err(Error::Avatar(InvalidInput::TooLarge {
24+ maximum: MAXIMUM_AVATAR_BYTES as u64,
25+ actual: encoded.len() as u64,
26+ }))
27+}
28+
29+fn center_square(image: DynamicImage) -> DynamicImage {
30+ let side = image.width().min(image.height());
31+ let x = (image.width() - side) / 2;
32+ let y = (image.height() - side) / 2;
33+
34+ image.crop_imm(x, y, side, side)
35+}
36+
37+fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Error> {
38+ let mut bytes = Vec::new();
39+ JpegEncoder::new_with_quality(&mut bytes, quality)
40+ .encode_image(image)
41+ .map_err(decode_error)?;
42+
43+ Ok(bytes)
44+}
45+
46+fn decode_error(error: image::ImageError) -> Error {
47+ Error::Decode(error.to_string())
48+}
49+
50+const HUE_BINS: usize = 24;
51+
52+pub fn dominant_hue(bytes: &[u8]) -> Option<f32> {
53+ let image = image::load_from_memory(bytes)
54+ .ok()?
55+ .thumbnail(32, 32)
56+ .to_rgb8();
57+ let mut bins = [(0.0f32, 0.0f32, 0.0f32); HUE_BINS];
58+
59+ for pixel in image.pixels() {
60+ let [r, g, b] = pixel.0.map(|channel| channel as f32 / 255.);
61+ let max = r.max(g).max(b);
62+ let min = r.min(g).min(b);
63+ let chroma = max - min;
64+ if chroma < 0.15 {
65+ continue;
66+ }
67+ let hue = if max == r {
68+ ((g - b) / chroma).rem_euclid(6.)
69+ } else if max == g {
70+ (b - r) / chroma + 2.
71+ } else {
72+ (r - g) / chroma + 4.
73+ } / 6.;
74+ let angle = hue * std::f32::consts::TAU;
75+ let bin = &mut bins[(hue * HUE_BINS as f32) as usize % HUE_BINS];
76+ bin.0 += chroma;
77+ bin.1 += angle.cos() * chroma;
78+ bin.2 += angle.sin() * chroma;
79+ }
80+
81+ let total: f32 = bins.iter().map(|bin| bin.0).sum();
82+ let (weight, x, y) = bins.into_iter().max_by(|a, b| a.0.total_cmp(&b.0))?;
83+ if weight < total * 0.05 || total < (image.len() / 3) as f32 * 0.03 {
84+ return None;
85+ }
86+
87+ Some(y.atan2(x).rem_euclid(std::f32::consts::TAU) / std::f32::consts::TAU)
88+}
crates/client/src/embed.rsadded+365 -0
@@ -0,0 +1,365 @@
1+use std::io::Read;
2+use std::time::Duration;
3+
4+use ureq::http::Uri;
5+use ureq::{Agent, Body, ResponseExt};
6+
7+const MAX_LINKS: usize = 3;
8+const MAX_IMAGE: u64 = 5 * 1024 * 1024;
9+const MAX_HTML: u64 = 512 * 1024;
10+const MAX_TITLE: usize = 256;
11+const MAX_DESCRIPTION: usize = 512;
12+
13+#[derive(Debug, Clone, PartialEq, Eq)]
14+pub enum EmbedKind {
15+ Page,
16+ Image,
17+}
18+
19+#[derive(Debug, Clone, PartialEq, Eq)]
20+pub struct Embed {
21+ pub url: String,
22+ pub kind: EmbedKind,
23+ pub site: Option<String>,
24+ pub title: Option<String>,
25+ pub description: Option<String>,
26+ pub image: Option<Vec<u8>>,
27+}
28+
29+#[derive(Debug, PartialEq, Eq)]
30+struct Meta {
31+ title: Option<String>,
32+ description: Option<String>,
33+ image: Option<String>,
34+ site: Option<String>,
35+}
36+
37+pub fn urls(text: &str) -> Vec<String> {
38+ let mut out: Vec<String> = Vec::new();
39+ let mut rest = text;
40+ while out.len() < MAX_LINKS {
41+ let Some(start) = find_scheme(rest) else {
42+ break;
43+ };
44+ let tail = &rest[start..];
45+ let end = tail
46+ .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"'))
47+ .unwrap_or(tail.len());
48+ rest = &tail[end..];
49+ let link = trim_link(&tail[..end]);
50+ let has_host = link.find("://").is_some_and(|i| link.len() > i + 3);
51+ if has_host && !out.iter().any(|u| u == link) {
52+ out.push(link.to_owned());
53+ }
54+ }
55+ out
56+}
57+
58+fn find_scheme(s: &str) -> Option<usize> {
59+ match (s.find("http://"), s.find("https://")) {
60+ (Some(a), Some(b)) => Some(a.min(b)),
61+ (a, b) => a.or(b),
62+ }
63+}
64+
65+fn trim_link(s: &str) -> &str {
66+ let mut s = s;
67+ loop {
68+ let t = s.trim_end_matches(['.', ',', ';', ':', '!', '?']);
69+ let t = if t.ends_with(')') && t.matches(')').count() > t.matches('(').count() {
70+ &t[..t.len() - 1]
71+ } else {
72+ t
73+ };
74+ if t.len() == s.len() {
75+ return s;
76+ }
77+ s = t;
78+ }
79+}
80+
81+pub fn fetch(url: &str) -> Option<Embed> {
82+ if !is_web(url) {
83+ return None;
84+ }
85+ let agent = Agent::new_with_config(
86+ Agent::config_builder()
87+ .timeout_global(Some(Duration::from_secs(5)))
88+ .max_redirects(5)
89+ .user_agent("yumush")
90+ .http_status_as_error(true)
91+ .build(),
92+ );
93+ let mut resp = agent.get(url).call().ok()?;
94+ let final_url = resp.get_uri().to_string();
95+ let mime = mime_of(&resp)?;
96+
97+ if is_image(&mime) {
98+ let image = read_image(&mut resp)?;
99+ return Some(Embed {
100+ url: url.to_owned(),
101+ kind: EmbedKind::Image,
102+ site: None,
103+ title: last_segment(&final_url),
104+ description: None,
105+ image: Some(image),
106+ });
107+ }
108+ if mime != "text/html" {
109+ return None;
110+ }
111+
112+ let mut bytes = Vec::new();
113+ resp.body_mut()
114+ .as_reader()
115+ .take(MAX_HTML)
116+ .read_to_end(&mut bytes)
117+ .ok()?;
118+ let meta = parse_meta(&String::from_utf8_lossy(&bytes));
119+
120+ let image = meta
121+ .image
122+ .and_then(|src| resolve(&final_url, &src))
123+ .and_then(|img| fetch_image(&agent, &img));
124+ if meta.title.is_none() && image.is_none() {
125+ return None;
126+ }
127+
128+ let host = final_url
129+ .parse::<Uri>()
130+ .ok()
131+ .and_then(|u| u.host().map(str::to_owned));
132+ Some(Embed {
133+ url: url.to_owned(),
134+ kind: EmbedKind::Page,
135+ site: meta.site.or(host),
136+ title: meta.title,
137+ description: meta.description,
138+ image,
139+ })
140+}
141+
142+fn is_web(url: &str) -> bool {
143+ url.parse::<Uri>()
144+ .is_ok_and(|u| matches!(u.scheme_str(), Some("http" | "https")))
145+}
146+
147+fn mime_of(resp: &ureq::http::Response<Body>) -> Option<String> {
148+ let mime = resp.body().mime_type()?;
149+ Some(mime.trim().to_ascii_lowercase())
150+}
151+
152+fn is_image(mime: &str) -> bool {
153+ matches!(
154+ mime,
155+ "image/png" | "image/jpeg" | "image/gif" | "image/webp"
156+ )
157+}
158+
159+fn read_image(resp: &mut ureq::http::Response<Body>) -> Option<Vec<u8>> {
160+ resp.body_mut()
161+ .with_config()
162+ .limit(MAX_IMAGE)
163+ .read_to_vec()
164+ .ok()
165+}
166+
167+fn fetch_image(agent: &Agent, url: &str) -> Option<Vec<u8>> {
168+ if !is_web(url) {
169+ return None;
170+ }
171+ let mut resp = agent.get(url).call().ok()?;
172+ if !is_image(&mime_of(&resp)?) {
173+ return None;
174+ }
175+ read_image(&mut resp)
176+}
177+
178+fn last_segment(url: &str) -> Option<String> {
179+ let path = url.parse::<Uri>().ok()?.path().to_owned();
180+ path.rsplit('/').find(|s| !s.is_empty()).map(str::to_owned)
181+}
182+
183+fn resolve(base: &str, src: &str) -> Option<String> {
184+ let src = src.trim();
185+ if src.starts_with("http://") || src.starts_with("https://") {
186+ return Some(src.to_owned());
187+ }
188+ let base = base.parse::<Uri>().ok()?;
189+ let scheme = base.scheme_str()?;
190+ let authority = base.authority()?.as_str();
191+ if let Some(rest) = src.strip_prefix("//") {
192+ return Some(format!("{scheme}://{rest}"));
193+ }
194+ if src.starts_with('/') {
195+ return Some(format!("{scheme}://{authority}{src}"));
196+ }
197+ let path = base.path();
198+ let dir = match path.rfind('/') {
199+ Some(i) => &path[..=i],
200+ None => "/",
201+ };
202+ Some(format!("{scheme}://{authority}{dir}{src}"))
203+}
204+
205+fn parse_meta(html: &str) -> Meta {
206+ let lower = html.to_ascii_lowercase();
207+ let mut tags: Vec<(String, String)> = Vec::new();
208+ for (pos, _) in lower.match_indices("<meta") {
209+ let mut key = None;
210+ let mut content = None;
211+ for (name, value) in attributes(&html[pos + 5..]) {
212+ match name.as_str() {
213+ "property" | "name" => key = Some(value),
214+ "content" => content = Some(value),
215+ _ => {}
216+ }
217+ }
218+ if let (Some(k), Some(c)) = (key, content) {
219+ tags.push((k.to_ascii_lowercase(), c));
220+ }
221+ }
222+
223+ let found = |names: &[&str]| -> Option<String> {
224+ names.iter().find_map(|n| {
225+ tags.iter()
226+ .find(|(k, _)| k.as_str() == *n)
227+ .map(|(_, v)| v.clone())
228+ })
229+ };
230+
231+ let title = found(&["og:title", "twitter:title"])
232+ .or_else(|| tag_text(html, &lower, "<title", "</title"));
233+
234+ Meta {
235+ title: title
236+ .map(|t| clean(&t, MAX_TITLE))
237+ .filter(|t| !t.is_empty()),
238+ description: found(&["og:description", "twitter:description", "description"])
239+ .map(|d| clean(&d, MAX_DESCRIPTION))
240+ .filter(|d| !d.is_empty()),
241+ image: found(&["og:image", "twitter:image"]).map(|i| i.trim().to_owned()),
242+ site: found(&["og:site_name"])
243+ .map(|s| clean(&s, MAX_TITLE))
244+ .filter(|s| !s.is_empty()),
245+ }
246+}
247+
248+fn tag_text(html: &str, lower: &str, open: &str, close: &str) -> Option<String> {
249+ let start = lower.find(open)?;
250+ let body = start + lower[start..].find('>')? + 1;
251+ let end = body + lower[body..].find(close)?;
252+ Some(html[body..end].to_owned())
253+}
254+
255+fn attributes(tag: &str) -> Vec<(String, String)> {
256+ let mut out = Vec::new();
257+ let mut rest = tag;
258+ loop {
259+ rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '/');
260+ if rest.is_empty() || rest.starts_with('>') {
261+ break;
262+ }
263+ let end = rest
264+ .find(|c: char| c.is_whitespace() || c == '=' || c == '>')
265+ .unwrap_or(rest.len());
266+ let name = rest[..end].to_ascii_lowercase();
267+ rest = rest[end..].trim_start();
268+ let mut value = String::new();
269+ if let Some(after) = rest.strip_prefix('=') {
270+ let after = after.trim_start();
271+ match after.chars().next() {
272+ Some(q @ ('"' | '\'')) => {
273+ let body = &after[1..];
274+ let close = body.find(q).unwrap_or(body.len());
275+ value = body[..close].to_owned();
276+ rest = &body[(close + 1).min(body.len())..];
277+ }
278+ _ => {
279+ let close = after
280+ .find(|c: char| c.is_whitespace() || c == '>')
281+ .unwrap_or(after.len());
282+ value = after[..close].to_owned();
283+ rest = &after[close..];
284+ }
285+ }
286+ }
287+ out.push((name, value));
288+ }
289+ out
290+}
291+
292+fn clean(s: &str, max: usize) -> String {
293+ decode(s)
294+ .split_whitespace()
295+ .collect::<Vec<_>>()
296+ .join(" ")
297+ .chars()
298+ .take(max)
299+ .collect()
300+}
301+
302+fn decode(s: &str) -> String {
303+ let mut out = String::new();
304+ let mut rest = s;
305+ while let Some(i) = rest.find('&') {
306+ out.push_str(&rest[..i]);
307+ rest = &rest[i..];
308+ if let Some(semi) = rest.find(';').filter(|&j| j <= 10)
309+ && let Some(c) = entity(&rest[1..semi])
310+ {
311+ out.push(c);
312+ rest = &rest[semi + 1..];
313+ continue;
314+ }
315+ out.push('&');
316+ rest = &rest[1..];
317+ }
318+ out.push_str(rest);
319+ out
320+}
321+
322+fn entity(e: &str) -> Option<char> {
323+ match e {
324+ "amp" => Some('&'),
325+ "lt" => Some('<'),
326+ "gt" => Some('>'),
327+ "quot" => Some('"'),
328+ "#39" | "#x27" => Some('\''),
329+ _ => match e.strip_prefix("#x") {
330+ Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?),
331+ None => char::from_u32(e.strip_prefix('#')?.parse().ok()?),
332+ },
333+ }
334+}
335+
336+#[cfg(test)]
337+mod tests {
338+ use super::*;
339+
340+ #[test]
341+ fn parse_meta_reads_mixed_attributes_and_entities() {
342+ let html = r#"<title>Ignored</title><META content="Og &quot;Title&quot;" property="og:title"><meta name='description' content='It&#39;s &#x27;here&#x27;'><meta content="https://img.test/a.png" property="og:image"><meta property="og:site_name" content='Site'>"#;
343+ let meta = parse_meta(html);
344+ assert_eq!(meta.title.as_deref(), Some("Og \"Title\""));
345+ assert_eq!(meta.description.as_deref(), Some("It's 'here'"));
346+ assert_eq!(meta.image.as_deref(), Some("https://img.test/a.png"));
347+ assert_eq!(meta.site.as_deref(), Some("Site"));
348+ assert_eq!(
349+ parse_meta("<title> A\n B &amp; C </title>")
350+ .title
351+ .as_deref(),
352+ Some("A B & C")
353+ );
354+ }
355+
356+ #[test]
357+ fn urls_trims_punctuation_and_dedups() {
358+ let text = "see (https://a.com/x), https://b.com/y. and <https://c.com/z>! https://a.com/x http://d.com/w?q=1 https://e.com";
359+ assert_eq!(
360+ urls(text),
361+ ["https://a.com/x", "https://b.com/y", "https://c.com/z"]
362+ );
363+ assert_eq!(urls("https://w.org/a_(b)"), ["https://w.org/a_(b)"]);
364+ }
365+}
crates/client/src/gui.rsmodified+733 -55
@@ -1,23 +1,411 @@
1-use std::fmt::Display;1+use std::{
2+ collections::HashMap,
3+ fmt::Display,
4+ hash::{DefaultHasher, Hash, Hasher},
5+ sync::Arc,
6+};
2 7
3-use common::model::User;8+use common::{
9+ error::Error,
10+ event::Event,
11+ model::{Community, CommunityKind, Rank, User},
12+};
4 use gpui_kit::{13 use gpui_kit::{
5- AppContext, AsyncWindowContext, Context, Entity, IntoElement, ParentElement, Render, Styled,14+ AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight,
6- WeakEntity, Window,15+ Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent,
16+ KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Render, RenderOnce, Stateful,
17+ StatefulInteractiveElement, Styled, WeakEntity, Window, actions,
18+ base::Selectable,
7 component::{19 component::{
8- ActiveTheme, WindowExt, button::Button, input::InputState, notification::Notification,20+ ActiveTheme, Theme, WindowExt,
21+ input::{Input, InputEvent, InputState},
22+ notification::Notification,
9 },23 },
10- div, rgb,24+ div, hsla, img, px, rgb,
11 };25 };
26+use jiff::{Timestamp, tz::TimeZone};
12 use tokio::sync::mpsc;27 use tokio::sync::mpsc;
28+use uuid::Uuid;
13 29
14-use crate::network::{NetworkEvent, NetworkHandle};30+use crate::{
31+ accounts::{self, Accounts},
32+ network::{NetworkEvent, NetworkHandle},
33+ settings::{Look, Settings, ThemeChoice},
34+};
15 35
16 mod auth;36 mod auth;
17 mod chat;37 mod chat;
38+mod community_settings;
39+mod composer;
40+mod forward;
41+mod media_view;
42+mod message_actions;
43+mod profile;
44+mod settings_page;
45+mod sidebar;
46+mod snippet;
47+mod social;
48+mod voice_settings;
18 49
19 use auth::Auth;50 use auth::Auth;
20-use chat::Chat;51+use chat::{Chat, View};
52+use voice_settings::VoiceControls;
53+
54+actions!(yumush, [FocusFind, CloseSettings]);
55+
56+const TINTS: [u32; 10] = [
57+ 0x10b981, 0xa855f7, 0xf59e0b, 0xf97316, 0xec4899, 0x0ea5e9, 0x22c55e, 0xef4444, 0x06b6d4,
58+ 0xd946ef,
59+];
60+
61+#[derive(Clone, Copy)]
62+pub struct Palette {
63+ pub window: Hsla,
64+ pub panel: Hsla,
65+ pub field: Hsla,
66+ pub border: Hsla,
67+ pub text: Hsla,
68+ pub body: Hsla,
69+ pub muted: Hsla,
70+ pub hover: Hsla,
71+ pub accent: Hsla,
72+ pub on_accent: Hsla,
73+ pub ok: Hsla,
74+ pub danger: Hsla,
75+ pub alert: Hsla,
76+ pub dark: bool,
77+}
78+
79+impl Palette {
80+ pub fn tinted(self, id: &str) -> Hsla {
81+ let color = tint(id);
82+ if self.dark {
83+ color
84+ } else {
85+ hsla(color.h, color.s, color.l * 0.62, 1.)
86+ }
87+ }
88+
89+ pub fn for_community(self, community: Option<&Community>, hues: &HashMap<String, f32>) -> Self {
90+ let Some(community) = community else {
91+ return self;
92+ };
93+ let (id, avatar_id) = match &community.kind {
94+ CommunityKind::Group => (&community.id, &community.avatar_id),
95+ CommunityKind::Direct { peer } => (&peer.id, &peer.avatar_id),
96+ };
97+ let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) {
98+ Some(&hue) if self.dark => hsla(hue, 0.75, 0.55, 1.),
99+ Some(&hue) => hsla(hue, 0.75, 0.4, 1.),
100+ None => self.tinted(id),
101+ };
102+ Palette { accent, ..self }
103+ }
104+}
105+
106+pub fn palette(cx: &App) -> Palette {
107+ let black = cx
108+ .try_global::<Look>()
109+ .is_some_and(|look| look.0 == ThemeChoice::Black);
110+ let dark = cx.theme().is_dark();
111+ let (window, panel, field, border, text, body, muted, hover) = match (dark, black) {
112+ (true, true) => (
113+ 0x000000, 0x000000, 0x0e0e11, 0x1d1d22, 0xececf0, 0xd4d4da, 0x8f8f99, 0x16161a,
114+ ),
115+ (true, false) => (
116+ 0x121419, 0x191c23, 0x20232b, 0x2a2e38, 0xececf0, 0xd4d6de, 0x9094a0, 0x232733,
117+ ),
118+ _ => (
119+ 0xf3f4f8, 0xffffff, 0xffffff, 0xe1e3ea, 0x1c1d24, 0x33353f, 0x6b6e7a, 0xe8eaf1,
120+ ),
121+ };
122+ let (accent, alert) = if dark {
123+ (0xec4899, 0xef4444)
124+ } else {
125+ (0xdb2777, 0xdc2626)
126+ };
127+
128+ Palette {
129+ window: rgb(window).into(),
130+ panel: rgb(panel).into(),
131+ field: rgb(field).into(),
132+ border: rgb(border).into(),
133+ text: rgb(text).into(),
134+ body: rgb(body).into(),
135+ muted: rgb(muted).into(),
136+ hover: rgb(hover).into(),
137+ accent: rgb(accent).into(),
138+ on_accent: rgb(0xffffff).into(),
139+ ok: rgb(0x3fb950).into(),
140+ danger: rgb(0xd1483f).into(),
141+ alert: rgb(alert).into(),
142+ dark,
143+ }
144+}
145+
146+pub fn sync_accent(accent: Hsla, cx: &mut App) {
147+ let theme = Theme::global_mut(cx);
148+ if theme.colors.ring == accent {
149+ return;
150+ }
151+ let colors = &mut theme.colors;
152+ colors.primary = accent;
153+ colors.primary_hover = accent.opacity(0.85);
154+ colors.primary_active = accent;
155+ colors.ring = accent;
156+ colors.caret = accent;
157+ theme.tokens = (&theme.colors).into();
158+}
159+
160+pub fn sync_theme(cx: &mut App) {
161+ let palette = palette(cx);
162+ let theme = Theme::global_mut(cx);
163+ let colors = &mut theme.colors;
164+
165+ colors.background = palette.panel;
166+ colors.foreground = palette.text;
167+ colors.popover = palette.panel;
168+ colors.popover_foreground = palette.text;
169+ colors.border = palette.border;
170+ colors.input = palette.border;
171+ colors.muted = palette.field;
172+ colors.muted_foreground = palette.muted;
173+ colors.accent = palette.hover;
174+ colors.accent_foreground = palette.text;
175+ colors.list_hover = palette.hover;
176+ colors.secondary = palette.field;
177+ colors.secondary_foreground = palette.text;
178+ colors.primary = palette.accent;
179+ colors.primary_hover = palette.accent.opacity(0.85);
180+ colors.primary_active = palette.accent;
181+ colors.primary_foreground = palette.on_accent;
182+ colors.ring = palette.accent;
183+ colors.caret = palette.accent;
184+ colors.danger = palette.danger;
185+ theme.tokens = (&theme.colors).into();
186+ theme.radius = px(6.);
187+ theme.radius_lg = px(10.);
188+ theme.font_size = px(14.);
189+ theme.focus_ring = false;
190+}
191+
192+const FIND_KEY: &str = "ctrl-k";
193+pub const FIND_HINT: &str = "Ctrl K";
194+
195+pub fn tint(id: &str) -> Hsla {
196+ let mut hasher = DefaultHasher::new();
197+ id.hash(&mut hasher);
198+ rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into()
199+}
200+
201+pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Pixels) -> Div {
202+ let initial = name
203+ .chars()
204+ .next()
205+ .unwrap_or('?')
206+ .to_uppercase()
207+ .to_string();
208+
209+ div()
210+ .size(size)
211+ .flex_shrink_0()
212+ .flex()
213+ .items_center()
214+ .justify_center()
215+ .bg(tint(id))
216+ .text_color(palette.on_accent)
217+ .text_size(font)
218+ .font_weight(FontWeight::SEMIBOLD)
219+ .child(initial)
220+}
221+
222+pub fn avatar(
223+ palette: Palette,
224+ user: &User,
225+ size: Pixels,
226+ font: Pixels,
227+ avatars: &HashMap<String, Arc<Image>>,
228+) -> Div {
229+ let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else {
230+ return badge(palette, &user.id, &user.username, size, font).rounded_full();
231+ };
232+
233+ div()
234+ .size(size)
235+ .flex_shrink_0()
236+ .rounded_full()
237+ .overflow_hidden()
238+ .child(img(image.clone()).size_full().rounded_full())
239+}
240+
241+pub fn community_name(community: &Community) -> &str {
242+ match &community.kind {
243+ CommunityKind::Group => &community.name,
244+ CommunityKind::Direct { peer } => &peer.username,
245+ }
246+}
247+
248+pub fn community_icon(
249+ palette: Palette,
250+ community: &Community,
251+ size: Pixels,
252+ font: Pixels,
253+ avatars: &HashMap<String, Arc<Image>>,
254+) -> Div {
255+ match &community.kind {
256+ CommunityKind::Group => match community.avatar_id.as_ref().and_then(|id| avatars.get(id)) {
257+ Some(image) => div()
258+ .size(size)
259+ .flex_shrink_0()
260+ .rounded(px(4.))
261+ .overflow_hidden()
262+ .child(img(image.clone()).size_full()),
263+ None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)),
264+ },
265+ CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars),
266+ }
267+}
268+
269+pub fn id_time(id: &str, format: &str) -> String {
270+ let Some((seconds, nanos)) = Uuid::parse_str(id)
271+ .ok()
272+ .and_then(|uuid| uuid.get_timestamp())
273+ .map(|timestamp| timestamp.to_unix())
274+ else {
275+ return String::new();
276+ };
277+ let Ok(timestamp) = Timestamp::new(seconds as i64, nanos as i32) else {
278+ return String::new();
279+ };
280+
281+ timestamp
282+ .to_zoned_datetime(TimeZone::system())
283+ .strftime(format)
284+ .to_string()
285+}
286+
287+pub fn hoverable(id: impl Into<ElementId>, element: Div, palette: Palette) -> Stateful<Div> {
288+ hoverable_with(id, element, palette.hover)
289+}
290+
291+pub fn hoverable_with(id: impl Into<ElementId>, element: Div, hover: Hsla) -> Stateful<Div> {
292+ element
293+ .id(id)
294+ .cursor_pointer()
295+ .hover(move |style| style.bg(hover))
296+}
297+
298+pub fn clickable(
299+ id: impl Into<ElementId>,
300+ palette: Palette,
301+ on_click: impl Fn(&mut Window, &mut App) + 'static,
302+) -> Stateful<Div> {
303+ hoverable(id, div(), palette).on_click(move |_, window, cx| on_click(window, cx))
304+}
305+
306+pub fn entity_action<T: 'static>(
307+ entity: &Entity<T>,
308+ run: impl Fn(&mut T, &mut Window, &mut Context<T>) + 'static,
309+) -> impl Fn(&mut Window, &mut App) + 'static {
310+ let entity = entity.clone();
311+
312+ move |window, cx| entity.update(cx, |state, cx| run(state, window, cx))
313+}
314+
315+pub struct Tip(&'static str);
316+
317+impl Render for Tip {
318+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
319+ let palette = palette(cx);
320+ div()
321+ .px(px(6.))
322+ .py(px(3.))
323+ .rounded(px(4.))
324+ .border_1()
325+ .border_color(palette.border)
326+ .bg(palette.panel)
327+ .text_color(palette.text)
328+ .text_size(px(12.))
329+ .child(self.0)
330+ }
331+}
332+
333+pub trait Tooltip {
334+ fn tip(self, text: &'static str) -> Self;
335+}
336+
337+impl Tooltip for Stateful<Div> {
338+ fn tip(self, text: &'static str) -> Self {
339+ self.tooltip(move |_, cx| cx.new(|_| Tip(text)).into())
340+ }
341+}
342+
343+pub fn primary_button(
344+ id: impl Into<ElementId>,
345+ palette: Palette,
346+ on_click: impl Fn(&mut Window, &mut App) + 'static,
347+) -> Stateful<Div> {
348+ div()
349+ .id(id)
350+ .cursor_pointer()
351+ .on_click(move |_, window, cx| on_click(window, cx))
352+ .bg(palette.accent)
353+ .text_color(palette.on_accent)
354+ .hover(|style| style.opacity(0.85))
355+}
356+
357+#[derive(IntoElement)]
358+pub struct Trigger(AnyElement);
359+
360+impl Trigger {
361+ pub fn new(content: impl IntoElement) -> Self {
362+ Self(content.into_any_element())
363+ }
364+}
365+
366+impl Selectable for Trigger {
367+ fn selected(self, _: bool) -> Self {
368+ self
369+ }
370+
371+ fn is_selected(&self) -> bool {
372+ false
373+ }
374+}
375+
376+impl RenderOnce for Trigger {
377+ fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
378+ self.0
379+ }
380+}
381+
382+pub fn rank_tag(rank: Option<Rank>, palette: Palette) -> Option<Div> {
383+ let (label, color) = match rank? {
384+ Rank::Owner => ("Owner", palette.muted),
385+ Rank::Admin => ("Admin", palette.muted),
386+ Rank::Moderator => ("Mod", palette.muted),
387+ Rank::Member => return None,
388+ Rank::Staff => ("Staff", palette.text),
389+ };
390+
391+ Some(
392+ div()
393+ .px(px(5.))
394+ .py(px(1.))
395+ .rounded(px(4.))
396+ .bg(palette.hover)
397+ .text_size(px(11.))
398+ .text_color(color)
399+ .child(label),
400+ )
401+}
402+
403+pub fn bind_keys(cx: &mut App) {
404+ cx.bind_keys([
405+ KeyBinding::new(FIND_KEY, FocusFind, None),
406+ KeyBinding::new("escape", CloseSettings, None),
407+ ]);
408+}
21 409
22 #[derive(Debug, Clone, Copy, PartialEq, Eq)]410 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
23 enum Route {411 enum Route {
@@ -33,15 +421,22 @@ pub struct Yumush {
33 chat: Chat,421 chat: Chat,
34 network: NetworkHandle,422 network: NetworkHandle,
35 connected: bool,423 connected: bool,
424+ settings: Settings,
425+ accounts: Accounts,
426+ voice: VoiceControls,
427+ focus: gpui_kit::FocusHandle,
36 }428 }
37 429
38 impl Yumush {430 impl Yumush {
39 pub fn new(431 pub fn new(
40 network: NetworkHandle,432 network: NetworkHandle,
41 mut network_event_receiver: mpsc::Receiver<NetworkEvent>,433 mut network_event_receiver: mpsc::Receiver<NetworkEvent>,
434+ settings: Settings,
42 window: &mut Window,435 window: &mut Window,
43 cx: &mut Context<Self>,436 cx: &mut Context<Self>,
44 ) -> Self {437 ) -> Self {
438+ network.set_voice_settings(settings.voice.clone());
439+
45 cx.spawn_in(window, async move |this, cx| {440 cx.spawn_in(window, async move |this, cx| {
46 while let Some(event) = network_event_receiver.recv().await {441 while let Some(event) = network_event_receiver.recv().await {
47 let updated = this.update_in(cx, |yumush, window, cx| {442 let updated = this.update_in(cx, |yumush, window, cx| {
@@ -55,20 +450,113 @@ impl Yumush {
55 })450 })
56 .detach();451 .detach();
57 452
453+ cx.observe_window_appearance(window, |yumush, window, cx| {
454+ if yumush.settings.theme == ThemeChoice::System {
455+ Theme::sync_system_appearance(Some(window), cx);
456+ sync_theme(cx);
457+ }
458+ cx.notify();
459+ })
460+ .detach();
461+
462+ cx.observe_window_activation(window, |yumush, window, _| {
463+ if !window.is_window_active() {
464+ yumush.network.set_talking(false);
465+ }
466+ })
467+ .detach();
468+
469+ let voice = VoiceControls::new(&settings.voice, window, cx);
470+
58 Self {471 Self {
59 user: None,472 user: None,
473+ focus: cx.focus_handle(),
60 current_route: Route::Login,474 current_route: Route::Login,
61 auth: Auth::new(window, cx),475 auth: Auth::new(window, cx),
62 chat: Chat::new(window, cx),476 chat: Chat::new(window, cx),
63 network,477 network,
64 connected: false,478 connected: false,
479+ settings,
480+ accounts: accounts::load(),
481+ voice,
65 }482 }
66 }483 }
67 484
68- fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {485+ pub(super) fn enter_session(
69- if self.user.take().is_none() {486+ &mut self,
487+ user: User,
488+ token: String,
489+ window: &mut Window,
490+ cx: &mut Context<Self>,
491+ ) {
492+ self.accounts.sign_in(&user, token);
493+ self.request_user_avatar(&user, cx);
494+ self.user = Some(user);
495+ self.change_page(Route::Chat, window, cx);
496+ self.load_communities(window, cx);
497+ self.load_social(window, cx);
498+ }
499+
500+ pub(super) fn switch_account(
501+ &mut self,
502+ user_id: String,
503+ window: &mut Window,
504+ cx: &mut Context<Self>,
505+ ) {
506+ let Some(account) = self.accounts.get(&user_id).cloned() else {
507+ return;
508+ };
509+ if !self.connected {
510+ window.push_notification(Notification::error("Not connected"), cx);
70 return;511 return;
71 }512 }
513+ if self.user.is_some() {
514+ self.end_session(window, cx);
515+ }
516+ let network = self.network.clone();
517+
518+ cx.spawn_in(window, async move |this, cx| {
519+ let result = network.resume(&account.token).await;
520+ let _ = this.update_in(cx, |yumush, window, cx| match result {
521+ Ok((user, token)) => yumush.enter_session(user, token, window, cx),
522+ Err(error @ (Error::NotFound | Error::Unauthenticated)) => {
523+ yumush.accounts.forget(&account.user_id);
524+ window.push_notification(Notification::error(error.to_string()), cx);
525+ cx.notify();
526+ }
527+ Err(error) => {
528+ window.push_notification(Notification::error(error.to_string()), cx);
529+ }
530+ });
531+ })
532+ .detach();
533+ }
534+
535+ pub(super) fn add_account(&mut self, window: &mut Window, cx: &mut Context<Self>) {
536+ self.accounts.detach();
537+ self.end_session(window, cx);
538+ let network = self.network.clone();
539+
540+ cx.spawn_in(window, async move |this, cx| {
541+ if let Err(error) = network.detach().await {
542+ notify_error(&this, cx, error);
543+ }
544+ })
545+ .detach();
546+ }
547+
548+ pub(super) fn forget_account(&mut self, user_id: &str, cx: &mut Context<Self>) {
549+ self.accounts.forget(user_id);
550+ cx.notify();
551+ }
552+
553+ fn logout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
554+ let Some(user) = self.user.take() else {
555+ return;
556+ };
557+ self.accounts.forget(&user.id);
558+ self.end_voice(cx);
559+ self.leave_settings();
72 let network = self.network.clone();560 let network = self.network.clone();
73 561
74 self.chat.reset();562 self.chat.reset();
@@ -92,6 +580,125 @@ impl Yumush {
92 }580 }
93 }581 }
94 582
583+ fn show_view(&mut self, view: View, window: &mut Window, cx: &mut Context<Self>) {
584+ if self.chat.view == View::Settings && view != View::Settings {
585+ self.leave_settings();
586+ }
587+ if view == View::Settings {
588+ self.enter_settings(window, cx);
589+ let (username, status) = self
590+ .user
591+ .as_ref()
592+ .map(|user| (user.username.clone(), user.status.clone()))
593+ .unwrap_or_default();
594+ self.chat
595+ .username_input
596+ .update(cx, |input, cx| input.set_value(username, window, cx));
597+ self.chat
598+ .status_input
599+ .update(cx, |input, cx| input.set_value(status, window, cx));
600+ }
601+ if view == View::CommunitySettings {
602+ let name = self
603+ .chat
604+ .selected_community()
605+ .map(|community| community.name.clone())
606+ .unwrap_or_default();
607+ self.chat
608+ .community_name_input
609+ .update(cx, |input, cx| input.set_value(name, window, cx));
610+ self.load_bans(window, cx);
611+ }
612+
613+ self.chat.view = view;
614+ self.chat.delete_step = chat::DeleteStep::Idle;
615+ if view == View::Chat {
616+ self.chat.focus(window, cx);
617+ }
618+ cx.notify();
619+ }
620+
621+ pub fn themed(&self, cx: &App) -> Palette {
622+ let community = match self.chat.view {
623+ View::Settings => None,
624+ _ => self.chat.selected_community(),
625+ };
626+ palette(cx).for_community(community, &self.chat.hues)
627+ }
628+
629+ pub fn actor_rank(&self) -> Option<Rank> {
630+ self.user.as_ref().and_then(|me| self.chat.my_rank(me))
631+ }
632+
633+ pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context<Self>) {
634+ if self.chat.avatars.contains_key(avatar_id)
635+ || self.chat.avatar_requests.contains(avatar_id)
636+ {
637+ return;
638+ }
639+ self.chat.avatar_requests.insert(avatar_id.to_string());
640+
641+ let network = self.network.clone();
642+ let avatar_id = avatar_id.to_string();
643+
644+ cx.spawn(async move |this, cx| {
645+ let result = network.read_avatar(&avatar_id).await;
646+ let _ = this.update(cx, |yumush, cx| {
647+ yumush.chat.avatar_requests.remove(&avatar_id);
648+ if let Ok(bytes) = result {
649+ if let Some(hue) = crate::avatar::dominant_hue(&bytes) {
650+ yumush.chat.hues.insert(avatar_id.clone(), hue);
651+ }
652+ yumush.chat.avatars.insert(
653+ avatar_id,
654+ Arc::new(Image::from_bytes(ImageFormat::Jpeg, bytes)),
655+ );
656+ }
657+ cx.notify();
658+ });
659+ })
660+ .detach();
661+ }
662+
663+ pub fn request_user_avatar(&mut self, user: &User, cx: &mut Context<Self>) {
664+ if let Some(avatar_id) = &user.avatar_id {
665+ self.request_avatar(avatar_id, cx);
666+ }
667+ }
668+
669+ fn apply_pushed(&mut self, event: Event, cx: &mut Context<Self>) {
670+ match &event {
671+ Event::MemberJoined { member, .. } => self.request_user_avatar(&member.user, cx),
672+ Event::UserUpdated(user) => {
673+ if self.is_me(&user.id) {
674+ self.user = Some(user.clone());
675+ self.accounts.rename(user);
676+ }
677+ self.request_user_avatar(user, cx);
678+ }
679+ Event::VoiceLeft {
680+ community_id,
681+ user_id,
682+ } if self.is_me(user_id) => self.chat.clear_voice_in(community_id),
683+ _ => {}
684+ }
685+ self.chat.apply_event(event);
686+ self.request_social_avatars(cx);
687+ self.request_media(cx);
688+ }
689+
690+ fn is_me(&self, user_id: &str) -> bool {
691+ self.user.as_ref().is_some_and(|me| me.id == user_id)
692+ }
693+
694+ fn end_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
695+ self.end_voice(cx);
696+ self.leave_settings();
697+ self.user = None;
698+ self.chat.reset();
699+ self.change_page(Route::Login, window, cx);
700+ }
701+
95 fn handle_network_event(702 fn handle_network_event(
96 &mut self,703 &mut self,
97 event: NetworkEvent,704 event: NetworkEvent,
@@ -103,21 +710,107 @@ impl Yumush {
103 self.connected = true;710 self.connected = true;
104 if self.user.is_some() {711 if self.user.is_some() {
105 self.reload(window, cx);712 self.reload(window, cx);
713+ } else if let Some(active) = self.accounts.active.clone() {
714+ self.switch_account(active, window, cx);
106 }715 }
107 }716 }
108 NetworkEvent::Disconnected(_) => self.connected = false,717 NetworkEvent::Disconnected(_) => self.connected = false,
109 NetworkEvent::SessionLost => {718 NetworkEvent::SessionLost => {
110- self.user = None;719+ if let Some(user) = &self.user {
111- self.chat.reset();720+ self.accounts.forget(&user.id.clone());
112- self.change_page(Route::Login, window, cx);721+ }
722+ self.end_session(window, cx);
113 }723 }
114- NetworkEvent::Pushed(event) => self.chat.apply_event(event),724+ NetworkEvent::Pushed(event) => match *event {
725+ Event::MemberLeft {
726+ community_id,
727+ user_id,
728+ } if self.is_me(&user_id) => {
729+ self.leave_voice_in(&community_id, cx);
730+ self.chat.remove_community(&community_id);
731+ }
732+ Event::Removed {
733+ community_id,
734+ community_name,
735+ banned,
736+ reason,
737+ } => {
738+ self.leave_voice_in(&community_id, cx);
739+ self.chat.remove_community(&community_id);
740+ let action = if banned { "Banned from" } else { "Kicked from" };
741+ let text = match reason {
742+ Some(reason) => format!("{action} {community_name}: {reason}"),
743+ None => format!("{action} {community_name}"),
744+ };
745+ window.push_notification(Notification::warning(text), cx);
746+ }
747+ Event::CommunityDeleted { community_id } => {
748+ self.leave_voice_in(&community_id, cx);
749+ self.apply_pushed(Event::CommunityDeleted { community_id }, cx);
750+ }
751+ event => self.apply_pushed(event, cx),
752+ },
115 }753 }
116 754
117 cx.notify();755 cx.notify();
118 }756 }
119 }757 }
120 758
759+pub fn input_dialog(
760+ title: &'static str,
761+ action: &'static str,
762+ placeholder: &'static str,
763+ window: &mut Window,
764+ cx: &mut Context<Yumush>,
765+ on_submit: impl Fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>) + 'static,
766+) {
767+ let input = new_input(placeholder, window, cx);
768+ let on_submit = std::rc::Rc::new(on_submit);
769+ let on_enter = on_submit.clone();
770+
771+ cx.subscribe_in(&input, window, move |this, input, event, window, cx| {
772+ if matches!(event, InputEvent::PressEnter { .. }) {
773+ let text = input.read(cx).text().to_string();
774+ on_enter(this, text, window, cx);
775+ }
776+ })
777+ .detach();
778+
779+ let entity = cx.entity();
780+ let dialog_input = input.clone();
781+ window.open_dialog(cx, move |dialog, _, cx| {
782+ let palette = entity.read(cx).themed(cx);
783+ let entity = entity.clone();
784+ let on_submit = on_submit.clone();
785+ let button_input = dialog_input.clone();
786+
787+ dialog.title(title).child(
788+ div()
789+ .flex()
790+ .flex_col()
791+ .gap(px(12.))
792+ .child(Input::new(&dialog_input))
793+ .child(
794+ div().flex().justify_end().child(
795+ primary_button("input_dialog_submit", palette, move |window, cx| {
796+ let text = button_input.read(cx).text().to_string();
797+ entity.update(cx, |this, cx| on_submit(this, text, window, cx));
798+ })
799+ .h(px(30.))
800+ .px(px(14.))
801+ .flex()
802+ .items_center()
803+ .rounded(px(8.))
804+ .child(action),
805+ ),
806+ ),
807+ )
808+ });
809+ window.defer(cx, move |window, cx| {
810+ input.update(cx, |input, cx| input.focus(window, cx));
811+ });
812+}
813+
121 pub fn notify_error<T: 'static>(814 pub fn notify_error<T: 'static>(
122 this: &WeakEntity<T>,815 this: &WeakEntity<T>,
123 cx: &mut AsyncWindowContext,816 cx: &mut AsyncWindowContext,
@@ -128,7 +821,7 @@ pub fn notify_error<T: 'static>(
128 });821 });
129 }822 }
130 823
131-fn new_input(824+pub(super) fn new_input(
132 placeholder: &'static str,825 placeholder: &'static str,
133 window: &mut Window,826 window: &mut Window,
134 cx: &mut Context<Yumush>,827 cx: &mut Context<Yumush>,
@@ -143,54 +836,39 @@ fn new_input(
143 836
144 impl Render for Yumush {837 impl Render for Yumush {
145 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {838 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
839+ let palette = palette(cx);
840+ sync_accent(self.themed(cx).accent, cx);
146 let route = self.current_route;841 let route = self.current_route;
147 let page = match route {842 let page = match route {
148 Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(),843 Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(),
149 Route::Chat => self.chat_page(cx).into_any_element(),844 Route::Chat => self.chat_page(cx).into_any_element(),
150 };845 };
151- let status_color = if self.connected {
152- rgb(0x22c55e)
153- } else {
154- rgb(0xef4444)
155- };
156 846
157 div()847 div()
158 .size_full()848 .size_full()
159- .relative()849+ .bg(palette.window)
160- .child(850+ .text_color(palette.text)
161- div()851+ .text_size(px(13.))
162- .flex()852+ .track_focus(&self.focus)
163- .flex_col()853+ .on_action(
164- .justify_center()854+ cx.listener(|this, _: &FocusFind, window, cx| this.chat.focus_find(window, cx)),
165- .items_center()
166- .size_full()
167- .bg(rgb(0x1e1e1e))
168- .text_color(cx.theme().foreground)
169- .child(page),
170- )
171- .child(
172- div()
173- .absolute()
174- .top_2()
175- .right_2()
176- .flex()
177- .flex_row()
178- .items_center()
179- .gap_2()
180- .children(
181- self.user.as_ref().map(|user| {
182- div().text_color(status_color).child(user.username.clone())
183- }),
184- )
185- .children(self.user.is_some().then(|| {
186- let entity = cx.entity();
187-
188- Button::new("logout_button").label("Logout").on_click(
189- move |_, window, cx| {
190- entity.update(cx, |yumush, cx| yumush.logout(window, cx));
191- },
192- )
193- })),
194 )855 )
856+ .on_action(cx.listener(|this, _: &CloseSettings, window, cx| {
857+ if this.chat.view != View::Chat {
858+ this.show_view(View::Chat, window, cx);
859+ } else {
860+ this.cancel_composer(window, cx);
861+ }
862+ }))
863+ .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
864+ this.voice_key_down(event, cx);
865+ }))
866+ .on_key_up(cx.listener(|this, event: &KeyUpEvent, _, cx| {
867+ this.voice_key_up(event, cx);
868+ }))
869+ .on_modifiers_changed(cx.listener(|this, event: &ModifiersChangedEvent, _, cx| {
870+ this.voice_modifiers(event, cx);
871+ }))
872+ .child(page)
195 }873 }
196 }874 }
crates/client/src/gui/auth.rsmodified+183 -30
@@ -1,13 +1,17 @@
1 use gpui_kit::{1 use gpui_kit::{
2- Context, Entity, IntoElement, ParentElement, Styled, Window,2+ Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
3- component::{3+ component::input::{Input, InputEvent, InputState},
4- button::Button,
5- input::{Input, InputEvent, InputState},
6- },
7 div,4 div,
5+ prelude::FluentBuilder as _,
6+ px,
8 };7 };
9 8
10-use crate::gui::{Route, Yumush, new_input, notify_error};9+use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon};
10+
11+use crate::gui::{
12+ Palette, Route, Yumush, badge, clickable, hoverable, new_input, notify_error, palette,
13+ primary_button,
14+};
11 15
12 pub struct Auth {16 pub struct Auth {
13 username_input: Entity<InputState>,17 username_input: Entity<InputState>,
@@ -55,15 +59,13 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) {
55 };59 };
56 60
57 match result {61 match result {
58- Ok(user) => {62+ Ok((user, token)) => {
59 let _ = this.update_in(cx, |yumush, window, cx| {63 let _ = this.update_in(cx, |yumush, window, cx| {
60 yumush64 yumush
61 .auth65 .auth
62 .password_input66 .password_input
63 .update(cx, |input, cx| input.set_value("", window, cx));67 .update(cx, |input, cx| input.set_value("", window, cx));
64- yumush.user = Some(user);68+ yumush.enter_session(user, token, window, cx);
65- yumush.change_page(Route::Chat, window, cx);
66- yumush.load_communities(window, cx);
67 });69 });
68 }70 }
69 Err(error) => notify_error(&this, cx, error),71 Err(error) => notify_error(&this, cx, error),
@@ -72,33 +74,184 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) {
72 .detach();74 .detach();
73 }75 }
74 76
77+pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div {
78+ div()
79+ .h(px(32.))
80+ .flex()
81+ .items_center()
82+ .rounded(px(8.))
83+ .border_1()
84+ .border_color(palette.border)
85+ .bg(palette.field)
86+ .child(
87+ Input::new(input)
88+ .appearance(false)
89+ .text_color(palette.text)
90+ .flex_1()
91+ .min_w_0(),
92+ )
93+}
94+
75 impl Yumush {95 impl Yumush {
76 pub(super) fn auth_page(&self, route: Route, cx: &mut Context<Self>) -> impl IntoElement {96 pub(super) fn auth_page(&self, route: Route, cx: &mut Context<Self>) -> impl IntoElement {
77- let (action_label, switch_route, switch_label) = match route {97+ let palette = palette(cx);
78- Route::Register => ("Register", Route::Login, "Go to Login Page"),98+ let action_label = match route {
79- _ => ("Login", Route::Register, "Go to Register Page"),99+ Route::Register => "Register",
100+ _ => "Log in",
80 };101 };
81 102
82 let entity = cx.entity();103 let entity = cx.entity();
83- let action_button =104+ let submit_entity = entity.clone();
84- Button::new("auth_button")105+ let action_button = primary_button("auth_button", palette, move |window, cx| {
85- .label(action_label)106+ submit_entity.update(cx, |this, cx| submit(this, window, cx));
86- .on_click(move |_, window, cx| {107+ })
87- entity.update(cx, |this, cx| submit(this, window, cx));108+ .h(px(32.))
88- });109+ .flex()
110+ .items_center()
111+ .justify_center()
112+ .rounded(px(8.))
113+ .font_weight(FontWeight::MEDIUM)
114+ .child(action_label);
89 115
90- let entity = cx.entity();116+ let tabs = div()
91- let switch_button = Button::new("auth_switch_button")117+ .flex()
92- .label(switch_label)118+ .p(px(3.))
93- .on_click(move |_, window, cx| {119+ .gap(px(3.))
94- entity.update(cx, |this, cx| this.change_page(switch_route, window, cx));120+ .rounded(px(8.))
95- });121+ .bg(palette.window)
122+ .child(tab(palette, &entity, Route::Login, "Log in", route))
123+ .child(tab(palette, &entity, Route::Register, "Register", route));
96 124
97 div()125 div()
98- .w_1_5()126+ .flex()
99- .child(Input::new(&self.auth.username_input))127+ .flex_col()
100- .child(Input::new(&self.auth.password_input))128+ .items_center()
101- .child(action_button)129+ .justify_center()
102- .child(switch_button)130+ .size_full()
131+ .child(
132+ div()
133+ .w(px(320.))
134+ .p(px(24.))
135+ .flex()
136+ .flex_col()
137+ .gap(px(12.))
138+ .rounded(px(10.))
139+ .border_1()
140+ .border_color(palette.border)
141+ .bg(palette.panel)
142+ .child(
143+ div()
144+ .text_size(px(18.))
145+ .font_weight(FontWeight::SEMIBOLD)
146+ .child("yumush"),
147+ )
148+ .children(self.saved_accounts(&entity, palette))
149+ .child(tabs)
150+ .child(field(palette, &self.auth.username_input))
151+ .child(field(palette, &self.auth.password_input))
152+ .child(action_button),
153+ )
103 }154 }
104 }155 }
156+
157+impl Yumush {
158+ fn saved_accounts(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
159+ if self.accounts.list.is_empty() {
160+ return None;
161+ }
162+ let rows: Vec<AnyElement> = self
163+ .accounts
164+ .list
165+ .iter()
166+ .map(|account| {
167+ let switch_entity = entity.clone();
168+ let forget_entity = entity.clone();
169+ let switch_id = account.user_id.clone();
170+ let forget_id = account.user_id.clone();
171+
172+ hoverable(
173+ format!("saved_{}", account.user_id),
174+ div()
175+ .h(px(36.))
176+ .px(px(8.))
177+ .flex()
178+ .items_center()
179+ .gap(px(8.))
180+ .rounded(px(6.))
181+ .child(
182+ badge(
183+ palette,
184+ &account.user_id,
185+ &account.username,
186+ px(22.),
187+ px(11.),
188+ )
189+ .rounded_full(),
190+ )
191+ .child(div().flex_1().truncate().child(account.username.clone()))
192+ .child(
193+ clickable(
194+ format!("forget_{}", account.user_id),
195+ palette,
196+ move |_, cx| {
197+ cx.stop_propagation();
198+ forget_entity.update(cx, |yumush, cx| {
199+ yumush.forget_account(&forget_id, cx)
200+ });
201+ },
202+ )
203+ .size(px(22.))
204+ .flex()
205+ .items_center()
206+ .justify_center()
207+ .rounded(px(5.))
208+ .text_color(palette.muted)
209+ .child(Icon::new(IconName::X).w(px(12.)).h(px(12.))),
210+ ),
211+ palette,
212+ )
213+ .on_click(move |_, window, cx| {
214+ switch_entity.update(cx, |yumush, cx| {
215+ yumush.switch_account(switch_id.clone(), window, cx)
216+ })
217+ })
218+ .into_any_element()
219+ })
220+ .collect();
221+
222+ Some(div().flex().flex_col().gap(px(2.)).children(rows))
223+ }
224+}
225+
226+fn tab(
227+ palette: Palette,
228+ entity: &Entity<Yumush>,
229+ target: Route,
230+ label: &'static str,
231+ route: Route,
232+) -> impl IntoElement {
233+ let entity = entity.clone();
234+ let active = route == target;
235+ clickable(label, palette, move |window, cx| {
236+ entity.update(cx, |this, cx| this.change_page(target, window, cx));
237+ })
238+ .flex_1()
239+ .flex()
240+ .justify_center()
241+ .py(px(4.))
242+ .rounded(px(6.))
243+ .text_size(px(12.))
244+ .when(active, |tab| {
245+ tab.bg(palette.panel)
246+ .border_1()
247+ .border_color(palette.border)
248+ .text_color(palette.text)
249+ .font_weight(FontWeight::MEDIUM)
250+ })
251+ .when(!active, |tab| {
252+ tab.border_1()
253+ .border_color(palette.window)
254+ .text_color(palette.muted)
255+ })
256+ .child(label)
257+}
crates/client/src/gui/chat.rsmodified+1244 -340
@@ -1,28 +1,67 @@
1+use std::{
2+ collections::{HashMap, HashSet},
3+ sync::Arc,
4+ time::Duration,
5+};
6+
7+use crate::gui::social::InviteLookup;
8+use crate::gui::{
9+ FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, clickable, community_icon,
10+ community_name,
11+ community_settings::{BanSort, LogSort},
12+ composer::{self, Composer},
13+ hoverable, id_time,
14+ media_view::{self, Media},
15+ message_actions, new_input, notify_error, palette, primary_button,
16+ profile::profile_popover,
17+ rank_tag,
18+ sidebar::SidebarTab,
19+ snippet,
20+};
1 use common::{21 use common::{
2 constant::MESSAGE_PAGE_LIMIT,22 constant::MESSAGE_PAGE_LIMIT,
3 event::Event,23 event::Event,
4- model::{Community, Message, User},24+ model::{
5- validate::{validate_community_name, validate_message_body},25+ Ban, Community, CommunityKind, Friends, Invitation, LogEntry, Member, Message, Rank, User,
26+ },
27+ permission,
6 };28 };
7 use gpui_kit::{29 use gpui_kit::{
8- Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement,30+ Anchor, AnyElement, App, Context, Entity, FontWeight, Image, InteractiveElement, IntoElement,
9- StatefulInteractiveElement, Styled, Window,31+ ParentElement, RenderOnce, ScrollHandle, StatefulInteractiveElement, Styled, Task, Window,
32+ assets::IconName,
33+ base::Selectable,
10 component::{34 component::{
11- WindowExt,35+ Icon, WindowExt,
12- button::Button,
13 input::{Input, InputEvent, InputState},36 input::{Input, InputEvent, InputState},
14- notification::Notification,37+ popover::Popover,
15 },38 },
16- div, rgb,39+ div,
40+ prelude::FluentBuilder as _,
41+ px, relative,
17 };42 };
18 43
19-use crate::gui::{Yumush, new_input, notify_error};44+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45+pub enum View {
46+ Chat,
47+ Settings,
48+ CommunitySettings,
49+}
20 50
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22-enum Panel {52+pub enum DeleteStep {
23- None,53+ Idle,
24- Create,54+ Confirm,
25- Join,55+}
56+
57+#[derive(Debug, Clone, PartialEq, Eq)]
58+pub enum VoiceState {
59+ Off,
60+ In {
61+ community_id: String,
62+ muted: bool,
63+ deafened: bool,
64+ },
26 }65 }
27 66
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -42,86 +81,171 @@ impl History {
42 }81 }
43 82
44 pub struct Chat {83 pub struct Chat {
45- communities: Vec<Community>,84+ pub(super) communities: Vec<Community>,
46- selected_community_id: Option<String>,85+ pub(super) selected_community_id: Option<String>,
47- members: Vec<User>,86+ members: Vec<Member>,
48- messages: Vec<Message>,87+ pub(super) messages: Vec<Message>,
49 history: History,88 history: History,
50- panel: Panel,89+ pub(super) unread: HashSet<String>,
51- message_input: Entity<InputState>,90+ pub(super) message_input: Entity<InputState>,
52- community_name_input: Entity<InputState>,91+ pub(super) search_input: Entity<InputState>,
53- community_search_input: Entity<InputState>,92+ pub(super) found: Option<User>,
54- search_results: Vec<Community>,93+ pub(super) invite: InviteLookup,
94+ pub(super) tab: SidebarTab,
95+ pub(super) composer: Composer,
96+ scroll: ScrollHandle,
97+ pub(super) view: View,
98+ pub(super) username_input: Entity<InputState>,
99+ pub(super) community_name_input: Entity<InputState>,
100+ pub(super) status_input: Entity<InputState>,
101+ pub(super) avatars: HashMap<String, Arc<Image>>,
102+ pub(super) hues: HashMap<String, f32>,
103+ pub(super) avatar_requests: HashSet<String>,
104+ pub(super) users: HashMap<String, User>,
105+ user_requests: HashSet<String>,
106+ pub(super) delete_step: DeleteStep,
107+ pub(super) bans: Vec<Ban>,
108+ pub(super) ban_search: Entity<InputState>,
109+ pub(super) ban_sort: BanSort,
110+ pub(super) logs: Vec<LogEntry>,
111+ pub(super) log_search: Entity<InputState>,
112+ pub(super) log_sort: LogSort,
113+ pub(super) friends: Friends,
114+ pub(super) invitations: Vec<Invitation>,
115+ pub(super) pending_user_delete: Option<String>,
116+ pub(super) voice: HashMap<String, Vec<String>>,
117+ pub(super) voice_state: VoiceState,
118+ pub(super) speaking: HashSet<String>,
119+ pub(super) voice_task: Option<Task<()>>,
120+ pub(super) media: Media,
55 }121 }
56 122
57 impl Chat {123 impl Chat {
58 pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {124 pub fn new(window: &mut Window, cx: &mut Context<Yumush>) -> Self {
59- let message_input = new_input("", window, cx);125+ let message_input = new_input("Message", window, cx);
60 cx.subscribe_in(&message_input, window, |this, input, event, window, cx| {126 cx.subscribe_in(&message_input, window, |this, input, event, window, cx| {
61 if matches!(event, InputEvent::PressEnter { .. }) {127 if matches!(event, InputEvent::PressEnter { .. }) {
62- send_message(this, input, window, cx);128+ this.submit_composer(input, window, cx);
63 }129 }
64 })130 })
65 .detach();131 .detach();
66 132
67- let community_name_input = new_input("Community Name...", window, cx);133+ let username_input = editable_input("Username...", Yumush::save_username, window, cx);
134+ let status_input = editable_input("Status...", Yumush::save_status, window, cx);
135+ let community_name_input =
136+ editable_input("Community name...", Yumush::save_community_name, window, cx);
137+
138+ let search_input = new_input("Find user", window, cx);
68 cx.subscribe_in(139 cx.subscribe_in(
69- &community_name_input,140+ &search_input,
70 window,141 window,
71- |this, input, event, window, cx| {142+ |this, _, event, window, cx| match event {
72- if matches!(event, InputEvent::PressEnter { .. }) {143+ InputEvent::Change => this.search_user(window, cx),
73- create_community(this, input, window, cx);144+ InputEvent::PressEnter { .. } => this.open_found(window, cx),
74- }145+ _ => {}
75 },146 },
76 )147 )
77 .detach();148 .detach();
78 149
79- let community_search_input = new_input("Community Name...", window, cx);150+ let ban_search = new_input("Search...", window, cx);
80- cx.subscribe_in(151+ let log_search = new_input("Search...", window, cx);
81- &community_search_input,152+ for search in [&ban_search, &log_search] {
82- window,153+ cx.subscribe_in(search, window, |_, _, event, window, cx| {
83- |this, input, event, window, cx| {154+ if matches!(event, InputEvent::Change) {
84- if matches!(event, InputEvent::PressEnter { .. }) {155+ window.refresh();
85- search_community(this, input, window, cx);156+ cx.notify();
86 }157 }
87- },158+ })
88- )159+ .detach();
89- .detach();160+ }
90 161
91 Self {162 Self {
92 communities: vec![],163 communities: vec![],
93 selected_community_id: None,164 selected_community_id: None,
94 members: vec![],165 members: vec![],
166+ bans: vec![],
167+ ban_search,
168+ ban_sort: BanSort::Newest,
169+ logs: vec![],
170+ log_search,
171+ log_sort: LogSort::Newest,
172+ friends: Friends::default(),
173+ invitations: vec![],
95 messages: vec![],174 messages: vec![],
96 history: History::End,175 history: History::End,
97- panel: Panel::None,176+ scroll: ScrollHandle::new(),
177+ unread: HashSet::new(),
98 message_input,178 message_input,
179+ search_input,
180+ found: None,
181+ invite: InviteLookup::Idle,
182+ tab: SidebarTab::Communities,
183+ view: View::Chat,
184+ username_input,
99 community_name_input,185 community_name_input,
100- community_search_input,186+ status_input,
101- search_results: vec![],187+ avatars: HashMap::new(),
188+ hues: HashMap::new(),
189+ avatar_requests: HashSet::new(),
190+ users: HashMap::new(),
191+ user_requests: HashSet::new(),
192+ delete_step: DeleteStep::Idle,
193+ pending_user_delete: None,
194+ voice: HashMap::new(),
195+ voice_state: VoiceState::Off,
196+ speaking: HashSet::new(),
197+ voice_task: None,
198+ media: Media::default(),
199+ composer: Composer::Compose { reply: None },
102 }200 }
103 }201 }
104 202
203+ pub(super) fn has_unread(&self, direct: bool) -> bool {
204+ self.communities.iter().any(|community| {
205+ self.unread.contains(&community.id)
206+ && matches!(community.kind, CommunityKind::Direct { .. }) == direct
207+ })
208+ }
209+
105 pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {210 pub fn focus(&self, window: &mut Window, cx: &mut Context<Yumush>) {
106- self.message_input211+ let input = match self.selected_community_id {
212+ Some(_) => &self.message_input,
213+ None => &self.search_input,
214+ };
215+ input.update(cx, |input, cx| input.focus(window, cx));
216+ }
217+
218+ pub fn focus_find(&mut self, window: &mut Window, cx: &mut Context<Yumush>) {
219+ self.tab = SidebarTab::Messages;
220+ self.search_input
107 .update(cx, |input, cx| input.focus(window, cx));221 .update(cx, |input, cx| input.focus(window, cx));
108 }222 }
109 223
110 pub fn apply_event(&mut self, event: Event) {224 pub fn apply_event(&mut self, event: Event) {
111 match event {225 match event {
112- Event::MessageCreated(message) | Event::MessageUpdated(message) => {226+ Event::MessageCreated(message) => {
227+ if self.is_selected(&message.community_id) {
228+ self.insert_messages([message]);
229+ } else {
230+ self.unread.insert(message.community_id);
231+ }
232+ }
233+ Event::MessageUpdated(message) => {
113 if self.is_selected(&message.community_id) {234 if self.is_selected(&message.community_id) {
114 self.insert_messages([message]);235 self.insert_messages([message]);
115 }236 }
116 }237 }
117 Event::MessageDeleted(message) => {238 Event::MessageDeleted(message) => {
118 if self.is_selected(&message.community_id) {239 if self.is_selected(&message.community_id) {
119- self.messages.retain(|existing| existing.id != message.id);240+ self.forget_message(&message.id);
120 }241 }
121 }242 }
122- Event::MemberJoined { community_id, user } => {243+ Event::MemberJoined {
244+ community_id,
245+ member,
246+ } => {
123 if self.is_selected(&community_id) {247 if self.is_selected(&community_id) {
124- self.insert_member(user);248+ self.insert_member(member);
125 }249 }
126 }250 }
127 Event::MemberLeft {251 Event::MemberLeft {
@@ -129,31 +253,110 @@ impl Chat {
129 user_id,253 user_id,
130 } => {254 } => {
131 if self.is_selected(&community_id) {255 if self.is_selected(&community_id) {
132- self.members.retain(|member| member.id != user_id);256+ self.remove_member(&user_id);
257+ }
258+ }
259+ Event::RankChanged {
260+ community_id,
261+ user_id,
262+ rank,
263+ } => {
264+ if self.is_selected(&community_id) {
265+ self.set_rank(&user_id, rank);
266+ }
267+ }
268+ Event::CommunityUpdated(community) | Event::CommunityAdded(community) => {
269+ self.insert_community(community)
270+ }
271+ Event::FriendsUpdated(friends) => self.friends = friends,
272+ Event::InvitationsUpdated(invitations) => self.invitations = invitations,
273+ Event::CommunityDeleted { community_id } | Event::Removed { community_id, .. } => {
274+ self.remove_community(&community_id)
275+ }
276+ Event::UserDeleted { user_id } => {
277+ self.remove_member(&user_id);
278+ self.messages.retain(|message| message.user_id != user_id);
279+ }
280+ Event::UserUpdated(user) => self.update_member(&user),
281+ Event::VoiceJoined {
282+ community_id,
283+ user_id,
284+ } => {
285+ let ids = self.voice.entry(community_id).or_default();
286+ if !ids.contains(&user_id) {
287+ ids.push(user_id);
288+ }
289+ }
290+ Event::VoiceLeft {
291+ community_id,
292+ user_id,
293+ } => {
294+ if let Some(ids) = self.voice.get_mut(&community_id) {
295+ ids.retain(|id| *id != user_id);
133 }296 }
134 }297 }
135- Event::CommunityUpdated(community) => self.insert_community(community),
136- Event::CommunityDeleted { community_id } => self.remove_community(&community_id),
137 }298 }
138 }299 }
139 300
140- fn is_selected(&self, community_id: &str) -> bool {301+ pub(super) fn is_selected(&self, community_id: &str) -> bool {
141 self.selected_community_id.as_deref() == Some(community_id)302 self.selected_community_id.as_deref() == Some(community_id)
142 }303 }
143 304
144 fn select(&mut self, community_id: Option<String>) {305 fn select(&mut self, community_id: Option<String>) {
306+ if let Some(community_id) = &community_id {
307+ self.unread.remove(community_id);
308+ }
309+ if self.view == View::CommunitySettings {
310+ self.view = View::Chat;
311+ self.delete_step = DeleteStep::Idle;
312+ }
145 self.selected_community_id = community_id;313 self.selected_community_id = community_id;
146 self.members.clear();314 self.members.clear();
315+ self.bans.clear();
316+ self.logs.clear();
317+ self.pending_user_delete = None;
147 self.messages.clear();318 self.messages.clear();
148 self.history = History::End;319 self.history = History::End;
320+ self.media.leave();
321+ self.composer = Composer::Compose { reply: None };
322+ }
323+
324+ fn joined(&self, community_id: &str) -> bool {
325+ self.communities
326+ .iter()
327+ .any(|community| community.id == community_id)
328+ }
329+
330+ fn forget_message(&mut self, message_id: &str) {
331+ self.messages.retain(|existing| existing.id != message_id);
332+
333+ let stale = match &self.composer {
334+ Composer::Compose { reply } => reply.as_deref() == Some(message_id),
335+ Composer::Edit { message_id: edited } => edited == message_id,
336+ Composer::Select { .. } => false,
337+ };
338+ if stale {
339+ self.composer = Composer::Compose { reply: None };
340+ }
341+ if let Composer::Select { ids } = &mut self.composer {
342+ ids.retain(|id| id != message_id);
343+ }
344+ }
345+
346+ pub fn communities(&self) -> &[Community] {
347+ &self.communities
149 }348 }
150 349
151 fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>) {350 fn insert_messages(&mut self, messages: impl IntoIterator<Item = Message>) {
351+ let newest = self.messages.last().map(|message| message.id.clone());
152 for message in messages {352 for message in messages {
153 self.messages.retain(|existing| existing.id != message.id);353 self.messages.retain(|existing| existing.id != message.id);
154 self.messages.push(message);354 self.messages.push(message);
155 }355 }
156 self.messages.sort_by(|left, right| left.id.cmp(&right.id));356 self.messages.sort_by(|left, right| left.id.cmp(&right.id));
357+ if self.messages.last().map(|message| &message.id) != newest.as_ref() {
358+ self.scroll.scroll_to_bottom();
359+ }
157 }360 }
158 361
159 fn add_page(&mut self, page: Vec<Message>) {362 fn add_page(&mut self, page: Vec<Message>) {
@@ -161,13 +364,130 @@ impl Chat {
161 self.insert_messages(page);364 self.insert_messages(page);
162 }365 }
163 366
164- fn insert_member(&mut self, user: User) {367+ fn insert_member(&mut self, member: Member) {
165- self.members.retain(|member| member.id != user.id);368+ self.remove_member(&member.user.id);
166- self.members.push(user);369+ self.members.push(member);
167- self.members.sort_by(|left, right| left.id.cmp(&right.id));370+ self.members
371+ .sort_by(|left, right| left.user.id.cmp(&right.user.id));
372+ }
373+
374+ pub(super) fn remove_member(&mut self, user_id: &str) {
375+ if let Some(index) = self
376+ .members
377+ .iter()
378+ .position(|member| member.user.id == user_id)
379+ {
380+ let member = self.members.remove(index);
381+ self.users.insert(member.user.id.clone(), member.user);
382+ }
383+ }
384+
385+ fn set_rank(&mut self, user_id: &str, rank: Rank) {
386+ if let Some(member) = self
387+ .members
388+ .iter_mut()
389+ .find(|member| member.user.id == user_id)
390+ {
391+ member.rank = rank;
392+ }
393+ }
394+
395+ pub fn selected_community(&self) -> Option<&Community> {
396+ self.communities
397+ .iter()
398+ .find(|community| self.is_selected(&community.id))
399+ }
400+
401+ pub fn member(&self, user_id: &str) -> Option<&User> {
402+ self.members
403+ .iter()
404+ .map(|member| &member.user)
405+ .find(|user| user.id == user_id)
406+ }
407+
408+ pub fn author(&self, user_id: &str) -> Option<&User> {
409+ self.member(user_id).or_else(|| self.users.get(user_id))
410+ }
411+
412+ fn missing_authors(&self) -> Vec<String> {
413+ if self.members.is_empty() {
414+ return vec![];
415+ }
416+ let mut missing: Vec<String> = self
417+ .messages
418+ .iter()
419+ .flat_map(|message| {
420+ std::iter::once(&message.user_id)
421+ .chain(message.reply.as_ref().map(|quote| &quote.user_id))
422+ })
423+ .filter(|id| self.author(id).is_none() && !self.user_requests.contains(*id))
424+ .cloned()
425+ .collect();
426+ missing.sort();
427+ missing.dedup();
428+ missing
429+ }
430+
431+ pub fn rank_of(&self, user: &User) -> Option<Rank> {
432+ let rank = self
433+ .members
434+ .iter()
435+ .find(|member| member.user.id == user.id)
436+ .map(|member| member.rank);
437+
438+ permission::effective_rank(user.role, rank)
439+ }
440+
441+ pub fn my_rank(&self, me: &User) -> Option<Rank> {
442+ self.rank_of(me)
168 }443 }
169 444
170- fn insert_community(&mut self, community: Community) {445+ pub fn rank_of_id(&self, user_id: &str) -> Option<Rank> {
446+ self.member(user_id).and_then(|user| self.rank_of(user))
447+ }
448+
449+ pub fn can_delete(&self, message: &Message, me: &User) -> bool {
450+ permission::can_delete_message(
451+ self.my_rank(me),
452+ self.rank_of_id(&message.user_id),
453+ message.user_id == me.id,
454+ )
455+ }
456+
457+ pub fn update_member(&mut self, user: &User) {
458+ if let Some(member) = self
459+ .members
460+ .iter_mut()
461+ .find(|member| member.user.id == user.id)
462+ {
463+ member.user = user.clone();
464+ }
465+
466+ let peers = self
467+ .communities
468+ .iter_mut()
469+ .filter_map(|community| match &mut community.kind {
470+ CommunityKind::Direct { peer } => Some(peer),
471+ CommunityKind::Group => None,
472+ });
473+ let known = self
474+ .friends
475+ .friends
476+ .iter_mut()
477+ .chain(self.friends.incoming.iter_mut())
478+ .chain(self.friends.outgoing.iter_mut())
479+ .chain(
480+ self.invitations
481+ .iter_mut()
482+ .map(|invitation| &mut invitation.inviter),
483+ )
484+ .chain(peers);
485+ for existing in known.filter(|existing| existing.id == user.id) {
486+ *existing = user.clone();
487+ }
488+ }
489+
490+ pub(super) fn insert_community(&mut self, community: Community) {
171 self.communities491 self.communities
172 .retain(|existing| existing.id != community.id);492 .retain(|existing| existing.id != community.id);
173 self.communities.push(community);493 self.communities.push(community);
@@ -175,9 +495,14 @@ impl Chat {
175 .sort_by(|left, right| left.id.cmp(&right.id));495 .sort_by(|left, right| left.id.cmp(&right.id));
176 }496 }
177 497
178- fn remove_community(&mut self, community_id: &str) {498+ pub(super) fn remove_community(&mut self, community_id: &str) {
179 self.communities499 self.communities
180 .retain(|community| community.id != community_id);500 .retain(|community| community.id != community_id);
501+ self.unread.remove(community_id);
502+ self.voice.remove(community_id);
503+ if self.in_voice(community_id) {
504+ self.set_voice_off();
505+ }
181 if self.is_selected(community_id) {506 if self.is_selected(community_id) {
182 self.select(None);507 self.select(None);
183 }508 }
@@ -193,66 +518,92 @@ impl Chat {
193 if !selected_present {518 if !selected_present {
194 self.select(None);519 self.select(None);
195 }520 }
196- }
197 521
198- fn set_panel(&mut self, panel: Panel) {522+ if self.voice_community().is_some_and(|id| !self.joined(id)) {
199- if panel != Panel::Join {523+ self.set_voice_off();
200- self.search_results.clear();
201 }524 }
202- self.panel = panel;
203 }525 }
204 526
205 pub fn reset(&mut self) {527 pub fn reset(&mut self) {
206 self.communities.clear();528 self.communities.clear();
529+ self.friends = Friends::default();
530+ self.invitations.clear();
531+ self.found = None;
207 self.select(None);532 self.select(None);
208- self.set_panel(Panel::None);533+ self.unread.clear();
534+ self.view = View::Chat;
535+ self.delete_step = DeleteStep::Idle;
536+ self.voice.clear();
537+ self.set_voice_off();
209 }538 }
210-}
211 539
212-fn send_message(540+ pub fn voice_community(&self) -> Option<&str> {
213- this: &mut Yumush,541+ match &self.voice_state {
214- input: &Entity<InputState>,542+ VoiceState::Off => None,
215- window: &mut Window,543+ VoiceState::In { community_id, .. } => Some(community_id),
216- cx: &mut Context<Yumush>,544+ }
217-) {545+ }
218- let body = input.read(cx).text().to_string();
219 546
220- if let Err(error) = validate_message_body(&body) {547+ pub fn in_voice(&self, community_id: &str) -> bool {
221- window.push_notification(Notification::error(error.to_string()), cx);548+ self.voice_community() == Some(community_id)
222- return;
223 }549 }
224 550
225- let Some(community_id) = this.chat.selected_community_id.clone() else {551+ pub fn voice_flags(&self) -> Option<(bool, bool)> {
226- window.push_notification(Notification::error("No Community Selected"), cx);552+ match &self.voice_state {
227- return;553+ VoiceState::Off => None,
228- };554+ VoiceState::In {
229- let network = this.network.clone();555+ muted, deafened, ..
556+ } => Some((*muted, *deafened)),
557+ }
558+ }
230 559
231- cx.spawn_in(window, async move |this, cx| {560+ pub fn voice_ids(&self, community_id: &str) -> &[String] {
232- if let Err(error) = network.create_message(&community_id, &body).await {561+ self.voice
233- notify_error(&this, cx, error);562+ .get(community_id)
563+ .map(Vec::as_slice)
564+ .unwrap_or_default()
565+ }
566+
567+ pub fn set_voice_off(&mut self) {
568+ self.voice_state = VoiceState::Off;
569+ self.speaking.clear();
570+ self.voice_task = None;
571+ }
572+
573+ pub fn clear_voice_in(&mut self, community_id: &str) {
574+ if self.in_voice(community_id) {
575+ self.set_voice_off();
234 }576 }
235- })577+ }
236- .detach();578+}
237 579
238- input.update(cx, |state, cx| state.set_value("", window, cx));580+fn empty_state(palette: Palette) -> impl IntoElement {
581+ div()
582+ .flex_1()
583+ .flex()
584+ .items_center()
585+ .justify_center()
586+ .gap(px(8.))
587+ .text_color(palette.muted)
588+ .child(
589+ div()
590+ .px(px(5.))
591+ .rounded(px(4.))
592+ .border_1()
593+ .border_color(palette.border)
594+ .text_size(px(11.))
595+ .child(FIND_HINT),
596+ )
597+ .child("Find a user")
239 }598 }
240 599
241-fn create_community(600+pub(super) fn create_community(
242 this: &mut Yumush,601 this: &mut Yumush,
243- input: &Entity<InputState>,602+ name: String,
244 window: &mut Window,603 window: &mut Window,
245 cx: &mut Context<Yumush>,604 cx: &mut Context<Yumush>,
246 ) {605 ) {
247- let name = input.read(cx).text().to_string();
248-
249- if let Err(error) = validate_community_name(&name) {
250- window.push_notification(Notification::error(error.to_string()), cx);
251- return;
252- }
253-
254 let network = this.network.clone();606 let network = this.network.clone();
255- input.update(cx, |state, cx| state.set_value("", window, cx));
256 607
257 cx.spawn_in(window, async move |this, cx| {608 cx.spawn_in(window, async move |this, cx| {
258 let community = match network.create_community(&name).await {609 let community = match network.create_community(&name).await {
@@ -264,281 +615,273 @@ fn create_community(
264 };615 };
265 616
266 let _ = this.update_in(cx, |yumush, window, cx| {617 let _ = this.update_in(cx, |yumush, window, cx| {
618+ window.close_dialog(cx);
267 yumush.enter_community(community, window, cx);619 yumush.enter_community(community, window, cx);
268 });620 });
269 })621 })
270 .detach();622 .detach();
271 }623 }
272 624
273-fn search_community(625+#[derive(IntoElement)]
274- this: &mut Yumush,626+struct MembersTrigger {
275- input: &Entity<InputState>,627+ palette: Palette,
276- window: &mut Window,628+ members: Vec<User>,
277- cx: &mut Context<Yumush>,629+ avatars: HashMap<String, Arc<Image>>,
278-) {630+}
279- let name = input.read(cx).text().to_string();
280 631
281- if let Err(error) = validate_community_name(&name) {632+impl Selectable for MembersTrigger {
282- window.push_notification(Notification::error(error.to_string()), cx);633+ fn selected(self, _: bool) -> Self {
283- return;634+ self
284 }635 }
285 636
286- let network = this.network.clone();637+ fn is_selected(&self) -> bool {
638+ false
639+ }
640+}
287 641
288- cx.spawn_in(window, async move |this, cx| {642+impl RenderOnce for MembersTrigger {
289- let communities = match network.search_community(&name).await {643+ fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
290- Ok(communities) => communities,644+ let palette = self.palette;
291- Err(error) => {645+ let avatars = self
292- notify_error(&this, cx, error);646+ .members
293- return;647+ .iter()
294- }648+ .take(3)
295- };649+ .enumerate()
650+ .map(|(index, user)| {
651+ avatar(palette, user, px(18.), px(9.), &self.avatars)
652+ .border_2()
653+ .border_color(palette.panel)
654+ .when(index > 0, |this| this.ml(px(-6.)))
655+ });
296 656
297- let _ = this.update(cx, |yumush, cx| {657+ hoverable(
298- yumush.chat.search_results = communities;658+ "members_trigger",
299- cx.notify();659+ div()
300- });660+ .h(px(28.))
301- })661+ .px(px(8.))
302- .detach();662+ .flex()
663+ .items_center()
664+ .gap(px(6.))
665+ .rounded(px(6.))
666+ .text_size(px(12.))
667+ .text_color(palette.muted)
668+ .child(div().flex().children(avatars))
669+ .child(self.members.len().to_string()),
670+ palette,
671+ )
672+ }
303 }673 }
304 674
305 impl Yumush {675 impl Yumush {
306 pub(super) fn chat_page(&self, cx: &mut Context<Self>) -> impl IntoElement {676 pub(super) fn chat_page(&self, cx: &mut Context<Self>) -> impl IntoElement {
677+ let palette = palette(cx);
307 let entity = cx.entity();678 let entity = cx.entity();
308 679
309 div()680 div()
310 .flex()681 .flex()
311 .flex_row()682 .flex_row()
312 .size_full()683 .size_full()
313- .child(self.community_list(&entity))684+ .child(self.sidebar(&entity, &self.search_query(cx), palette))
314- .child(685+ .child(self.main_panel(&entity, palette, cx))
315- div()
316- .flex()
317- .flex_col()
318- .flex_1()
319- .min_w_0()
320- .child(self.message_list(&entity))
321- .child(
322- div()
323- .p_2()
324- .border_t_1()
325- .border_color(rgb(0x2f3136))
326- .child(Input::new(&self.chat.message_input)),
327- ),
328- )
329- .child(self.member_list(&entity))
330 }686 }
331 687
332- fn community_list(&self, entity: &Entity<Self>) -> impl IntoElement {688+ fn main_panel(&self, entity: &Entity<Self>, palette: Palette, cx: &App) -> impl IntoElement {
689+ let themed = self.themed(cx);
690+
333 div()691 div()
334- .id("community_list")692+ .flex_1()
335- .h_full()693+ .min_w_0()
694+ .mt(px(8.))
695+ .mr(px(8.))
696+ .mb(px(8.))
336 .flex()697 .flex()
337 .flex_col()698 .flex_col()
338- .flex_shrink_0()699+ .rounded(px(10.))
339- .w_1_5()700+ .border_1()
340- .border_r_1()701+ .border_color(palette.border)
341- .border_color(rgb(0x2f3136))702+ .bg(palette.panel)
342- .bg(rgb(0x2b2d31))703+ .map(|panel| match self.chat.view {
343- .p_2()704+ View::Settings => panel.child(self.settings_page(entity, palette, cx)),
344- .gap_1()705+ View::CommunitySettings => {
706+ panel.child(self.community_settings_page(entity, palette, cx))
707+ }
708+ View::Chat => match self.chat.selected_community_id {
709+ Some(_) => panel
710+ .child(self.header(entity, themed))
711+ .child(self.message_list(entity, themed))
712+ .child(self.composer(entity, themed)),
713+ None => panel.child(empty_state(palette)),
714+ },
715+ })
716+ }
717+
718+ fn header(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
719+ let community = self.chat.selected_community();
720+ let name = community.map(community_name).unwrap_or_default();
721+ let group =
722+ community.is_some_and(|community| matches!(community.kind, CommunityKind::Group));
723+
724+ div()
725+ .h(px(44.))
726+ .pl(px(20.))
727+ .pr(px(12.))
728+ .flex()
729+ .items_center()
730+ .gap(px(8.))
731+ .border_b_2()
732+ .border_color(palette.accent)
733+ .children(community.map(|community| {
734+ community_icon(palette, community, px(20.), px(10.), &self.chat.avatars)
735+ }))
345 .child(736 .child(
346 div()737 div()
347- .flex()738+ .font_weight(FontWeight::SEMIBOLD)
348- .flex_row()739+ .child(name.to_string()),
349- .items_center()
350- .justify_between()
351- .child(
352- div()
353- .text_color(rgb(0x949ba4))
354- .font_weight(FontWeight::SEMIBOLD)
355- .child("Communities"),
356- )
357- .child(panel_button(
358- entity,
359- "create_community_button",
360- "+",
361- Panel::Create,
362- ))
363- .child(panel_button(
364- entity,
365- "join_community_button",
366- "Join",
367- Panel::Join,
368- )),
369- )
370- .children(
371- (self.chat.panel == Panel::Create)
372- .then(|| Input::new(&self.chat.community_name_input)),
373- )
374- .children(
375- (self.chat.panel == Panel::Join)
376- .then(|| Input::new(&self.chat.community_search_input)),
377- )
378- .children(
379- self.chat
380- .search_results
381- .iter()
382- .filter(|result| {
383- !self
384- .chat
385- .communities
386- .iter()
387- .any(|community| community.id == result.id)
388- })
389- .enumerate()
390- .map(|(index, result)| {
391- let community_id = result.id.clone();
392- let entity = entity.clone();
393-
394- div()
395- .id(("community_search_result", index))
396- .p_1()
397- .cursor_pointer()
398- .bg(rgb(0x1e1f22))
399- .text_color(rgb(0x949ba4))
400- .child(result.name.clone())
401- .on_click(move |_, window, cx| {
402- entity.update(cx, |yumush, cx| {
403- yumush.join_community(&community_id, window, cx)
404- })
405- })
406- }),
407 )740 )
741+ .child(div().flex_1())
408 .children(742 .children(
409- self.chat743+ community
410- .communities744+ .is_some()
411- .iter()745+ .then(|| self.voice_stack(entity, palette))
412- .enumerate()746+ .flatten(),
413- .map(|(index, community)| {
414- let community_id = community.id.clone();
415- let selected = self.chat.is_selected(&community.id);
416- let entity = entity.clone();
417-
418- div()
419- .id(("community", index))
420- .p_1()
421- .cursor_pointer()
422- .bg(if selected {
423- rgb(0x404249)
424- } else {
425- rgb(0x2b2d31)
426- })
427- .child(community.name.clone())
428- .on_click(move |_, window, cx| {
429- entity.update(cx, |yumush, cx| {
430- yumush.select_community(community_id.clone(), window, cx)
431- })
432- })
433- }),
434 )747 )
748+ .children(self.voice_button(entity, palette))
749+ .children(group.then(|| members_popover(entity, &self.chat, palette)))
435 }750 }
436 751
437- fn message_list(&self, entity: &Entity<Self>) -> impl IntoElement {752+ fn message_list(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
438 div()753 div()
439 .id("chat_messages")754 .id("chat_messages")
755+ .track_scroll(&self.chat.scroll)
440 .flex()756 .flex()
441 .flex_col()757 .flex_col()
442 .flex_1()758 .flex_1()
443 .min_w_0()759 .min_w_0()
444 .overflow_y_scroll()760 .overflow_y_scroll()
445- .p_2()761+ .px(px(24.))
446- .gap_1()762+ .py(px(20.))
447- .children((self.chat.history == History::More).then(|| older_button(entity)))763+ .gap(px(2.))
764+ .child(div().flex_1())
765+ .children((self.chat.history == History::More).then(|| older_button(entity, palette)))
448 .children(766 .children(
449 self.chat767 self.chat
450 .messages768 .messages
451 .iter()769 .iter()
452- .map(|message| render_message(message, &self.chat.members)),770+ .enumerate()
771+ .map(|(index, message)| {
772+ let first =
773+ index == 0 || self.chat.messages[index - 1].user_id != message.user_id;
774+ render_message(
775+ message,
776+ first,
777+ index > 0,
778+ &self.chat,
779+ self.user.as_ref(),
780+ entity,
781+ palette,
782+ )
783+ }),
453 )784 )
454 }785 }
455 786
456- fn member_list(&self, entity: &Entity<Self>) -> impl IntoElement {787+ fn composer(&self, entity: &Entity<Self>, palette: Palette) -> gpui_kit::AnyElement {
788+ if let Composer::Select { ids } = &self.chat.composer {
789+ return div()
790+ .p(px(16.))
791+ .child(composer::selection_bar(ids, entity, palette))
792+ .into_any_element();
793+ }
794+
795+ let input = self.chat.message_input.clone();
796+ let attach = entity.clone();
797+ let pending = media_view::pending_row(&self.chat.media, entity, palette);
798+ let bar = composer::mode_bar(&self.chat, entity, palette);
799+ let entity = entity.clone();
800+
457 div()801 div()
458- .id("member_list")802+ .p(px(16.))
459- .h_full()803+ .children(pending)
460- .flex()804+ .children(bar)
461- .flex_col()
462- .flex_shrink_0()
463- .w_1_5()
464- .border_l_1()
465- .border_color(rgb(0x2f3136))
466- .bg(rgb(0x2b2d31))
467- .p_2()
468- .gap_1()
469 .child(805 .child(
470 div()806 div()
807+ .min_h(px(40.))
808+ .pl(px(4.))
809+ .pr(px(4.))
810+ .py(px(4.))
471 .flex()811 .flex()
472- .flex_row()
473 .items_center()812 .items_center()
474- .justify_between()813+ .gap(px(8.))
814+ .rounded(px(8.))
815+ .border_1()
816+ .border_color(palette.border)
817+ .bg(palette.field)
475 .child(818 .child(
476- div()819+ clickable("attach_button", palette, move |window, cx| {
477- .text_color(rgb(0x949ba4))820+ attach.update(cx, |yumush, cx| yumush.attach_files(window, cx))
478- .font_weight(FontWeight::SEMIBOLD)821+ })
479- .child(format!("Members - {}", self.chat.members.len())),822+ .tip("Attach")
823+ .size(px(28.))
824+ .flex()
825+ .items_center()
826+ .justify_center()
827+ .rounded(px(6.))
828+ .text_color(palette.muted)
829+ .child(Icon::new(IconName::Plus).w(px(16.)).h(px(16.))),
480 )830 )
481- .children(831+ .child(
482- self.chat832+ Input::new(&self.chat.message_input)
483- .selected_community_id833+ .appearance(false)
484- .is_some()834+ .text_color(palette.text)
485- .then(|| leave_button(entity)),835+ .flex_1()
836+ .min_w_0(),
837+ )
838+ .child(
839+ primary_button("send_button", palette, move |window, cx| {
840+ entity
841+ .update(cx, |yumush, cx| yumush.submit_composer(&input, window, cx))
842+ })
843+ .tip("Send")
844+ .size(px(28.))
845+ .flex()
846+ .items_center()
847+ .justify_center()
848+ .rounded(px(6.))
849+ .child(Icon::new(IconName::ArrowUp).w(px(14.)).h(px(14.))),
486 ),850 ),
487 )851 )
488- .children(852+ .into_any_element()
489- self.chat
490- .members
491- .iter()
492- .map(|user| div().p_1().child(user.username.clone())),
493- )
494- }
495-
496- fn toggle_panel(&mut self, panel: Panel, window: &mut Window, cx: &mut Context<Self>) {
497- let panel = if self.chat.panel == panel {
498- Panel::None
499- } else {
500- panel
501- };
502- self.chat.set_panel(panel);
503-
504- let input = match panel {
505- Panel::None => None,
506- Panel::Create => Some(&self.chat.community_name_input),
507- Panel::Join => Some(&self.chat.community_search_input),
508- };
509- if let Some(input) = input {
510- input.update(cx, |state, cx| state.focus(window, cx));
511- }
512-
513- cx.notify();
514 }853 }
515 854
516- fn select_community(855+ pub(super) fn select_community(
517 &mut self,856 &mut self,
518 community_id: String,857 community_id: String,
519 window: &mut Window,858 window: &mut Window,
520 cx: &mut Context<Self>,859 cx: &mut Context<Self>,
521 ) {860 ) {
861+ self.stop_playing(cx);
522 self.chat.select(Some(community_id));862 self.chat.select(Some(community_id));
863+ self.chat.focus(window, cx);
523 self.load_members(window, cx);864 self.load_members(window, cx);
865+ self.load_voice(window, cx);
524 self.load_latest_messages(window, cx);866 self.load_latest_messages(window, cx);
525 cx.notify();867 cx.notify();
526 }868 }
527 869
528- fn enter_community(870+ pub(super) fn enter_community(
529 &mut self,871 &mut self,
530 community: Community,872 community: Community,
531 window: &mut Window,873 window: &mut Window,
532 cx: &mut Context<Self>,874 cx: &mut Context<Self>,
533 ) {875 ) {
534- self.chat.set_panel(Panel::None);
535 let community_id = community.id.clone();876 let community_id = community.id.clone();
536 self.chat.insert_community(community);877 self.chat.insert_community(community);
878+ self.request_social_avatars(cx);
537 self.select_community(community_id, window, cx);879 self.select_community(community_id, window, cx);
538 }880 }
539 881
540 pub(super) fn reload(&self, window: &mut Window, cx: &mut Context<Self>) {882 pub(super) fn reload(&self, window: &mut Window, cx: &mut Context<Self>) {
541 self.load_communities(window, cx);883 self.load_communities(window, cx);
884+ self.load_social(window, cx);
542 885
543 if self.chat.selected_community_id.is_some() {886 if self.chat.selected_community_id.is_some() {
544 self.load_members(window, cx);887 self.load_members(window, cx);
@@ -560,6 +903,7 @@ impl Yumush {
560 903
561 let _ = this.update_in(cx, |yumush, window, cx| {904 let _ = this.update_in(cx, |yumush, window, cx| {
562 yumush.chat.replace_communities(communities);905 yumush.chat.replace_communities(communities);
906+ yumush.request_social_avatars(cx);
563 907
564 if yumush.chat.selected_community_id.is_none() {908 if yumush.chat.selected_community_id.is_none() {
565 let first = yumush909 let first = yumush
@@ -592,9 +936,68 @@ impl Yumush {
592 }936 }
593 };937 };
594 938
595- let _ = this.update(cx, |yumush, cx| {939+ let _ = this.update_in(cx, |yumush, window, cx| {
596 if yumush.chat.is_selected(&community_id) {940 if yumush.chat.is_selected(&community_id) {
941+ for member in &members {
942+ yumush.request_user_avatar(&member.user, cx);
943+ }
597 yumush.chat.members = members;944 yumush.chat.members = members;
945+ yumush.load_bans(window, cx);
946+ yumush.request_authors(window, cx);
947+ cx.notify();
948+ }
949+ });
950+ })
951+ .detach();
952+ }
953+
954+ fn request_authors(&mut self, window: &mut Window, cx: &mut Context<Self>) {
955+ let missing = self.chat.missing_authors();
956+ if missing.is_empty() {
957+ return;
958+ }
959+ self.chat.user_requests.extend(missing.iter().cloned());
960+ let network = self.network.clone();
961+
962+ cx.spawn_in(window, async move |this, cx| {
963+ for user_id in missing {
964+ let Ok(user) = network.read_user(&user_id).await else {
965+ continue;
966+ };
967+ let _ = this.update(cx, |yumush, cx| {
968+ yumush.request_user_avatar(&user, cx);
969+ yumush.chat.users.insert(user.id.clone(), user);
970+ cx.notify();
971+ });
972+ }
973+ })
974+ .detach();
975+ }
976+
977+ pub(super) fn load_bans(&self, window: &mut Window, cx: &mut Context<Self>) {
978+ if !permission::can_unban(self.actor_rank()) {
979+ return;
980+ }
981+ let Some(community_id) = self.chat.selected_community_id.clone() else {
982+ return;
983+ };
984+ let network = self.network.clone();
985+
986+ cx.spawn_in(window, async move |this, cx| {
987+ let bans = match network.bans(&community_id).await {
988+ Ok(bans) => bans,
989+ Err(error) => {
990+ notify_error(&this, cx, error);
991+ return;
992+ }
993+ };
994+
995+ let _ = this.update(cx, |yumush, cx| {
996+ if yumush.chat.is_selected(&community_id) {
997+ for ban in &bans {
998+ yumush.request_user_avatar(&ban.user, cx);
999+ }
1000+ yumush.chat.bans = bans;
598 cx.notify();1001 cx.notify();
599 }1002 }
600 });1003 });
@@ -631,9 +1034,11 @@ impl Yumush {
631 }1034 }
632 };1035 };
633 1036
634- let _ = this.update(cx, |yumush, cx| {1037+ let _ = this.update_in(cx, |yumush, window, cx| {
635 if yumush.chat.is_selected(&community_id) {1038 if yumush.chat.is_selected(&community_id) {
636 yumush.chat.add_page(page);1039 yumush.chat.add_page(page);
1040+ yumush.request_media(cx);
1041+ yumush.request_authors(window, cx);
637 cx.notify();1042 cx.notify();
638 }1043 }
639 });1044 });
@@ -641,27 +1046,29 @@ impl Yumush {
641 .detach();1046 .detach();
642 }1047 }
643 1048
644- fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context<Self>) {1049+ pub(super) fn delete_message(
1050+ &self,
1051+ message_id: &str,
1052+ window: &mut Window,
1053+ cx: &mut Context<Self>,
1054+ ) {
645 let network = self.network.clone();1055 let network = self.network.clone();
646- let community_id = community_id.to_string();1056+ let message_id = message_id.to_string();
647 1057
648 cx.spawn_in(window, async move |this, cx| {1058 cx.spawn_in(window, async move |this, cx| {
649- match network.join_community(&community_id).await {1059+ if let Err(error) = network.delete_message(&message_id).await {
650- Ok(community) => {1060+ notify_error(&this, cx, error);
651- let _ = this.update_in(cx, |yumush, window, cx| {
652- yumush.enter_community(community, window, cx);
653- });
654- }
655- Err(error) => notify_error(&this, cx, error),
656 }1061 }
657 })1062 })
658 .detach();1063 .detach();
659 }1064 }
660 1065
661- fn leave_community(&self, window: &mut Window, cx: &mut Context<Self>) {1066+ pub(super) fn leave_community(
662- let Some(community_id) = self.chat.selected_community_id.clone() else {1067+ &self,
663- return;1068+ community_id: String,
664- };1069+ window: &mut Window,
1070+ cx: &mut Context<Self>,
1071+ ) {
665 let network = self.network.clone();1072 let network = self.network.clone();
666 1073
667 cx.spawn_in(window, async move |this, cx| {1074 cx.spawn_in(window, async move |this, cx| {
@@ -671,63 +1078,560 @@ impl Yumush {
671 }1078 }
672 1079
673 let _ = this.update(cx, |yumush, cx| {1080 let _ = this.update(cx, |yumush, cx| {
1081+ yumush.leave_voice_in(&community_id, cx);
674 yumush.chat.remove_community(&community_id);1082 yumush.chat.remove_community(&community_id);
675 cx.notify();1083 cx.notify();
676 });1084 });
677 })1085 })
678 .detach();1086 .detach();
679 }1087 }
680-}
681 1088
682-fn panel_button(1089+ fn load_voice(&self, window: &mut Window, cx: &mut Context<Self>) {
683- entity: &Entity<Yumush>,1090+ let Some(community_id) = self.chat.selected_community_id.clone() else {
684- id: &'static str,1091+ return;
685- label: &'static str,1092+ };
686- panel: Panel,1093+ let network = self.network.clone();
687-) -> impl IntoElement {
688- let entity = entity.clone();
689 1094
690- Button::new(id).label(label).on_click(move |_, window, cx| {1095+ cx.spawn_in(window, async move |this, cx| {
691- entity.update(cx, |yumush, cx| yumush.toggle_panel(panel, window, cx));1096+ let participants = match network.voice_participants(&community_id).await {
692- })1097+ Ok(participants) => participants,
1098+ Err(error) => {
1099+ notify_error(&this, cx, error);
1100+ return;
1101+ }
1102+ };
1103+
1104+ let _ = this.update(cx, |yumush, cx| {
1105+ yumush.chat.voice.insert(community_id, participants);
1106+ cx.notify();
1107+ });
1108+ })
1109+ .detach();
1110+ }
1111+
1112+ fn toggle_voice(&mut self, community_id: String, window: &mut Window, cx: &mut Context<Self>) {
1113+ if self.chat.in_voice(&community_id) {
1114+ self.end_voice(cx);
1115+ return;
1116+ }
1117+
1118+ let (muted, deafened) = self.chat.voice_flags().unwrap_or((false, false));
1119+ let was_in = self.chat.voice_community().is_some();
1120+ if was_in {
1121+ self.chat.set_voice_off();
1122+ }
1123+ let network = self.network.clone();
1124+
1125+ cx.spawn_in(window, async move |this, cx| {
1126+ if was_in {
1127+ let _ = network.leave_voice().await;
1128+ }
1129+
1130+ match network.join_voice(&community_id).await {
1131+ Ok(participants) => {
1132+ network.set_muted(muted);
1133+ network.set_deafened(deafened);
1134+ let _ = this.update_in(cx, |yumush, _, cx| {
1135+ yumush.chat.voice.insert(community_id.clone(), participants);
1136+ yumush.chat.voice_state = VoiceState::In {
1137+ community_id,
1138+ muted,
1139+ deafened,
1140+ };
1141+ yumush.start_voice_poll(cx);
1142+ cx.notify();
1143+ });
1144+ }
1145+ Err(error) => {
1146+ let _ = this.update(cx, |yumush, cx| {
1147+ yumush.chat.set_voice_off();
1148+ cx.notify();
1149+ });
1150+ notify_error(&this, cx, error);
1151+ }
1152+ }
1153+ })
1154+ .detach();
1155+ }
1156+
1157+ pub(super) fn end_voice(&mut self, cx: &mut Context<Self>) {
1158+ if self.chat.voice_community().is_none() {
1159+ return;
1160+ }
1161+ self.chat.set_voice_off();
1162+ let network = self.network.clone();
1163+
1164+ cx.spawn(async move |_, _| {
1165+ let _ = network.leave_voice().await;
1166+ })
1167+ .detach();
1168+ }
1169+
1170+ pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context<Self>) {
1171+ if self.chat.in_voice(community_id) {
1172+ self.end_voice(cx);
1173+ }
1174+ }
1175+
1176+ fn toggle_mute(&mut self, cx: &mut Context<Self>) {
1177+ if let VoiceState::In { muted, .. } = &mut self.chat.voice_state {
1178+ *muted = !*muted;
1179+ self.network.set_muted(*muted);
1180+ }
1181+ cx.notify();
1182+ }
1183+
1184+ fn toggle_deafen(&mut self, cx: &mut Context<Self>) {
1185+ if let VoiceState::In { deafened, .. } = &mut self.chat.voice_state {
1186+ *deafened = !*deafened;
1187+ self.network.set_deafened(*deafened);
1188+ }
1189+ cx.notify();
1190+ }
1191+
1192+ fn start_voice_poll(&mut self, cx: &mut Context<Self>) {
1193+ let network = self.network.clone();
1194+
1195+ self.chat.voice_task = Some(cx.spawn(async move |this, cx| {
1196+ loop {
1197+ cx.background_executor()
1198+ .timer(Duration::from_millis(150))
1199+ .await;
1200+ let speaking = network.speaking();
1201+ let polling = this.update(cx, |yumush, cx| {
1202+ if yumush.chat.voice_community().is_none() {
1203+ return false;
1204+ }
1205+ yumush.update_speaking(speaking, cx);
1206+ true
1207+ });
1208+ if !matches!(polling, Ok(true)) {
1209+ break;
1210+ }
1211+ }
1212+ }));
1213+ }
1214+
1215+ fn update_speaking(&mut self, mut speaking: Vec<String>, cx: &mut Context<Self>) {
1216+ let silent = self
1217+ .chat
1218+ .voice_flags()
1219+ .is_some_and(|(muted, deafened)| muted || deafened);
1220+ if silent {
1221+ speaking.retain(|id| !self.is_me(id));
1222+ }
1223+
1224+ let speaking: HashSet<String> = speaking.into_iter().collect();
1225+ if speaking != self.chat.speaking {
1226+ self.chat.speaking = speaking;
1227+ cx.notify();
1228+ }
1229+ }
1230+
1231+ fn voice_button(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
1232+ let community_id = self.chat.selected_community_id.clone()?;
1233+ let in_voice = self.chat.in_voice(&community_id);
1234+ if !in_voice && !permission::can_join_voice(self.actor_rank()) {
1235+ return None;
1236+ }
1237+
1238+ let entity = entity.clone();
1239+ let on_click = move |window: &mut Window, cx: &mut App| {
1240+ entity.update(cx, |yumush, cx| {
1241+ yumush.toggle_voice(community_id.clone(), window, cx)
1242+ })
1243+ };
1244+ let button = if in_voice {
1245+ primary_button("voice_button", palette, on_click)
1246+ } else {
1247+ clickable("voice_button", palette, on_click)
1248+ };
1249+
1250+ Some(
1251+ button
1252+ .tip(if in_voice {
1253+ "Leave voice"
1254+ } else {
1255+ "Join voice"
1256+ })
1257+ .size(px(28.))
1258+ .flex()
1259+ .items_center()
1260+ .justify_center()
1261+ .rounded(px(6.))
1262+ .text_color(if in_voice {
1263+ palette.on_accent
1264+ } else {
1265+ palette.accent
1266+ })
1267+ .child(Icon::new(IconName::Headphones).w(px(14.)).h(px(14.))),
1268+ )
1269+ }
1270+
1271+ fn voice_stack(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
1272+ let community_id = self.chat.selected_community_id.as_deref()?;
1273+ let users: Vec<&User> = self
1274+ .chat
1275+ .voice_ids(community_id)
1276+ .iter()
1277+ .filter_map(|id| self.chat.member(id))
1278+ .collect();
1279+ if users.is_empty() {
1280+ return None;
1281+ }
1282+
1283+ Some(
1284+ div()
1285+ .flex()
1286+ .children(users.into_iter().take(3).enumerate().map(|(index, user)| {
1287+ let ring = if self.chat.speaking.contains(&user.id) {
1288+ palette.ok
1289+ } else {
1290+ palette.panel
1291+ };
1292+
1293+ profile_popover(
1294+ format!("voice_{}", user.id),
1295+ Anchor::TopRight,
1296+ user,
1297+ entity,
1298+ avatar(palette, user, px(20.), px(10.), &self.chat.avatars)
1299+ .border_2()
1300+ .border_color(ring)
1301+ .cursor_pointer()
1302+ .hover(move |style| style.border_color(palette.accent))
1303+ .when(index > 0, |this| this.ml(px(-6.))),
1304+ )
1305+ })),
1306+ )
1307+ }
1308+
1309+ pub(super) fn voice_controls(
1310+ &self,
1311+ entity: &Entity<Self>,
1312+ palette: Palette,
1313+ ) -> Option<impl IntoElement> {
1314+ let (muted, deafened) = self.chat.voice_flags()?;
1315+ let mic_entity = entity.clone();
1316+ let deafen_entity = entity.clone();
1317+ let mic_icon = if muted {
1318+ IconName::MicOff
1319+ } else {
1320+ IconName::Mic
1321+ };
1322+ let deafen_icon = if deafened {
1323+ IconName::VolumeX
1324+ } else {
1325+ IconName::Headphones
1326+ };
1327+
1328+ Some(
1329+ div()
1330+ .flex()
1331+ .items_center()
1332+ .child(
1333+ clickable("mic_button", palette, move |_, cx| {
1334+ mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(cx))
1335+ })
1336+ .tip(if muted { "Unmute" } else { "Mute" })
1337+ .size(px(26.))
1338+ .flex()
1339+ .items_center()
1340+ .justify_center()
1341+ .rounded(px(6.))
1342+ .text_color(if muted || deafened {
1343+ palette.danger
1344+ } else {
1345+ palette.muted
1346+ })
1347+ .child(Icon::new(mic_icon).w(px(14.)).h(px(14.))),
1348+ )
1349+ .child(
1350+ clickable("deafen_button", palette, move |_, cx| {
1351+ deafen_entity.update(cx, |yumush, cx| yumush.toggle_deafen(cx))
1352+ })
1353+ .tip(if deafened { "Undeafen" } else { "Deafen" })
1354+ .size(px(26.))
1355+ .flex()
1356+ .items_center()
1357+ .justify_center()
1358+ .rounded(px(6.))
1359+ .text_color(if deafened {
1360+ palette.danger
1361+ } else {
1362+ palette.muted
1363+ })
1364+ .child(Icon::new(deafen_icon).w(px(14.)).h(px(14.))),
1365+ ),
1366+ )
1367+ }
693 }1368 }
694 1369
695-fn leave_button(entity: &Entity<Yumush>) -> impl IntoElement {1370+fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> impl IntoElement {
696 let entity = entity.clone();1371 let entity = entity.clone();
1372+ let voice: Vec<String> = chat
1373+ .selected_community_id
1374+ .as_deref()
1375+ .map(|community_id| chat.voice_ids(community_id).to_vec())
1376+ .unwrap_or_default();
1377+ let members: Vec<(User, Option<Rank>, bool)> = chat
1378+ .members
1379+ .iter()
1380+ .map(|member| {
1381+ (
1382+ member.user.clone(),
1383+ chat.rank_of(&member.user),
1384+ voice.contains(&member.user.id),
1385+ )
1386+ })
1387+ .collect();
1388+ let avatars = chat.avatars.clone();
1389+
1390+ Popover::new("members_popover")
1391+ .anchor(Anchor::TopRight)
1392+ .appearance(false)
1393+ .trigger(MembersTrigger {
1394+ palette,
1395+ members: members.iter().map(|(user, _, _)| user.clone()).collect(),
1396+ avatars: avatars.clone(),
1397+ })
1398+ .content(move |_, _, _| {
1399+ let entity = entity.clone();
697 1400
698- Button::new("leave_community_button")1401+ div()
699- .label("Leave")1402+ .w(px(200.))
700- .on_click(move |_, window, cx| {1403+ .p(px(4.))
701- entity.update(cx, |yumush, cx| yumush.leave_community(window, cx));1404+ .flex()
1405+ .flex_col()
1406+ .rounded(px(8.))
1407+ .border_1()
1408+ .border_color(palette.border)
1409+ .bg(palette.panel)
1410+ .children(members.iter().map(|(user, rank, in_voice)| {
1411+ profile_popover(
1412+ format!("member_{}", user.id),
1413+ Anchor::TopRight,
1414+ user,
1415+ &entity,
1416+ hoverable(
1417+ format!("member_trigger_{}", user.id),
1418+ div()
1419+ .h(px(30.))
1420+ .px(px(8.))
1421+ .flex()
1422+ .items_center()
1423+ .gap(px(8.))
1424+ .rounded(px(6.))
1425+ .child(avatar(palette, user, px(18.), px(9.), &avatars))
1426+ .child(
1427+ div()
1428+ .flex_1()
1429+ .min_w_0()
1430+ .flex()
1431+ .flex_col()
1432+ .child(
1433+ div()
1434+ .flex()
1435+ .items_center()
1436+ .gap(px(6.))
1437+ .child(user.username.clone())
1438+ .children(rank_tag(*rank, palette))
1439+ .children(in_voice.then(|| {
1440+ Icon::new(IconName::Headphones)
1441+ .w(px(12.))
1442+ .h(px(12.))
1443+ .text_color(palette.muted)
1444+ })),
1445+ )
1446+ .children((!user.status.is_empty()).then(|| {
1447+ div()
1448+ .text_size(px(11.))
1449+ .text_color(palette.muted)
1450+ .truncate()
1451+ .child(user.status.clone())
1452+ })),
1453+ ),
1454+ palette,
1455+ ),
1456+ )
1457+ }))
702 })1458 })
703 }1459 }
704 1460
705-fn older_button(entity: &Entity<Yumush>) -> impl IntoElement {1461+fn older_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
706 let entity = entity.clone();1462 let entity = entity.clone();
707 1463
708- Button::new("load_older_button")1464+ clickable("load_older_button", palette, move |window, cx| {
709- .label("↑")1465+ entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx));
710- .on_click(move |_, window, cx| {1466+ })
711- entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx));1467+ .self_center()
712- })1468+ .h(px(24.))
1469+ .px(px(8.))
1470+ .flex()
1471+ .items_center()
1472+ .rounded(px(6.))
1473+ .text_color(palette.muted)
1474+ .child("↑")
713 }1475 }
714 1476
715-fn render_message(message: &Message, members: &[User]) -> impl IntoElement {1477+fn render_message(
716- let username = members1478+ message: &Message,
717- .iter()1479+ first: bool,
718- .find(|user| user.id == message.user_id)1480+ spaced: bool,
1481+ chat: &Chat,
1482+ me: Option<&User>,
1483+ entity: &Entity<Yumush>,
1484+ palette: Palette,
1485+) -> AnyElement {
1486+ let author = chat.author(&message.user_id);
1487+ let username = author
719 .map(|user| user.username.as_str())1488 .map(|user| user.username.as_str())
720- .unwrap_or(message.user_id.as_str());1489+ .unwrap_or("unknown");
721-1490+ let name = div()
722- div()
723 .flex()1491 .flex()
724- .flex_col()1492+ .items_center()
725- .p_1()1493+ .gap(px(8.))
1494+ .child(match author {
1495+ Some(user) => avatar(palette, user, px(20.), px(10.), &chat.avatars),
1496+ None => badge(palette, &message.user_id, username, px(20.), px(10.)).rounded_full(),
1497+ })
726 .child(1498 .child(
727 div()1499 div()
728- .text_color(rgb(0x7289da))1500+ .id(format!("author_name_{}", message.id))
729- .font_weight(FontWeight::BOLD)1501+ .font_weight(FontWeight::SEMIBOLD)
1502+ .text_color(palette.tinted(&message.user_id))
1503+ .when(author.is_some(), |this| {
1504+ this.hover(|style| style.underline())
1505+ })
730 .child(username.to_string()),1506 .child(username.to_string()),
731- )1507+ );
732- .child(div().pl_2().child(message.body.clone()))1508+ let group = format!("message_{}", message.id);
1509+ let selecting = matches!(chat.composer, Composer::Select { .. });
1510+ let selected = matches!(&chat.composer, Composer::Select { ids } if ids.contains(&message.id));
1511+
1512+ let row =
1513+ div()
1514+ .id(format!("message_row_{}", message.id))
1515+ .group(group.clone())
1516+ .flex()
1517+ .flex_col()
1518+ .min_w_0()
1519+ .when(first && spaced, |this| this.mt(px(14.)))
1520+ .when(first, |this| {
1521+ let author = match author {
1522+ Some(user) => profile_popover(
1523+ format!("author_{}", message.id),
1524+ Anchor::TopLeft,
1525+ user,
1526+ entity,
1527+ name.cursor_pointer(),
1528+ )
1529+ .into_any_element(),
1530+ None => name.into_any_element(),
1531+ };
1532+
1533+ this.child(
1534+ div()
1535+ .flex()
1536+ .items_center()
1537+ .gap(px(8.))
1538+ .mb(px(2.))
1539+ .child(author)
1540+ .child(
1541+ div()
1542+ .text_size(px(12.))
1543+ .text_color(palette.muted)
1544+ .child(id_time(&message.id, "%H:%M")),
1545+ ),
1546+ )
1547+ })
1548+ .child(
1549+ div()
1550+ .pl(px(28.))
1551+ .flex()
1552+ .items_center()
1553+ .gap(px(8.))
1554+ .child(
1555+ div()
1556+ .max_w(px(720.))
1557+ .flex()
1558+ .flex_col()
1559+ .gap(px(6.))
1560+ .children(message_actions::quote_line(message, chat, palette))
1561+ .when(!message.body.is_empty(), |this| {
1562+ this.child(
1563+ div()
1564+ .flex()
1565+ .flex_wrap()
1566+ .items_baseline()
1567+ .gap(px(4.))
1568+ .line_height(relative(1.55))
1569+ .text_color(palette.body)
1570+ .child(message.body.clone())
1571+ .when(message.edited, |this| {
1572+ this.child(
1573+ div()
1574+ .text_size(px(11.))
1575+ .text_color(palette.muted)
1576+ .child("(edited)"),
1577+ )
1578+ }),
1579+ )
1580+ })
1581+ .children(media_view::attachments(
1582+ &message.attachments,
1583+ &chat.media,
1584+ entity,
1585+ palette,
1586+ ))
1587+ .children(snippet::snippet_card(message, chat, entity, palette))
1588+ .children(media_view::embeds(message, &chat.media, palette)),
1589+ )
1590+ .child(div().flex_1())
1591+ .children((!selecting).then(|| {
1592+ message_actions::actions(message, chat, me, entity, palette, group)
1593+ })),
1594+ );
1595+
1596+ if !selecting {
1597+ return row.into_any_element();
1598+ }
1599+
1600+ let message_id = message.id.clone();
1601+ let select_entity = entity.clone();
1602+ let row = row
1603+ .flex_1()
1604+ .cursor_pointer()
1605+ .when(selected, |this| this.bg(palette.hover))
1606+ .on_click(move |_, _, cx| {
1607+ select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx));
1608+ });
1609+
1610+ div()
1611+ .flex()
1612+ .items_start()
1613+ .gap(px(8.))
1614+ .child(message_actions::selection_mark(selected, palette))
1615+ .child(row)
1616+ .into_any_element()
1617+}
1618+
1619+fn editable_input(
1620+ placeholder: &'static str,
1621+ save: fn(&mut Yumush, &mut Window, &mut Context<Yumush>),
1622+ window: &mut Window,
1623+ cx: &mut Context<Yumush>,
1624+) -> Entity<InputState> {
1625+ let input = new_input(placeholder, window, cx);
1626+ cx.subscribe_in(
1627+ &input,
1628+ window,
1629+ move |this, _, event, window, cx| match event {
1630+ InputEvent::PressEnter { .. } => save(this, window, cx),
1631+ InputEvent::Change => cx.notify(),
1632+ _ => {}
1633+ },
1634+ )
1635+ .detach();
1636+ input
733 }1637 }
crates/client/src/gui/community_settings.rsadded+660 -0
@@ -0,0 +1,660 @@
1+use std::{collections::HashMap, sync::Arc};
2+
3+use common::{
4+ error::Error,
5+ model::{Ban, Community, LogAction, LogEntry, User},
6+ permission,
7+ validate::validate_community_name,
8+};
9+use gpui_kit::{
10+ AnyElement, App, AsyncWindowContext, Context, Div, Entity, Image, InteractiveElement,
11+ IntoElement, ParentElement, PathPromptOptions, StatefulInteractiveElement, Styled, WeakEntity,
12+ Window,
13+ component::{
14+ WindowExt,
15+ input::{Input, InputState},
16+ notification::Notification,
17+ },
18+ div,
19+ prelude::FluentBuilder as _,
20+ px,
21+};
22+
23+use super::{
24+ Palette, Yumush, avatar,
25+ chat::{DeleteStep, View},
26+ clickable, community_icon, entity_action, id_time, notify_error,
27+ settings_page::{
28+ Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file,
29+ row, section, text_row,
30+ },
31+};
32+
33+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34+pub(super) enum BanSort {
35+ Newest,
36+ Oldest,
37+ Name,
38+}
39+
40+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41+pub(super) enum LogSort {
42+ Newest,
43+ Oldest,
44+}
45+
46+const BAN_SORTS: [(BanSort, &str); 3] = [
47+ (BanSort::Newest, "Newest"),
48+ (BanSort::Oldest, "Oldest"),
49+ (BanSort::Name, "Name"),
50+];
51+
52+const LOG_SORTS: [(LogSort, &str); 2] = [(LogSort::Newest, "Newest"), (LogSort::Oldest, "Oldest")];
53+
54+fn apply_community(
55+ this: &WeakEntity<Yumush>,
56+ cx: &mut AsyncWindowContext,
57+ result: Result<Community, Error>,
58+) {
59+ match result {
60+ Ok(community) => {
61+ let _ = this.update(cx, |yumush, cx| {
62+ yumush.chat.insert_community(community);
63+ yumush.request_social_avatars(cx);
64+ cx.notify();
65+ });
66+ }
67+ Err(error) => notify_error(this, cx, error),
68+ }
69+}
70+
71+impl Yumush {
72+ pub(super) fn community_settings_page(
73+ &self,
74+ entity: &Entity<Self>,
75+ palette: Palette,
76+ cx: &App,
77+ ) -> impl IntoElement {
78+ let name = self
79+ .chat
80+ .selected_community()
81+ .map(|community| community.name.clone())
82+ .unwrap_or_default();
83+ let actor = self.actor_rank();
84+ let community_id = self.chat.selected_community_id.clone().unwrap_or_default();
85+ let bans_count = self.chat.bans.len();
86+ let mut sections = Vec::new();
87+
88+ if let Some(community) = self
89+ .chat
90+ .selected_community()
91+ .filter(|_| permission::can_rename_community(actor))
92+ {
93+ sections.push(
94+ picture_card(
95+ Picture {
96+ id: "community_picture_picker",
97+ image: community_icon(
98+ palette,
99+ community,
100+ px(64.),
101+ px(24.),
102+ &self.chat.avatars,
103+ ),
104+ title: community.name.clone(),
105+ subtitle: String::new(),
106+ removable: community.avatar_id.is_some(),
107+ upload: Yumush::upload_community_picture,
108+ remove: Yumush::remove_community_picture,
109+ },
110+ entity,
111+ palette,
112+ )
113+ .into_any_element(),
114+ );
115+ }
116+ if permission::can_rename_community(actor) {
117+ sections.push(
118+ section(
119+ "General",
120+ palette,
121+ vec![text_row(
122+ Editable {
123+ id: "save_community_name_button",
124+ label: "Name",
125+ input: &self.chat.community_name_input,
126+ current: &name,
127+ save: Yumush::save_community_name,
128+ },
129+ entity,
130+ palette,
131+ cx,
132+ )],
133+ )
134+ .into_any_element(),
135+ );
136+ }
137+ let mut moderation = Vec::new();
138+ if permission::can_unban(actor) {
139+ moderation.push(row(
140+ "Bans",
141+ div()
142+ .flex()
143+ .items_center()
144+ .gap(px(8.))
145+ .child(
146+ div()
147+ .text_size(px(12.))
148+ .text_color(palette.muted)
149+ .child(bans_count.to_string()),
150+ )
151+ .child(view_control(
152+ "view_bans_button",
153+ entity,
154+ palette,
155+ Yumush::open_bans,
156+ )),
157+ ));
158+ }
159+ if permission::can_read_logs(actor) {
160+ moderation.push(row(
161+ "Logs",
162+ view_control("view_logs_button", entity, palette, Yumush::open_logs),
163+ ));
164+ }
165+ if !moderation.is_empty() {
166+ sections.push(section("Moderation", palette, moderation).into_any_element());
167+ }
168+ let mut danger = Vec::new();
169+ if permission::can_leave(actor) {
170+ danger.push(row(
171+ "Leave community",
172+ leave_control(entity, community_id, palette),
173+ ));
174+ }
175+ if permission::can_delete_community(actor) {
176+ danger.push(row(
177+ "Delete community",
178+ delete_control(
179+ "delete_community_button",
180+ self.chat.delete_step,
181+ entity,
182+ palette,
183+ Yumush::delete_community,
184+ ),
185+ ));
186+ }
187+ if !danger.is_empty() {
188+ sections.push(danger_section(palette, danger).into_any_element());
189+ }
190+
191+ page("community_settings_scroll", entity, palette, name, sections)
192+ }
193+
194+ pub(super) fn save_community_name(&mut self, window: &mut Window, cx: &mut Context<Self>) {
195+ let Some(community_id) = self.chat.selected_community_id.clone() else {
196+ return;
197+ };
198+ let name = self.chat.community_name_input.read(cx).text().to_string();
199+
200+ if let Err(error) = validate_community_name(&name) {
201+ window.push_notification(Notification::error(error.to_string()), cx);
202+ return;
203+ }
204+
205+ let network = self.network.clone();
206+
207+ cx.spawn_in(window, async move |this, cx| {
208+ match network.update_community(&community_id, &name).await {
209+ Ok(community) => {
210+ let _ = this.update(cx, |yumush, cx| {
211+ yumush.chat.insert_community(community);
212+ cx.notify();
213+ });
214+ }
215+ Err(error) => notify_error(&this, cx, error),
216+ }
217+ })
218+ .detach();
219+ }
220+
221+ fn upload_community_picture(&mut self, window: &mut Window, cx: &mut Context<Self>) {
222+ let Some(community_id) = self.chat.selected_community_id.clone() else {
223+ return;
224+ };
225+ let picked = cx.prompt_for_paths(PathPromptOptions {
226+ files: true,
227+ directories: false,
228+ multiple: false,
229+ prompt: None,
230+ });
231+ let network = self.network.clone();
232+
233+ cx.spawn_in(window, async move |this, cx| {
234+ let Ok(Ok(Some(paths))) = picked.await else {
235+ return;
236+ };
237+ let Some(path) = paths.into_iter().next() else {
238+ return;
239+ };
240+ let prepared = cx
241+ .background_executor()
242+ .spawn(async move { read_avatar_file(&path) })
243+ .await;
244+ let result = match prepared {
245+ Ok(bytes) => {
246+ network
247+ .update_community_avatar(&community_id, Some(bytes))
248+ .await
249+ }
250+ Err(error) => Err(error),
251+ };
252+ apply_community(&this, cx, result);
253+ })
254+ .detach();
255+ }
256+
257+ fn remove_community_picture(&mut self, window: &mut Window, cx: &mut Context<Self>) {
258+ let Some(community_id) = self.chat.selected_community_id.clone() else {
259+ return;
260+ };
261+ let network = self.network.clone();
262+
263+ cx.spawn_in(window, async move |this, cx| {
264+ let result = network.update_community_avatar(&community_id, None).await;
265+ apply_community(&this, cx, result);
266+ })
267+ .detach();
268+ }
269+
270+ pub(super) fn delete_community(&mut self, window: &mut Window, cx: &mut Context<Self>) {
271+ match self.chat.delete_step {
272+ DeleteStep::Idle => {
273+ self.chat.delete_step = DeleteStep::Confirm;
274+ cx.notify();
275+ }
276+ DeleteStep::Confirm => {
277+ let Some(community_id) = self.chat.selected_community_id.clone() else {
278+ return;
279+ };
280+ let network = self.network.clone();
281+
282+ cx.spawn_in(window, async move |this, cx| {
283+ match network.delete_community(&community_id).await {
284+ Ok(()) => {
285+ let _ = this.update_in(cx, |yumush, window, cx| {
286+ yumush.chat.remove_community(&community_id);
287+ yumush.show_view(View::Chat, window, cx);
288+ });
289+ }
290+ Err(error) => notify_error(&this, cx, error),
291+ }
292+ })
293+ .detach();
294+ }
295+ }
296+ }
297+
298+ pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context<Self>) {
299+ let Some(community_id) = self.chat.selected_community_id.clone() else {
300+ return;
301+ };
302+ let network = self.network.clone();
303+ let user_id = user_id.to_string();
304+
305+ cx.spawn_in(window, async move |this, cx| {
306+ match network.unban(&community_id, &user_id).await {
307+ Ok(()) => {
308+ let _ = this.update_in(cx, |yumush, window, cx| {
309+ yumush.chat.bans.retain(|ban| ban.user.id != user_id);
310+ window.refresh();
311+ cx.notify();
312+ });
313+ }
314+ Err(error) => notify_error(&this, cx, error),
315+ }
316+ })
317+ .detach();
318+ }
319+
320+ fn open_bans(&mut self, window: &mut Window, cx: &mut Context<Self>) {
321+ let entity = cx.entity();
322+ window.open_dialog(cx, move |dialog, _, cx| {
323+ let yumush = entity.read(cx);
324+ let palette = yumush.themed(cx);
325+ let query = search_text(&yumush.chat.ban_search, cx);
326+ let rows: Vec<AnyElement> = ban_list(&yumush.chat.bans, &query, yumush.chat.ban_sort)
327+ .into_iter()
328+ .map(|ban| ban_row(ban, &entity, palette, &yumush.chat.avatars).into_any_element())
329+ .collect();
330+
331+ dialog.title("Bans").child(moderation_body(
332+ "bans_scroll",
333+ &yumush.chat.ban_search,
334+ sort_control(
335+ BAN_SORTS,
336+ yumush.chat.ban_sort,
337+ &entity,
338+ palette,
339+ Yumush::set_ban_sort,
340+ ),
341+ rows,
342+ "No bans",
343+ palette,
344+ ))
345+ });
346+ }
347+
348+ fn open_logs(&mut self, window: &mut Window, cx: &mut Context<Self>) {
349+ self.load_logs(window, cx);
350+ let entity = cx.entity();
351+ window.open_dialog(cx, move |dialog, _, cx| {
352+ let yumush = entity.read(cx);
353+ let palette = yumush.themed(cx);
354+ let query = search_text(&yumush.chat.log_search, cx);
355+ let rows: Vec<AnyElement> = log_list(&yumush.chat.logs, &query, yumush.chat.log_sort)
356+ .into_iter()
357+ .map(|entry| log_row(entry, palette, &yumush.chat.avatars).into_any_element())
358+ .collect();
359+
360+ dialog.title("Logs").child(moderation_body(
361+ "logs_scroll",
362+ &yumush.chat.log_search,
363+ sort_control(
364+ LOG_SORTS,
365+ yumush.chat.log_sort,
366+ &entity,
367+ palette,
368+ Yumush::set_log_sort,
369+ ),
370+ rows,
371+ "No logs",
372+ palette,
373+ ))
374+ });
375+ }
376+
377+ fn set_ban_sort(&mut self, sort: BanSort, window: &mut Window, cx: &mut Context<Self>) {
378+ self.chat.ban_sort = sort;
379+ window.refresh();
380+ cx.notify();
381+ }
382+
383+ fn set_log_sort(&mut self, sort: LogSort, window: &mut Window, cx: &mut Context<Self>) {
384+ self.chat.log_sort = sort;
385+ window.refresh();
386+ cx.notify();
387+ }
388+
389+ fn load_logs(&self, window: &mut Window, cx: &mut Context<Self>) {
390+ let Some(community_id) = self.chat.selected_community_id.clone() else {
391+ return;
392+ };
393+ let network = self.network.clone();
394+
395+ cx.spawn_in(window, async move |this, cx| {
396+ let logs = match network.logs(&community_id).await {
397+ Ok(logs) => logs,
398+ Err(error) => {
399+ notify_error(&this, cx, error);
400+ return;
401+ }
402+ };
403+
404+ let _ = this.update_in(cx, |yumush, window, cx| {
405+ if yumush.chat.is_selected(&community_id) {
406+ for entry in &logs {
407+ if let Some(actor) = &entry.actor {
408+ yumush.request_user_avatar(actor, cx);
409+ }
410+ if let Some(target) = &entry.target {
411+ yumush.request_user_avatar(target, cx);
412+ }
413+ }
414+ yumush.chat.logs = logs;
415+ window.refresh();
416+ cx.notify();
417+ }
418+ });
419+ })
420+ .detach();
421+ }
422+}
423+
424+fn view_control(
425+ id: &'static str,
426+ entity: &Entity<Yumush>,
427+ palette: Palette,
428+ open: fn(&mut Yumush, &mut Window, &mut Context<Yumush>),
429+) -> impl IntoElement {
430+ clickable(id, palette, entity_action(entity, open))
431+ .h(px(28.))
432+ .px(px(10.))
433+ .flex()
434+ .items_center()
435+ .rounded(px(6.))
436+ .border_1()
437+ .border_color(palette.border)
438+ .text_size(px(13.))
439+ .child("View")
440+}
441+
442+fn sort_control<T: Copy + PartialEq + 'static, const N: usize>(
443+ options: [(T, &'static str); N],
444+ selected: T,
445+ entity: &Entity<Yumush>,
446+ palette: Palette,
447+ select: fn(&mut Yumush, T, &mut Window, &mut Context<Yumush>),
448+) -> impl IntoElement {
449+ div()
450+ .h(px(24.))
451+ .p(px(2.))
452+ .flex()
453+ .gap(px(2.))
454+ .rounded(px(6.))
455+ .border_1()
456+ .border_color(palette.border)
457+ .bg(palette.field)
458+ .children(options.map(|(choice, label)| {
459+ let active = choice == selected;
460+
461+ clickable(
462+ label,
463+ palette,
464+ entity_action(entity, move |yumush, window, cx| {
465+ select(yumush, choice, window, cx)
466+ }),
467+ )
468+ .px(px(8.))
469+ .flex()
470+ .items_center()
471+ .rounded(px(4.))
472+ .text_size(px(12.))
473+ .text_color(if active { palette.text } else { palette.muted })
474+ .when(active, |this| this.bg(palette.hover))
475+ .child(label)
476+ }))
477+}
478+
479+fn moderation_body(
480+ id: &'static str,
481+ search: &Entity<InputState>,
482+ sort: impl IntoElement,
483+ rows: Vec<AnyElement>,
484+ empty: &'static str,
485+ palette: Palette,
486+) -> impl IntoElement {
487+ let list = if rows.is_empty() {
488+ div()
489+ .text_size(px(13.))
490+ .text_color(palette.muted)
491+ .child(empty)
492+ .into_any_element()
493+ } else {
494+ div().flex().flex_col().children(rows).into_any_element()
495+ };
496+
497+ div()
498+ .flex()
499+ .flex_col()
500+ .gap(px(12.))
501+ .child(Input::new(search))
502+ .child(sort)
503+ .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list))
504+}
505+
506+fn search_text(input: &Entity<InputState>, cx: &App) -> String {
507+ input.read(cx).text().to_string().trim().to_lowercase()
508+}
509+
510+fn ban_list<'a>(bans: &'a [Ban], query: &str, sort: BanSort) -> Vec<&'a Ban> {
511+ let mut list: Vec<&Ban> = bans
512+ .iter()
513+ .filter(|ban| ban.user.username.to_lowercase().contains(query))
514+ .collect();
515+ match sort {
516+ BanSort::Newest => {}
517+ BanSort::Oldest => list.reverse(),
518+ BanSort::Name => list.sort_by_key(|ban| ban.user.username.to_lowercase()),
519+ }
520+ list
521+}
522+
523+fn log_list<'a>(logs: &'a [LogEntry], query: &str, sort: LogSort) -> Vec<&'a LogEntry> {
524+ let mut list: Vec<&LogEntry> = logs
525+ .iter()
526+ .filter(|entry| log_text(entry).to_lowercase().contains(query))
527+ .collect();
528+ match sort {
529+ LogSort::Newest => {}
530+ LogSort::Oldest => list.reverse(),
531+ }
532+ list
533+}
534+
535+fn user_name(user: &Option<User>) -> &str {
536+ user.as_ref()
537+ .map_or("someone", |user| user.username.as_str())
538+}
539+
540+fn with_reason(text: String, reason: &Option<String>) -> String {
541+ match reason {
542+ Some(reason) => format!("{text} · {reason}"),
543+ None => text,
544+ }
545+}
546+
547+fn log_text(entry: &LogEntry) -> String {
548+ let actor = user_name(&entry.actor);
549+ let target = user_name(&entry.target);
550+
551+ match &entry.action {
552+ LogAction::Created => format!("{actor} created the community"),
553+ LogAction::Renamed { name } => format!("{actor} renamed to {name}"),
554+ LogAction::AvatarChanged => format!("{actor} changed the avatar"),
555+ LogAction::AvatarRemoved => format!("{actor} removed the avatar"),
556+ LogAction::Invited => format!("{actor} invited {target}"),
557+ LogAction::Joined => format!("{actor} joined"),
558+ LogAction::Left => format!("{actor} left"),
559+ LogAction::Kicked { reason } => with_reason(format!("{actor} kicked {target}"), reason),
560+ LogAction::Banned { reason } => with_reason(format!("{actor} banned {target}"), reason),
561+ LogAction::Unbanned => format!("{actor} unbanned {target}"),
562+ LogAction::RankChanged { rank } => {
563+ format!("{actor} changed rank of {target} to {}", rank.as_str())
564+ }
565+ LogAction::MessageDeleted => format!("{actor} deleted a message by {target}"),
566+ }
567+}
568+
569+fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap<String, Arc<Image>>) -> Div {
570+ div()
571+ .min_h(px(40.))
572+ .px(px(12.))
573+ .flex()
574+ .items_center()
575+ .gap(px(8.))
576+ .children(
577+ entry
578+ .actor
579+ .as_ref()
580+ .map(|actor| avatar(palette, actor, px(20.), px(10.), avatars)),
581+ )
582+ .child(div().flex_1().min_w_0().truncate().child(log_text(entry)))
583+ .child(
584+ div()
585+ .flex_shrink_0()
586+ .text_size(px(11.))
587+ .text_color(palette.muted)
588+ .child(id_time(&entry.id, "%b %-d, %H:%M")),
589+ )
590+}
591+
592+fn leave_control(
593+ entity: &Entity<Yumush>,
594+ community_id: String,
595+ palette: Palette,
596+) -> impl IntoElement {
597+ let entity = entity.clone();
598+
599+ clickable("leave_community_button", palette, move |window, cx| {
600+ entity.update(cx, |yumush, cx| {
601+ yumush.leave_community(community_id.clone(), window, cx)
602+ });
603+ })
604+ .h(px(28.))
605+ .px(px(10.))
606+ .flex()
607+ .items_center()
608+ .rounded(px(6.))
609+ .border_1()
610+ .border_color(palette.danger.opacity(0.5))
611+ .text_size(px(13.))
612+ .text_color(palette.danger)
613+ .child("Leave")
614+}
615+
616+fn ban_row(
617+ ban: &Ban,
618+ entity: &Entity<Yumush>,
619+ palette: Palette,
620+ avatars: &HashMap<String, Arc<Image>>,
621+) -> Div {
622+ let entity = entity.clone();
623+ let user = &ban.user;
624+ let user_id = user.id.clone();
625+
626+ div()
627+ .h(px(48.))
628+ .px(px(12.))
629+ .flex()
630+ .items_center()
631+ .gap(px(8.))
632+ .child(avatar(palette, user, px(20.), px(10.), avatars))
633+ .child(
634+ div()
635+ .flex_1()
636+ .min_w_0()
637+ .flex()
638+ .flex_col()
639+ .child(user.username.clone())
640+ .children(ban.reason.clone().map(|reason| {
641+ div()
642+ .text_size(px(11.))
643+ .text_color(palette.muted)
644+ .truncate()
645+ .child(reason)
646+ })),
647+ )
648+ .child(
649+ clickable(format!("unban_{}", user.id), palette, move |window, cx| {
650+ entity.update(cx, |yumush, cx| yumush.unban(&user_id, window, cx));
651+ })
652+ .h(px(28.))
653+ .px(px(8.))
654+ .flex()
655+ .items_center()
656+ .rounded(px(6.))
657+ .text_color(palette.danger)
658+ .child("Unban"),
659+ )
660+}
crates/client/src/gui/composer.rsadded+294 -0
@@ -0,0 +1,294 @@
1+use common::{
2+ constant::MAXIMUM_FORWARD_MESSAGES,
3+ validate::{validate_message_body, validate_new_message},
4+};
5+use gpui_kit::{
6+ AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
7+ assets::IconName,
8+ component::{Icon, WindowExt, input::InputState, notification::Notification},
9+ div, px,
10+};
11+
12+use super::{Palette, Tooltip as _, Yumush, chat::Chat, clickable, notify_error, primary_button};
13+
14+#[derive(Debug, Clone, PartialEq, Eq)]
15+pub enum Composer {
16+ Compose { reply: Option<String> },
17+ Edit { message_id: String },
18+ Select { ids: Vec<String> },
19+}
20+
21+pub fn mode_bar(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> Option<AnyElement> {
22+ match &chat.composer {
23+ Composer::Compose {
24+ reply: Some(message_id),
25+ } => Some(reply_bar(chat, message_id, entity, palette).into_any_element()),
26+ Composer::Edit { .. } => Some(edit_bar(entity, palette).into_any_element()),
27+ Composer::Compose { reply: None } | Composer::Select { .. } => None,
28+ }
29+}
30+
31+pub fn selection_bar(
32+ ids: &[String],
33+ entity: &Entity<Yumush>,
34+ palette: Palette,
35+) -> impl IntoElement {
36+ let count = ids.len();
37+ let selected = ids.to_vec();
38+ let forward_entity = entity.clone();
39+
40+ div()
41+ .h(px(40.))
42+ .pl(px(14.))
43+ .pr(px(6.))
44+ .flex()
45+ .items_center()
46+ .gap(px(8.))
47+ .rounded(px(8.))
48+ .border_1()
49+ .border_color(palette.border)
50+ .bg(palette.field)
51+ .child(div().flex_1().child(format!("{count} selected")))
52+ .child(
53+ primary_button("forward_selected", palette, move |window, cx| {
54+ let selected = selected.clone();
55+ forward_entity.update(cx, |yumush, cx| yumush.open_forward(selected, window, cx));
56+ })
57+ .h(px(28.))
58+ .px(px(10.))
59+ .flex()
60+ .items_center()
61+ .rounded(px(6.))
62+ .text_size(px(12.))
63+ .child("Forward"),
64+ )
65+ .child(cancel_button(entity, palette))
66+}
67+
68+fn bar(palette: Palette) -> Div {
69+ div()
70+ .h(px(28.))
71+ .mb(px(8.))
72+ .px(px(8.))
73+ .flex()
74+ .items_center()
75+ .gap(px(6.))
76+ .rounded(px(6.))
77+ .bg(palette.hover)
78+ .text_size(px(12.))
79+ .text_color(palette.muted)
80+}
81+
82+fn reply_bar(
83+ chat: &Chat,
84+ message_id: &str,
85+ entity: &Entity<Yumush>,
86+ palette: Palette,
87+) -> impl IntoElement {
88+ let message = chat
89+ .messages
90+ .iter()
91+ .find(|message| message.id == message_id);
92+ let author = message
93+ .and_then(|message| chat.author(&message.user_id))
94+ .map_or("unknown", |user| user.username.as_str())
95+ .to_string();
96+ let quote = message
97+ .map(|message| super::message_actions::quote_text(&message.body, message.attachments.len()))
98+ .unwrap_or_default();
99+
100+ bar(palette)
101+ .child("Replying to")
102+ .child(
103+ div()
104+ .font_weight(FontWeight::SEMIBOLD)
105+ .text_color(palette.text)
106+ .child(author),
107+ )
108+ .child(div().flex_1().min_w_0().truncate().child(quote))
109+ .child(cancel_button(entity, palette))
110+}
111+
112+fn edit_bar(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
113+ bar(palette)
114+ .child(Icon::new(IconName::Pencil).w(px(12.)).h(px(12.)))
115+ .child("Editing")
116+ .child(div().flex_1())
117+ .child(cancel_button(entity, palette))
118+}
119+
120+fn cancel_button(entity: &Entity<Yumush>, palette: Palette) -> impl IntoElement {
121+ let entity = entity.clone();
122+
123+ clickable("cancel_composer", palette, move |window, cx| {
124+ entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx));
125+ })
126+ .tip("Cancel")
127+ .size(px(20.))
128+ .flex_shrink_0()
129+ .flex()
130+ .items_center()
131+ .justify_center()
132+ .rounded(px(4.))
133+ .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.)))
134+}
135+
136+impl Yumush {
137+ pub(super) fn submit_composer(
138+ &mut self,
139+ input: &Entity<InputState>,
140+ window: &mut Window,
141+ cx: &mut Context<Self>,
142+ ) {
143+ if self.chat.media.uploading() {
144+ return;
145+ }
146+ let body = input.read(cx).text().to_string();
147+
148+ match self.chat.composer.clone() {
149+ Composer::Compose { reply } => self.create_message(reply, body, input, window, cx),
150+ Composer::Edit { message_id } => {
151+ self.update_message(message_id, body, input, window, cx)
152+ }
153+ Composer::Select { .. } => {}
154+ }
155+ }
156+
157+ fn create_message(
158+ &mut self,
159+ reply: Option<String>,
160+ body: String,
161+ input: &Entity<InputState>,
162+ window: &mut Window,
163+ cx: &mut Context<Self>,
164+ ) {
165+ let attachments: Vec<String> = self
166+ .chat
167+ .media
168+ .pending
169+ .iter()
170+ .map(|attachment| attachment.id.clone())
171+ .collect();
172+
173+ if let Err(error) = validate_new_message(&body, attachments.len()) {
174+ window.push_notification(Notification::error(error.to_string()), cx);
175+ return;
176+ }
177+ let Some(community_id) = self.chat.selected_community_id.clone() else {
178+ window.push_notification(Notification::error("No Community Selected"), cx);
179+ return;
180+ };
181+ let network = self.network.clone();
182+
183+ cx.spawn_in(window, async move |this, cx| {
184+ if let Err(error) = network
185+ .create_message(&community_id, &body, attachments, reply)
186+ .await
187+ {
188+ notify_error(&this, cx, error);
189+ }
190+ })
191+ .detach();
192+
193+ input.update(cx, |state, cx| state.set_value("", window, cx));
194+ self.chat.media.pending.clear();
195+ self.chat.composer = Composer::Compose { reply: None };
196+ }
197+
198+ fn update_message(
199+ &mut self,
200+ message_id: String,
201+ body: String,
202+ input: &Entity<InputState>,
203+ window: &mut Window,
204+ cx: &mut Context<Self>,
205+ ) {
206+ if let Err(error) = validate_message_body(&body) {
207+ window.push_notification(Notification::error(error.to_string()), cx);
208+ return;
209+ }
210+ let network = self.network.clone();
211+
212+ cx.spawn_in(window, async move |this, cx| {
213+ if let Err(error) = network.update_message(&message_id, &body).await {
214+ notify_error(&this, cx, error);
215+ }
216+ })
217+ .detach();
218+
219+ input.update(cx, |state, cx| state.set_value("", window, cx));
220+ self.chat.composer = Composer::Compose { reply: None };
221+ cx.notify();
222+ }
223+
224+ pub(super) fn reply(
225+ &mut self,
226+ message_id: String,
227+ window: &mut Window,
228+ cx: &mut Context<Self>,
229+ ) {
230+ self.chat.composer = Composer::Compose {
231+ reply: Some(message_id),
232+ };
233+ self.chat.focus(window, cx);
234+ cx.notify();
235+ }
236+
237+ pub(super) fn edit(&mut self, message_id: String, window: &mut Window, cx: &mut Context<Self>) {
238+ let Some(body) = self
239+ .chat
240+ .messages
241+ .iter()
242+ .find(|message| message.id == message_id)
243+ .map(|message| message.body.clone())
244+ else {
245+ return;
246+ };
247+
248+ self.chat
249+ .message_input
250+ .update(cx, |input, cx| input.set_value(body, window, cx));
251+ self.chat.composer = Composer::Edit { message_id };
252+ self.chat.focus(window, cx);
253+ cx.notify();
254+ }
255+
256+ pub(super) fn start_select(
257+ &mut self,
258+ message_id: String,
259+ window: &mut Window,
260+ cx: &mut Context<Self>,
261+ ) {
262+ self.chat.composer = Composer::Select {
263+ ids: vec![message_id],
264+ };
265+ self.focus.focus(window, cx);
266+ cx.notify();
267+ }
268+
269+ pub(super) fn toggle_select(&mut self, message_id: &str, cx: &mut Context<Self>) {
270+ let Composer::Select { ids } = &mut self.chat.composer else {
271+ return;
272+ };
273+ if let Some(index) = ids.iter().position(|id| id == message_id) {
274+ ids.remove(index);
275+ } else if ids.len() < MAXIMUM_FORWARD_MESSAGES {
276+ ids.push(message_id.to_string());
277+ }
278+ cx.notify();
279+ }
280+
281+ pub(super) fn cancel_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
282+ match self.chat.composer.clone() {
283+ Composer::Compose { reply: None } => return,
284+ Composer::Compose { reply: Some(_) } | Composer::Select { .. } => {}
285+ Composer::Edit { .. } => self
286+ .chat
287+ .message_input
288+ .update(cx, |input, cx| input.set_value("", window, cx)),
289+ }
290+ self.chat.composer = Composer::Compose { reply: None };
291+ self.chat.focus(window, cx);
292+ cx.notify();
293+ }
294+}
crates/client/src/gui/forward.rsadded+196 -0
@@ -0,0 +1,196 @@
1+use gpui_kit::{
2+ AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,
3+ StatefulInteractiveElement, Styled, Window,
4+ component::{
5+ WindowExt,
6+ checkbox::Checkbox,
7+ input::{Input, InputEvent, InputState},
8+ },
9+ div, px,
10+};
11+
12+use super::{
13+ Yumush, clickable, community_icon, community_name, composer::Composer, notify_error, palette,
14+};
15+
16+pub struct Forward {
17+ yumush: Entity<Yumush>,
18+ selected: Vec<String>,
19+ filter: Entity<InputState>,
20+ keep_authors: bool,
21+}
22+
23+impl Forward {
24+ fn new(
25+ yumush: Entity<Yumush>,
26+ selected: Vec<String>,
27+ window: &mut Window,
28+ cx: &mut Context<Self>,
29+ ) -> Self {
30+ let filter = cx.new(|cx| {
31+ let mut state = InputState::new(window, cx);
32+ state.set_placeholder("Filter", window, cx);
33+ state
34+ });
35+ cx.subscribe_in(&filter, window, |_, _, event, _, cx| {
36+ if matches!(event, InputEvent::Change) {
37+ cx.notify();
38+ }
39+ })
40+ .detach();
41+
42+ let keep_authors = selected.len() > 1;
43+ Self {
44+ yumush,
45+ selected,
46+ filter,
47+ keep_authors,
48+ }
49+ }
50+}
51+
52+impl Render for Forward {
53+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
54+ let palette = palette(cx);
55+ let query = self.filter.read(cx).text().to_string().to_lowercase();
56+ let entity = cx.entity();
57+ let keep_authors = self.keep_authors;
58+ let rows: Vec<_> = {
59+ let yumush = self.yumush.read(cx);
60+ yumush
61+ .chat
62+ .communities()
63+ .iter()
64+ .filter(|community| community_name(community).to_lowercase().contains(&query))
65+ .enumerate()
66+ .map(|(index, community)| {
67+ let community_id = community.id.clone();
68+ let selected = self.selected.clone();
69+ let forward_entity = self.yumush.clone();
70+
71+ clickable(("forward_to", index), palette, move |window, cx| {
72+ let community_id = community_id.clone();
73+ let selected = selected.clone();
74+ forward_entity.update(cx, |yumush, cx| {
75+ yumush.forward_to(selected, community_id, keep_authors, window, cx)
76+ });
77+ })
78+ .h(px(28.))
79+ .px(px(8.))
80+ .flex()
81+ .items_center()
82+ .gap(px(8.))
83+ .rounded(px(6.))
84+ .child(community_icon(
85+ palette,
86+ community,
87+ px(16.),
88+ px(9.),
89+ &yumush.chat.avatars,
90+ ))
91+ .child(
92+ div()
93+ .flex_1()
94+ .min_w_0()
95+ .truncate()
96+ .child(community_name(community).to_string()),
97+ )
98+ })
99+ .collect()
100+ };
101+
102+ div()
103+ .flex()
104+ .flex_col()
105+ .gap(px(10.))
106+ .child(
107+ div()
108+ .h(px(30.))
109+ .px(px(10.))
110+ .flex()
111+ .items_center()
112+ .rounded(px(8.))
113+ .border_1()
114+ .border_color(palette.border)
115+ .bg(palette.field)
116+ .child(
117+ Input::new(&self.filter)
118+ .appearance(false)
119+ .text_color(palette.text)
120+ .flex_1()
121+ .min_w_0(),
122+ ),
123+ )
124+ .child(
125+ Checkbox::new("keep_authors")
126+ .label("Keep authors")
127+ .checked(keep_authors)
128+ .on_click(move |_, _, cx| {
129+ entity.update(cx, |this, cx| {
130+ this.keep_authors = !this.keep_authors;
131+ cx.notify();
132+ });
133+ }),
134+ )
135+ .child(
136+ div()
137+ .id("forward_list")
138+ .max_h(px(320.))
139+ .flex()
140+ .flex_col()
141+ .gap(px(1.))
142+ .overflow_y_scroll()
143+ .children(rows),
144+ )
145+ }
146+}
147+
148+impl Yumush {
149+ pub(super) fn open_forward(
150+ &mut self,
151+ selected: Vec<String>,
152+ window: &mut Window,
153+ cx: &mut Context<Self>,
154+ ) {
155+ if selected.is_empty() {
156+ return;
157+ }
158+ let yumush = cx.entity();
159+ let forward = cx.new(|cx| Forward::new(yumush, selected, window, cx));
160+
161+ window.open_dialog(cx, move |dialog, _, _| {
162+ dialog.title("Forward").w(px(360.)).child(forward.clone())
163+ });
164+ }
165+
166+ pub(super) fn forward_to(
167+ &mut self,
168+ selected: Vec<String>,
169+ community_id: String,
170+ snippet: bool,
171+ window: &mut Window,
172+ cx: &mut Context<Self>,
173+ ) {
174+ window.close_dialog(cx);
175+ if matches!(self.chat.composer, Composer::Select { .. }) {
176+ self.chat.composer = Composer::Compose { reply: None };
177+ }
178+
179+ let ids: Vec<String> = self
180+ .chat
181+ .messages
182+ .iter()
183+ .filter(|message| selected.contains(&message.id))
184+ .map(|message| message.id.clone())
185+ .collect();
186+ let network = self.network.clone();
187+
188+ cx.spawn_in(window, async move |this, cx| {
189+ if let Err(error) = network.forward_messages(ids, &community_id, snippet).await {
190+ notify_error(&this, cx, error);
191+ }
192+ })
193+ .detach();
194+ cx.notify();
195+ }
196+}
crates/client/src/gui/media_view.rsadded+821 -0
@@ -0,0 +1,821 @@
1+use std::{
2+ collections::{HashMap, HashSet},
3+ path::PathBuf,
4+ sync::Arc,
5+ time::Duration,
6+};
7+
8+use common::{
9+ error::size_text,
10+ model::{Attachment, AttachmentKind, Message},
11+};
12+use gpui_kit::{
13+ App, AppContext, Context, Entity, FontWeight, Image, ImageFormat, InteractiveElement,
14+ IntoElement, ParentElement, PathPromptOptions, RenderImage, StatefulInteractiveElement, Styled,
15+ Subscription, Task, Window,
16+ assets::IconName,
17+ component::{
18+ Icon, WindowExt,
19+ notification::Notification,
20+ slider::{Slider, SliderEvent, SliderState},
21+ },
22+ div, img,
23+ prelude::FluentBuilder as _,
24+ px,
25+};
26+
27+use super::{Palette, Tooltip as _, Yumush, clickable, notify_error};
28+use crate::{
29+ embed::{self, Embed, EmbedKind},
30+ media::Player,
31+};
32+
33+const FRAME_TICK: Duration = Duration::from_millis(16);
34+const IMAGE_BOX: (f32, f32) = (400., 300.);
35+const VIDEO_BOX: (f32, f32) = (480., 270.);
36+const EMBED_IMAGE_BOX: (f32, f32) = (400., 225.);
37+
38+pub struct LoadedEmbed {
39+ embed: Embed,
40+ image: Option<Arc<Image>>,
41+}
42+
43+pub enum PlayState {
44+ Loading,
45+ Ready {
46+ player: Player,
47+ frame: Option<Arc<RenderImage>>,
48+ generation: u64,
49+ seek: Entity<SliderState>,
50+ _subscription: Subscription,
51+ _tick: Task<()>,
52+ },
53+}
54+
55+pub struct Playing {
56+ attachment_id: String,
57+ state: PlayState,
58+}
59+
60+#[derive(Default)]
61+pub struct Media {
62+ pub pending: Vec<Attachment>,
63+ uploading: usize,
64+ thumbnails: HashMap<String, Arc<Image>>,
65+ embeds: HashMap<String, LoadedEmbed>,
66+ requested: HashSet<String>,
67+ playing: Option<Playing>,
68+}
69+
70+impl Media {
71+ pub fn uploading(&self) -> bool {
72+ self.uploading > 0
73+ }
74+
75+ pub fn leave(&mut self) {
76+ self.pending.clear();
77+ self.playing = None;
78+ }
79+}
80+
81+fn image_format(bytes: &[u8]) -> Option<ImageFormat> {
82+ match bytes {
83+ [0x89, b'P', b'N', b'G', ..] => Some(ImageFormat::Png),
84+ [0xFF, 0xD8, 0xFF, ..] => Some(ImageFormat::Jpeg),
85+ [b'G', b'I', b'F', b'8', ..] => Some(ImageFormat::Gif),
86+ [
87+ b'R',
88+ b'I',
89+ b'F',
90+ b'F',
91+ _,
92+ _,
93+ _,
94+ _,
95+ b'W',
96+ b'E',
97+ b'B',
98+ b'P',
99+ ..,
100+ ] => Some(ImageFormat::Webp),
101+ _ => None,
102+ }
103+}
104+
105+fn to_image(bytes: Vec<u8>) -> Option<Arc<Image>> {
106+ image_format(&bytes).map(|format| Arc::new(Image::from_bytes(format, bytes)))
107+}
108+
109+fn fit(width: Option<u32>, height: Option<u32>, limit: (f32, f32)) -> (f32, f32) {
110+ let (Some(width), Some(height)) = (width, height) else {
111+ return limit;
112+ };
113+ let (width, height) = (width.max(1) as f32, height.max(1) as f32);
114+ let scale = (limit.0 / width).min(limit.1 / height).min(1.);
115+ (width * scale, height * scale)
116+}
117+
118+fn cache_path(attachment: &Attachment) -> Option<PathBuf> {
119+ let directory = dirs::cache_dir()?.join("yumush").join("media");
120+ std::fs::create_dir_all(&directory).ok()?;
121+ let extension = attachment
122+ .name
123+ .rsplit_once('.')
124+ .map(|(_, extension)| format!(".{extension}"))
125+ .unwrap_or_default();
126+ Some(directory.join(format!("{}{extension}", attachment.id)))
127+}
128+
129+fn time_text(time: Duration) -> String {
130+ let seconds = time.as_secs();
131+ format!("{}:{:02}", seconds / 60, seconds % 60)
132+}
133+
134+fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> {
135+ let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?;
136+ Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)])))
137+}
138+
139+impl Yumush {
140+ pub(super) fn request_media(&mut self, cx: &mut Context<Self>) {
141+ let mut thumbnails = Vec::new();
142+ let mut links = Vec::new();
143+ let mut avatars = Vec::new();
144+ for message in &self.chat.messages {
145+ let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages);
146+ for item in forwarded.clone() {
147+ if let Some(avatar_id) = &item.avatar_id {
148+ avatars.push(avatar_id.clone());
149+ }
150+ }
151+ for attachment in message
152+ .attachments
153+ .iter()
154+ .chain(forwarded.flat_map(|item| &item.attachments))
155+ {
156+ if attachment.kind == AttachmentKind::Image
157+ && self.chat.media.requested.insert(attachment.id.clone())
158+ {
159+ thumbnails.push(attachment.id.clone());
160+ }
161+ }
162+ for url in embed::urls(&message.body) {
163+ if self.chat.media.requested.insert(url.clone()) {
164+ links.push(url);
165+ }
166+ }
167+ }
168+
169+ for avatar_id in avatars {
170+ self.request_avatar(&avatar_id, cx);
171+ }
172+
173+ for attachment_id in thumbnails {
174+ let network = self.network.clone();
175+ cx.spawn(async move |this, cx| {
176+ let Ok(bytes) = network.download_attachment(&attachment_id, true).await else {
177+ return;
178+ };
179+ let _ = this.update(cx, |yumush, cx| {
180+ if let Some(image) = to_image(bytes) {
181+ yumush.chat.media.thumbnails.insert(attachment_id, image);
182+ cx.notify();
183+ }
184+ });
185+ })
186+ .detach();
187+ }
188+
189+ for url in links {
190+ cx.spawn(async move |this, cx| {
191+ let fetched = cx
192+ .background_executor()
193+ .spawn({
194+ let url = url.clone();
195+ async move { embed::fetch(&url) }
196+ })
197+ .await;
198+ let Some(mut embed) = fetched else {
199+ return;
200+ };
201+ let image = embed.image.take().and_then(to_image);
202+ let _ = this.update(cx, |yumush, cx| {
203+ yumush
204+ .chat
205+ .media
206+ .embeds
207+ .insert(url, LoadedEmbed { embed, image });
208+ cx.notify();
209+ });
210+ })
211+ .detach();
212+ }
213+ }
214+
215+ pub(super) fn attach_files(&mut self, window: &mut Window, cx: &mut Context<Self>) {
216+ let Some(community_id) = self.chat.selected_community_id.clone() else {
217+ return;
218+ };
219+ let picked = cx.prompt_for_paths(PathPromptOptions {
220+ files: true,
221+ directories: false,
222+ multiple: true,
223+ prompt: None,
224+ });
225+ let network = self.network.clone();
226+
227+ cx.spawn_in(window, async move |this, cx| {
228+ let Ok(Ok(Some(paths))) = picked.await else {
229+ return;
230+ };
231+ for path in paths {
232+ let _ = this.update(cx, |yumush, cx| {
233+ yumush.chat.media.uploading += 1;
234+ cx.notify();
235+ });
236+ let result = network.upload_attachment(&community_id, path).await;
237+ let _ = this.update(cx, |yumush, cx| {
238+ yumush.chat.media.uploading -= 1;
239+ if let Ok(attachment) = &result {
240+ yumush.chat.media.pending.push(attachment.clone());
241+ }
242+ cx.notify();
243+ });
244+ if let Err(error) = result {
245+ notify_error(&this, cx, error);
246+ }
247+ }
248+ })
249+ .detach();
250+ }
251+
252+ fn remove_pending(&mut self, attachment_id: &str, cx: &mut Context<Self>) {
253+ self.chat
254+ .media
255+ .pending
256+ .retain(|attachment| attachment.id != attachment_id);
257+ cx.notify();
258+ }
259+
260+ fn fetch_file(
261+ &self,
262+ attachment: &Attachment,
263+ cx: &mut Context<Self>,
264+ ) -> Task<Result<PathBuf, common::error::Error>> {
265+ let network = self.network.clone();
266+ let attachment = attachment.clone();
267+ cx.spawn(async move |_, cx| {
268+ let path = cache_path(&attachment).ok_or(common::error::Error::Server)?;
269+ if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) {
270+ return Ok(path);
271+ }
272+ let bytes = network.download_attachment(&attachment.id, false).await?;
273+ cx.background_executor()
274+ .spawn({
275+ let path = path.clone();
276+ async move { std::fs::write(&path, bytes) }
277+ })
278+ .await
279+ .map_err(|_| common::error::Error::Server)?;
280+ Ok(path)
281+ })
282+ }
283+
284+ fn open_attachment(
285+ &self,
286+ attachment: &Attachment,
287+ window: &mut Window,
288+ cx: &mut Context<Self>,
289+ ) {
290+ let fetched = self.fetch_file(attachment, cx);
291+ cx.spawn_in(window, async move |this, cx| match fetched.await {
292+ Ok(path) => {
293+ let _ = this.update(cx, |_, cx| cx.open_with_system(&path));
294+ }
295+ Err(error) => notify_error(&this, cx, error),
296+ })
297+ .detach();
298+ }
299+
300+ fn save_attachment(
301+ &self,
302+ attachment: &Attachment,
303+ window: &mut Window,
304+ cx: &mut Context<Self>,
305+ ) {
306+ let directory = dirs::download_dir().unwrap_or_else(std::env::temp_dir);
307+ let target = cx.prompt_for_new_path(&directory, Some(&attachment.name));
308+ let fetched = self.fetch_file(attachment, cx);
309+ cx.spawn_in(window, async move |this, cx| {
310+ let Ok(Ok(Some(target))) = target.await else {
311+ return;
312+ };
313+ match fetched.await {
314+ Ok(path) => {
315+ let _ = std::fs::copy(path, target);
316+ }
317+ Err(error) => notify_error(&this, cx, error),
318+ }
319+ })
320+ .detach();
321+ }
322+
323+ fn play(&mut self, attachment: &Attachment, window: &mut Window, cx: &mut Context<Self>) {
324+ if let Some(playing) = &self.chat.media.playing
325+ && playing.attachment_id == attachment.id
326+ {
327+ if let PlayState::Ready { player, .. } = &playing.state {
328+ player.toggle();
329+ }
330+ cx.notify();
331+ return;
332+ }
333+ self.stop_playing(cx);
334+ self.chat.media.playing = Some(Playing {
335+ attachment_id: attachment.id.clone(),
336+ state: PlayState::Loading,
337+ });
338+ cx.notify();
339+
340+ let fetched = self.fetch_file(attachment, cx);
341+ let choice = self.settings.voice.choice.clone();
342+ let attachment_id = attachment.id.clone();
343+ cx.spawn_in(window, async move |this, cx| {
344+ let opened = match fetched.await {
345+ Ok(path) => cx
346+ .background_executor()
347+ .spawn(async move { Player::open(&path, choice) })
348+ .await
349+ .map_err(|error| error.to_string()),
350+ Err(error) => Err(error.to_string()),
351+ };
352+ let _ = this.update_in(cx, |yumush, window, cx| {
353+ let current = yumush
354+ .chat
355+ .media
356+ .playing
357+ .as_ref()
358+ .is_some_and(|playing| playing.attachment_id == attachment_id);
359+ if !current {
360+ return;
361+ }
362+ match opened {
363+ Ok(player) => yumush.start_player(attachment_id, player, window, cx),
364+ Err(error) => {
365+ yumush.chat.media.playing = None;
366+ window.push_notification(Notification::error(error), cx);
367+ }
368+ }
369+ cx.notify();
370+ });
371+ })
372+ .detach();
373+ }
374+
375+ fn start_player(
376+ &mut self,
377+ attachment_id: String,
378+ player: Player,
379+ window: &mut Window,
380+ cx: &mut Context<Self>,
381+ ) {
382+ let duration = player.info().duration.unwrap_or_default().as_secs_f32();
383+ let seek = cx.new(|_| {
384+ SliderState::new()
385+ .min(0.)
386+ .max(duration.max(0.1))
387+ .default_value(0.)
388+ });
389+ let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| {
390+ let SliderEvent::Release(value) = event else {
391+ return;
392+ };
393+ if let Some(Playing {
394+ state: PlayState::Ready { player, .. },
395+ ..
396+ }) = &yumush.chat.media.playing
397+ {
398+ player.seek(Duration::from_secs_f32(value.start().max(0.)));
399+ }
400+ cx.notify();
401+ });
402+ let tick = cx.spawn_in(window, async move |this, cx| {
403+ loop {
404+ cx.background_executor().timer(FRAME_TICK).await;
405+ if this
406+ .update_in(cx, |yumush, window, cx| yumush.tick_player(window, cx))
407+ .is_err()
408+ {
409+ break;
410+ }
411+ }
412+ });
413+ player.play();
414+ self.chat.media.playing = Some(Playing {
415+ attachment_id,
416+ state: PlayState::Ready {
417+ player,
418+ frame: None,
419+ generation: 0,
420+ seek,
421+ _subscription: subscription,
422+ _tick: tick,
423+ },
424+ });
425+ }
426+
427+ fn tick_player(&mut self, window: &mut Window, cx: &mut Context<Self>) {
428+ let Some(Playing {
429+ state:
430+ PlayState::Ready {
431+ player,
432+ frame,
433+ generation,
434+ seek,
435+ ..
436+ },
437+ ..
438+ }) = &mut self.chat.media.playing
439+ else {
440+ return;
441+ };
442+ if !player.playing() {
443+ return;
444+ }
445+ if let Some(next) = player.frame()
446+ && next.generation != *generation
447+ {
448+ *generation = next.generation;
449+ if let Some(old) = std::mem::replace(frame, to_render_image(&next)) {
450+ cx.drop_image(old, Some(window));
451+ }
452+ }
453+ let position = player.position().as_secs_f32();
454+ seek.update(cx, |state, cx| state.set_value(position, window, cx));
455+ cx.notify();
456+ }
457+
458+ pub(super) fn stop_playing(&mut self, cx: &mut Context<Self>) {
459+ if let Some(Playing {
460+ state: PlayState::Ready {
461+ frame: Some(frame), ..
462+ },
463+ ..
464+ }) = self.chat.media.playing.take()
465+ {
466+ cx.drop_image(frame, None);
467+ }
468+ }
469+}
470+
471+pub fn attachments(
472+ attachments: &[Attachment],
473+ media: &Media,
474+ entity: &Entity<Yumush>,
475+ palette: Palette,
476+) -> Option<impl IntoElement> {
477+ if attachments.is_empty() {
478+ return None;
479+ }
480+ Some(
481+ div().flex().flex_col().gap(px(6.)).children(
482+ attachments
483+ .iter()
484+ .map(|attachment| attachment_view(attachment, media, entity, palette)),
485+ ),
486+ )
487+}
488+
489+fn attachment_view(
490+ attachment: &Attachment,
491+ media: &Media,
492+ entity: &Entity<Yumush>,
493+ palette: Palette,
494+) -> gpui_kit::AnyElement {
495+ match attachment.kind {
496+ AttachmentKind::Image => image_view(attachment, media, entity, palette).into_any_element(),
497+ AttachmentKind::Video | AttachmentKind::Audio => {
498+ player_view(attachment, media, entity, palette).into_any_element()
499+ }
500+ AttachmentKind::File => file_view(attachment, entity, palette).into_any_element(),
501+ }
502+}
503+
504+fn on_attachment(
505+ entity: &Entity<Yumush>,
506+ attachment: &Attachment,
507+ action: fn(&mut Yumush, &Attachment, &mut Window, &mut Context<Yumush>),
508+) -> impl Fn(&mut Window, &mut App) + 'static {
509+ let entity = entity.clone();
510+ let attachment = attachment.clone();
511+ move |window, cx| {
512+ entity.update(cx, |yumush, cx| action(yumush, &attachment, window, cx));
513+ }
514+}
515+
516+fn image_view(
517+ attachment: &Attachment,
518+ media: &Media,
519+ entity: &Entity<Yumush>,
520+ palette: Palette,
521+) -> impl IntoElement {
522+ let (width, height) = fit(attachment.width, attachment.height, IMAGE_BOX);
523+ let open = on_attachment(entity, attachment, |yumush, attachment, window, cx| {
524+ yumush.open_attachment(attachment, window, cx)
525+ });
526+ div()
527+ .id(format!("attachment_{}", attachment.id))
528+ .w(px(width))
529+ .h(px(height))
530+ .rounded(px(8.))
531+ .overflow_hidden()
532+ .bg(palette.field)
533+ .cursor_pointer()
534+ .on_click(move |_, window, cx| open(window, cx))
535+ .children(
536+ media
537+ .thumbnails
538+ .get(&attachment.id)
539+ .map(|image| img(image.clone()).size_full()),
540+ )
541+}
542+
543+fn card(palette: Palette) -> gpui_kit::Div {
544+ div()
545+ .max_w(px(VIDEO_BOX.0))
546+ .flex()
547+ .items_center()
548+ .gap(px(10.))
549+ .px(px(12.))
550+ .py(px(10.))
551+ .rounded(px(8.))
552+ .border_1()
553+ .border_color(palette.border)
554+ .bg(palette.panel)
555+}
556+
557+fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl IntoElement {
558+ div()
559+ .flex_1()
560+ .min_w_0()
561+ .flex()
562+ .flex_col()
563+ .child(
564+ div()
565+ .truncate()
566+ .text_color(palette.text)
567+ .child(attachment.name.clone()),
568+ )
569+ .child(
570+ div()
571+ .text_size(px(12.))
572+ .text_color(palette.muted)
573+ .child(detail),
574+ )
575+}
576+
577+fn icon_button(
578+ id: String,
579+ icon: IconName,
580+ tip: &'static str,
581+ palette: Palette,
582+ on_click: impl Fn(&mut Window, &mut App) + 'static,
583+) -> impl IntoElement {
584+ clickable(id, palette, on_click)
585+ .tip(tip)
586+ .size(px(32.))
587+ .flex_shrink_0()
588+ .flex()
589+ .items_center()
590+ .justify_center()
591+ .rounded(px(6.))
592+ .text_color(palette.text)
593+ .child(Icon::new(icon).w(px(16.)).h(px(16.)))
594+}
595+
596+fn file_view(
597+ attachment: &Attachment,
598+ entity: &Entity<Yumush>,
599+ palette: Palette,
600+) -> impl IntoElement {
601+ card(palette)
602+ .child(
603+ Icon::new(IconName::File)
604+ .w(px(20.))
605+ .h(px(20.))
606+ .text_color(palette.muted),
607+ )
608+ .child(name_block(attachment, size_text(attachment.size), palette))
609+ .child(icon_button(
610+ format!("save_{}", attachment.id),
611+ IconName::ArrowDown,
612+ "Save",
613+ palette,
614+ on_attachment(entity, attachment, |yumush, attachment, window, cx| {
615+ yumush.save_attachment(attachment, window, cx)
616+ }),
617+ ))
618+}
619+
620+fn player_view(
621+ attachment: &Attachment,
622+ media: &Media,
623+ entity: &Entity<Yumush>,
624+ palette: Palette,
625+) -> impl IntoElement {
626+ let state = media
627+ .playing
628+ .as_ref()
629+ .filter(|playing| playing.attachment_id == attachment.id)
630+ .map(|playing| &playing.state);
631+ let playing = matches!(state, Some(PlayState::Ready { player, .. }) if player.playing());
632+ let toggle = icon_button(
633+ format!("play_{}", attachment.id),
634+ if playing {
635+ IconName::Pause
636+ } else {
637+ IconName::Play
638+ },
639+ if playing { "Pause" } else { "Play" },
640+ palette,
641+ on_attachment(entity, attachment, |yumush, attachment, window, cx| {
642+ yumush.play(attachment, window, cx)
643+ }),
644+ );
645+ let detail = match state {
646+ Some(PlayState::Loading) => "…".to_string(),
647+ Some(PlayState::Ready { player, .. }) => format!(
648+ "{} / {}",
649+ time_text(player.position()),
650+ time_text(player.info().duration.unwrap_or_default())
651+ ),
652+ None => size_text(attachment.size),
653+ };
654+ let controls = card(palette)
655+ .child(toggle)
656+ .child(name_block(attachment, detail, palette))
657+ .when_some(
658+ match state {
659+ Some(PlayState::Ready { seek, .. }) => Some(seek),
660+ _ => None,
661+ },
662+ |this, seek| this.child(div().w(px(140.)).child(Slider::new(seek))),
663+ );
664+
665+ let video = match state {
666+ Some(PlayState::Ready { player, frame, .. }) => player
667+ .info()
668+ .video
669+ .map(|(width, height)| (frame, width, height)),
670+ _ => None,
671+ };
672+
673+ div()
674+ .flex()
675+ .flex_col()
676+ .gap(px(4.))
677+ .when_some(video, |this, (frame, width, height)| {
678+ let (width, height) = fit(Some(width), Some(height), VIDEO_BOX);
679+ this.child(
680+ div()
681+ .w(px(width))
682+ .h(px(height))
683+ .rounded(px(8.))
684+ .overflow_hidden()
685+ .bg(gpui_kit::black())
686+ .children(frame.clone().map(|frame| img(frame).size_full())),
687+ )
688+ })
689+ .child(controls)
690+}
691+
692+pub fn embeds(message: &Message, media: &Media, palette: Palette) -> Vec<impl IntoElement> {
693+ embed::urls(&message.body)
694+ .into_iter()
695+ .filter_map(|url| media.embeds.get(&url))
696+ .map(|loaded| embed_view(loaded, palette))
697+ .collect()
698+}
699+
700+fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement {
701+ let embed = &loaded.embed;
702+ let url = embed.url.clone();
703+ let image = loaded.image.clone().map(|image| {
704+ div()
705+ .max_w(px(EMBED_IMAGE_BOX.0))
706+ .max_h(px(EMBED_IMAGE_BOX.1))
707+ .rounded(px(6.))
708+ .overflow_hidden()
709+ .child(
710+ img(image)
711+ .max_w(px(EMBED_IMAGE_BOX.0))
712+ .max_h(px(EMBED_IMAGE_BOX.1)),
713+ )
714+ });
715+
716+ if embed.kind == EmbedKind::Image {
717+ return div().children(image);
718+ }
719+
720+ div()
721+ .max_w(px(VIDEO_BOX.0))
722+ .flex()
723+ .flex_col()
724+ .gap(px(4.))
725+ .pl(px(12.))
726+ .pr(px(12.))
727+ .py(px(10.))
728+ .rounded(px(6.))
729+ .border_l_2()
730+ .border_color(palette.border)
731+ .bg(palette.panel)
732+ .children(embed.site.clone().map(|site| {
733+ div()
734+ .text_size(px(12.))
735+ .text_color(palette.muted)
736+ .child(site)
737+ }))
738+ .children(embed.title.clone().map(|title| {
739+ div()
740+ .id(format!("embed_{url}"))
741+ .font_weight(FontWeight::SEMIBOLD)
742+ .text_color(palette.text)
743+ .cursor_pointer()
744+ .hover(|style| style.underline())
745+ .on_click(move |_, _, cx| cx.open_url(&url))
746+ .child(title)
747+ }))
748+ .children(embed.description.clone().map(|description| {
749+ div()
750+ .text_size(px(13.))
751+ .text_color(palette.body)
752+ .line_clamp(3)
753+ .child(description)
754+ }))
755+ .children(image)
756+}
757+
758+pub fn pending_row(
759+ media: &Media,
760+ entity: &Entity<Yumush>,
761+ palette: Palette,
762+) -> Option<impl IntoElement> {
763+ if media.pending.is_empty() && !media.uploading() {
764+ return None;
765+ }
766+ Some(
767+ div()
768+ .flex()
769+ .flex_wrap()
770+ .gap(px(6.))
771+ .pb(px(8.))
772+ .children(media.pending.iter().map(|attachment| {
773+ let entity = entity.clone();
774+ let attachment_id = attachment.id.clone();
775+ div()
776+ .flex()
777+ .items_center()
778+ .gap(px(6.))
779+ .pl(px(10.))
780+ .pr(px(4.))
781+ .py(px(4.))
782+ .rounded(px(6.))
783+ .bg(palette.hover)
784+ .text_size(px(12.))
785+ .child(
786+ div()
787+ .max_w(px(180.))
788+ .truncate()
789+ .child(attachment.name.clone()),
790+ )
791+ .child(
792+ clickable(
793+ format!("unattach_{}", attachment.id),
794+ palette,
795+ move |_, cx| {
796+ entity.update(cx, |yumush, cx| {
797+ yumush.remove_pending(&attachment_id, cx)
798+ })
799+ },
800+ )
801+ .tip("Remove")
802+ .size(px(18.))
803+ .flex()
804+ .items_center()
805+ .justify_center()
806+ .rounded(px(4.))
807+ .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))),
808+ )
809+ }))
810+ .when(media.uploading(), |this| {
811+ this.child(
812+ div()
813+ .px(px(10.))
814+ .py(px(4.))
815+ .text_size(px(12.))
816+ .text_color(palette.muted)
817+ .child("…"),
818+ )
819+ }),
820+ )
821+}
crates/client/src/gui/message_actions.rsadded+170 -0
@@ -0,0 +1,170 @@
1+use common::model::{Message, User};
2+use gpui_kit::{
3+ Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window,
4+ assets::IconName, component::Icon, div, px,
5+};
6+
7+use super::{Palette, Tooltip as _, Yumush, avatar, chat::Chat, clickable};
8+
9+pub fn quote_text(body: &str, attachments: usize) -> String {
10+ if body.is_empty() {
11+ format!("{attachments} attachments")
12+ } else {
13+ body.to_string()
14+ }
15+}
16+
17+pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<impl IntoElement> {
18+ let quote = message.reply.as_ref()?;
19+ let author = chat.author(&quote.user_id);
20+
21+ Some(
22+ div()
23+ .flex()
24+ .items_center()
25+ .gap(px(6.))
26+ .pl(px(8.))
27+ .border_l_2()
28+ .border_color(palette.accent.opacity(0.6))
29+ .text_size(px(12.))
30+ .text_color(palette.muted)
31+ .children(author.map(|user| avatar(palette, user, px(14.), px(7.), &chat.avatars)))
32+ .children(author.map(|user| {
33+ div()
34+ .flex_shrink_0()
35+ .font_weight(FontWeight::SEMIBOLD)
36+ .text_color(palette.tinted(&user.id))
37+ .child(user.username.clone())
38+ }))
39+ .child(
40+ div()
41+ .flex_1()
42+ .min_w_0()
43+ .truncate()
44+ .child(quote_text(&quote.body, quote.attachments)),
45+ ),
46+ )
47+}
48+
49+pub fn selection_mark(selected: bool, palette: Palette) -> impl IntoElement {
50+ div()
51+ .mt(px(3.))
52+ .size(px(16.))
53+ .flex_shrink_0()
54+ .flex()
55+ .items_center()
56+ .justify_center()
57+ .rounded_full()
58+ .border_1()
59+ .border_color(if selected {
60+ palette.accent
61+ } else {
62+ palette.muted
63+ })
64+ .bg(if selected {
65+ palette.accent
66+ } else {
67+ palette.field
68+ })
69+ .children(selected.then(|| {
70+ Icon::new(IconName::Check)
71+ .w(px(10.))
72+ .h(px(10.))
73+ .text_color(palette.on_accent)
74+ }))
75+}
76+
77+pub fn actions(
78+ message: &Message,
79+ chat: &Chat,
80+ me: Option<&User>,
81+ entity: &Entity<Yumush>,
82+ palette: Palette,
83+ group: String,
84+) -> impl IntoElement {
85+ let mine = me.is_some_and(|me| me.id == message.user_id);
86+ let editable = mine && !message.body.is_empty() && message.snippet.is_none();
87+ let deletable = me.is_some_and(|me| chat.can_delete(message, me));
88+ let id = message.id.as_str();
89+
90+ div()
91+ .flex()
92+ .items_center()
93+ .gap(px(2.))
94+ .p(px(2.))
95+ .rounded(px(8.))
96+ .border_1()
97+ .border_color(palette.border)
98+ .bg(palette.panel)
99+ .invisible()
100+ .group_hover(group, |style| style.visible())
101+ .child(action(
102+ entity,
103+ palette,
104+ id,
105+ "Reply",
106+ IconName::Reply,
107+ |yumush, id, window, cx| yumush.reply(id, window, cx),
108+ ))
109+ .children(editable.then(|| {
110+ action(
111+ entity,
112+ palette,
113+ id,
114+ "Edit",
115+ IconName::Pencil,
116+ |yumush, id, window, cx| yumush.edit(id, window, cx),
117+ )
118+ }))
119+ .child(action(
120+ entity,
121+ palette,
122+ id,
123+ "Forward",
124+ IconName::Forward,
125+ |yumush, id, window, cx| yumush.open_forward(vec![id], window, cx),
126+ ))
127+ .child(action(
128+ entity,
129+ palette,
130+ id,
131+ "Select",
132+ IconName::ListChecks,
133+ |yumush, id, window, cx| yumush.start_select(id, window, cx),
134+ ))
135+ .children(deletable.then(|| {
136+ action(
137+ entity,
138+ palette,
139+ id,
140+ "Delete",
141+ IconName::Trash,
142+ |yumush, id, window, cx| yumush.delete_message(&id, window, cx),
143+ )
144+ }))
145+}
146+
147+fn action(
148+ entity: &Entity<Yumush>,
149+ palette: Palette,
150+ message_id: &str,
151+ tip: &'static str,
152+ icon: IconName,
153+ run: fn(&mut Yumush, String, &mut Window, &mut Context<Yumush>),
154+) -> impl IntoElement {
155+ let entity = entity.clone();
156+ let message_id = message_id.to_string();
157+
158+ clickable(format!("{tip}_{message_id}"), palette, move |window, cx| {
159+ let message_id = message_id.clone();
160+ entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx));
161+ })
162+ .tip(tip)
163+ .size(px(24.))
164+ .flex()
165+ .items_center()
166+ .justify_center()
167+ .rounded(px(6.))
168+ .text_color(palette.muted)
169+ .child(Icon::new(icon).w(px(14.)).h(px(14.)))
170+}
crates/client/src/gui/profile.rsadded+506 -0
@@ -0,0 +1,506 @@
1+use std::{collections::HashMap, sync::Arc};
2+
3+use common::{
4+ model::{Rank, User},
5+ permission,
6+};
7+use gpui_kit::{
8+ Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, IntoElement,
9+ ParentElement, SharedString, Styled, Window,
10+ assets::IconName,
11+ component::{
12+ Icon, WindowExt,
13+ popover::{Popover, PopoverState},
14+ },
15+ div, px,
16+};
17+
18+use super::chat::View;
19+use super::social::Relation;
20+use super::{
21+ Palette, Trigger, Yumush, avatar, clickable, id_time, input_dialog, palette, rank_tag,
22+};
23+
24+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25+enum Removal {
26+ Kick,
27+ Ban,
28+}
29+
30+impl Removal {
31+ fn title(self) -> &'static str {
32+ match self {
33+ Removal::Kick => "Kick",
34+ Removal::Ban => "Ban",
35+ }
36+ }
37+}
38+
39+pub(super) fn profile_popover(
40+ id: impl Into<ElementId>,
41+ anchor: Anchor,
42+ user: &User,
43+ entity: &Entity<Yumush>,
44+ trigger: impl IntoElement,
45+) -> Popover {
46+ let user = user.clone();
47+ let entity = entity.clone();
48+ let notify_entity = entity.clone();
49+
50+ Popover::new(id)
51+ .anchor(anchor)
52+ .appearance(false)
53+ .on_open_change(move |_, _, cx| notify_entity.update(cx, |_, cx| cx.notify()))
54+ .trigger(Trigger::new(trigger))
55+ .content(move |_, _, cx| {
56+ let yumush = entity.read(cx);
57+ let card = Card {
58+ viewer: yumush.user.clone(),
59+ actor: yumush.actor_rank(),
60+ target: yumush.chat.rank_of(&user),
61+ relation: yumush.relation(&user.id),
62+ confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()),
63+ others: yumush
64+ .accounts
65+ .others()
66+ .map(|account| (account.user_id.clone(), account.username.clone()))
67+ .collect(),
68+ user: user.clone(),
69+ };
70+
71+ card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars)
72+ })
73+}
74+
75+struct Card {
76+ user: User,
77+ viewer: Option<User>,
78+ actor: Option<Rank>,
79+ target: Option<Rank>,
80+ relation: Relation,
81+ confirming: bool,
82+ others: Vec<(String, String)>,
83+}
84+
85+impl Card {
86+ fn social_rows(
87+ &self,
88+ entity: &Entity<Yumush>,
89+ popover: &Entity<PopoverState>,
90+ palette: Palette,
91+ ) -> Vec<AnyElement> {
92+ let user_id = self.user.id.clone();
93+ let message_id = user_id.clone();
94+ let mut rows = vec![
95+ menu_row(
96+ "profile_message",
97+ "Message",
98+ IconName::MessageSquare,
99+ palette.text,
100+ palette,
101+ yumush_action(entity, popover, move |yumush, window, cx| {
102+ yumush.open_direct(message_id.clone(), window, cx)
103+ }),
104+ )
105+ .into_any_element(),
106+ ];
107+
108+ if let Some((label, icon)) = self.relation.action() {
109+ let relation = self.relation;
110+ rows.push(
111+ menu_row(
112+ "profile_friend",
113+ label,
114+ icon,
115+ palette.text,
116+ palette,
117+ yumush_action(entity, popover, move |yumush, window, cx| {
118+ yumush.friend_action(relation, user_id.clone(), window, cx)
119+ }),
120+ )
121+ .into_any_element(),
122+ );
123+ }
124+
125+ rows
126+ }
127+
128+ fn render(
129+ self,
130+ entity: &Entity<Yumush>,
131+ popover: Entity<PopoverState>,
132+ palette: Palette,
133+ avatars: &HashMap<String, Arc<Image>>,
134+ ) -> Div {
135+ let is_self = self
136+ .viewer
137+ .as_ref()
138+ .is_some_and(|viewer| viewer.id == self.user.id);
139+ let rows = if is_self {
140+ self_rows(&self.others, entity, &popover, palette)
141+ } else {
142+ let mut rows = self.social_rows(entity, &popover, palette);
143+ rows.extend(self.moderation_rows(entity, &popover, palette));
144+ rows
145+ };
146+ let divider = (!rows.is_empty()).then(|| div().h(px(1.)).my(px(4.)).bg(palette.border));
147+
148+ div()
149+ .w(px(260.))
150+ .p(px(16.))
151+ .flex()
152+ .flex_col()
153+ .gap(px(10.))
154+ .rounded(px(8.))
155+ .border_1()
156+ .border_color(palette.border)
157+ .bg(palette.panel)
158+ .child(avatar(palette, &self.user, px(48.), px(18.), avatars))
159+ .child(
160+ div()
161+ .flex()
162+ .items_center()
163+ .gap(px(6.))
164+ .child(
165+ div()
166+ .text_size(px(15.))
167+ .font_weight(FontWeight::SEMIBOLD)
168+ .child(self.user.username.clone()),
169+ )
170+ .children(rank_tag(self.target, palette)),
171+ )
172+ .children((!self.user.status.is_empty()).then(|| {
173+ div()
174+ .text_size(px(12.))
175+ .text_color(palette.muted)
176+ .child(self.user.status.clone())
177+ }))
178+ .child(
179+ div()
180+ .text_size(px(12.))
181+ .text_color(palette.muted)
182+ .child(format!("Joined {}", id_time(&self.user.id, "%b %-d, %Y"))),
183+ )
184+ .children(divider)
185+ .children(rows)
186+ }
187+
188+ fn moderation_rows(
189+ &self,
190+ entity: &Entity<Yumush>,
191+ popover: &Entity<PopoverState>,
192+ palette: Palette,
193+ ) -> Vec<AnyElement> {
194+ let actor = self.actor;
195+ let target = self.target;
196+ let user_id = self.user.id.clone();
197+ let mut rows = Vec::new();
198+
199+ for (rank, label) in [
200+ (Rank::Member, "Make member"),
201+ (Rank::Moderator, "Make moderator"),
202+ (Rank::Admin, "Make admin"),
203+ ] {
204+ if target != Some(rank) && permission::can_set_rank(actor, target, rank) {
205+ let user_id = user_id.clone();
206+ rows.push(
207+ menu_row(
208+ label,
209+ label,
210+ IconName::Shield,
211+ palette.text,
212+ palette,
213+ yumush_action(entity, popover, move |yumush, window, cx| {
214+ yumush.set_member_rank(&user_id, rank, window, cx)
215+ }),
216+ )
217+ .into_any_element(),
218+ );
219+ }
220+ }
221+
222+ if permission::can_moderate(actor, target) {
223+ let kick_id = user_id.clone();
224+ let ban_id = user_id.clone();
225+ rows.push(
226+ menu_row(
227+ "kick",
228+ "Kick",
229+ IconName::Close,
230+ palette.danger,
231+ palette,
232+ yumush_action(entity, popover, move |yumush, window, cx| {
233+ yumush.open_removal(kick_id.clone(), Removal::Kick, window, cx)
234+ }),
235+ )
236+ .into_any_element(),
237+ );
238+ rows.push(
239+ menu_row(
240+ "ban",
241+ "Ban",
242+ IconName::Ban,
243+ palette.danger,
244+ palette,
245+ yumush_action(entity, popover, move |yumush, window, cx| {
246+ yumush.open_removal(ban_id.clone(), Removal::Ban, window, cx)
247+ }),
248+ )
249+ .into_any_element(),
250+ );
251+ }
252+
253+ let deletable = self
254+ .viewer
255+ .as_ref()
256+ .is_some_and(|viewer| permission::can_delete_user(viewer.role, false, self.user.role));
257+ if deletable {
258+ let label = if self.confirming {
259+ "Confirm"
260+ } else {
261+ "Delete user"
262+ };
263+
264+ rows.push(
265+ menu_row(
266+ "delete_user",
267+ label,
268+ IconName::Trash,
269+ palette.danger,
270+ palette,
271+ delete_user_action(&user_id, self.confirming, entity, popover),
272+ )
273+ .into_any_element(),
274+ );
275+ }
276+
277+ rows
278+ }
279+}
280+
281+fn self_rows(
282+ others: &[(String, String)],
283+ entity: &Entity<Yumush>,
284+ popover: &Entity<PopoverState>,
285+ palette: Palette,
286+) -> Vec<AnyElement> {
287+ let mut rows: Vec<AnyElement> = others
288+ .iter()
289+ .map(|(user_id, username)| {
290+ let user_id = user_id.clone();
291+ menu_row(
292+ format!("switch_{user_id}"),
293+ username.clone(),
294+ IconName::ArrowLeft,
295+ palette.text,
296+ palette,
297+ yumush_action(entity, popover, move |yumush, window, cx| {
298+ yumush.switch_account(user_id.clone(), window, cx)
299+ }),
300+ )
301+ .into_any_element()
302+ })
303+ .collect();
304+ rows.push(
305+ menu_row(
306+ "profile_add_account",
307+ "Add account",
308+ IconName::UserPlus,
309+ palette.text,
310+ palette,
311+ yumush_action(entity, popover, |yumush, window, cx| {
312+ yumush.add_account(window, cx)
313+ }),
314+ )
315+ .into_any_element(),
316+ );
317+ rows.extend([
318+ menu_row(
319+ "profile_settings",
320+ "Settings",
321+ IconName::Settings,
322+ palette.text,
323+ palette,
324+ yumush_action(entity, popover, |yumush, window, cx| {
325+ yumush.show_view(View::Settings, window, cx)
326+ }),
327+ )
328+ .into_any_element(),
329+ menu_row(
330+ "profile_logout",
331+ "Log out",
332+ IconName::LogOut,
333+ palette.danger,
334+ palette,
335+ yumush_action(entity, popover, |yumush, window, cx| {
336+ yumush.logout(window, cx)
337+ }),
338+ )
339+ .into_any_element(),
340+ ]);
341+ rows
342+}
343+
344+fn yumush_action(
345+ entity: &Entity<Yumush>,
346+ popover: &Entity<PopoverState>,
347+ run: impl Fn(&mut Yumush, &mut Window, &mut Context<Yumush>) + 'static,
348+) -> impl Fn(&mut Window, &mut App) + 'static {
349+ let entity = entity.clone();
350+ let popover = popover.clone();
351+
352+ move |window, cx| {
353+ popover.update(cx, |state, cx| state.dismiss(window, cx));
354+ entity.update(cx, |yumush, cx| run(yumush, window, cx));
355+ }
356+}
357+
358+fn delete_user_action(
359+ user_id: &str,
360+ confirming: bool,
361+ entity: &Entity<Yumush>,
362+ popover: &Entity<PopoverState>,
363+) -> impl Fn(&mut Window, &mut App) + 'static {
364+ let user_id = user_id.to_string();
365+ let entity = entity.clone();
366+ let popover = popover.clone();
367+
368+ move |window, cx| {
369+ if confirming {
370+ popover.update(cx, |state, cx| state.dismiss(window, cx));
371+ entity.update(cx, |yumush, cx| {
372+ yumush.delete_member_account(&user_id, window, cx)
373+ });
374+ } else {
375+ entity.update(cx, |yumush, cx| yumush.request_member_delete(&user_id, cx));
376+ }
377+ }
378+}
379+
380+fn menu_row(
381+ id: impl Into<ElementId>,
382+ label: impl Into<SharedString>,
383+ icon: IconName,
384+ color: Hsla,
385+ palette: Palette,
386+ on_click: impl Fn(&mut Window, &mut App) + 'static,
387+) -> impl IntoElement {
388+ clickable(id, palette, on_click)
389+ .h(px(30.))
390+ .px(px(8.))
391+ .flex()
392+ .items_center()
393+ .gap(px(8.))
394+ .rounded(px(6.))
395+ .text_color(color)
396+ .child(Icon::new(icon).w(px(14.)).h(px(14.)))
397+ .child(label.into())
398+}
399+
400+impl Yumush {
401+ fn open_removal(
402+ &self,
403+ user_id: String,
404+ removal: Removal,
405+ window: &mut Window,
406+ cx: &mut Context<Self>,
407+ ) {
408+ let Some(community_id) = self.chat.selected_community_id.clone() else {
409+ return;
410+ };
411+ input_dialog(
412+ removal.title(),
413+ removal.title(),
414+ "Reason (optional)",
415+ window,
416+ cx,
417+ move |this, text, window, cx| {
418+ let reason = text.trim().to_string();
419+ let reason = (!reason.is_empty()).then_some(reason);
420+ this.remove_member(&community_id, &user_id, removal, reason, window, cx);
421+ },
422+ );
423+ }
424+
425+ fn remove_member(
426+ &self,
427+ community_id: &str,
428+ user_id: &str,
429+ removal: Removal,
430+ reason: Option<String>,
431+ window: &mut Window,
432+ cx: &mut Context<Self>,
433+ ) {
434+ let network = self.network.clone();
435+ let community_id = community_id.to_string();
436+ let user_id = user_id.to_string();
437+
438+ cx.spawn_in(window, async move |this, cx| {
439+ let reason = reason.as_deref();
440+ let result = match removal {
441+ Removal::Kick => network.kick(&community_id, &user_id, reason).await,
442+ Removal::Ban => network.ban(&community_id, &user_id, reason).await,
443+ };
444+ match result {
445+ Ok(()) => {
446+ let _ = this.update_in(cx, |yumush, window, cx| {
447+ window.close_dialog(cx);
448+ yumush.load_bans(window, cx);
449+ });
450+ }
451+ Err(error) => super::notify_error(&this, cx, error),
452+ }
453+ })
454+ .detach();
455+ }
456+
457+ pub(super) fn set_member_rank(
458+ &self,
459+ user_id: &str,
460+ rank: Rank,
461+ window: &mut Window,
462+ cx: &mut Context<Self>,
463+ ) {
464+ let Some(community_id) = self.chat.selected_community_id.clone() else {
465+ return;
466+ };
467+ let network = self.network.clone();
468+ let user_id = user_id.to_string();
469+
470+ cx.spawn_in(window, async move |this, cx| {
471+ if let Err(error) = network.set_rank(&community_id, &user_id, rank).await {
472+ super::notify_error(&this, cx, error);
473+ }
474+ })
475+ .detach();
476+ }
477+
478+ pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context<Self>) {
479+ self.chat.pending_user_delete = Some(user_id.to_string());
480+ cx.notify();
481+ }
482+
483+ pub(super) fn delete_member_account(
484+ &mut self,
485+ user_id: &str,
486+ window: &mut Window,
487+ cx: &mut Context<Self>,
488+ ) {
489+ self.chat.pending_user_delete = None;
490+ let network = self.network.clone();
491+ let user_id = user_id.to_string();
492+
493+ cx.spawn_in(window, async move |this, cx| {
494+ match network.delete_user(&user_id).await {
495+ Ok(()) => {
496+ let _ = this.update(cx, |yumush, cx| {
497+ yumush.chat.remove_member(&user_id);
498+ cx.notify();
499+ });
500+ }
501+ Err(error) => super::notify_error(&this, cx, error),
502+ }
503+ })
504+ .detach();
505+ }
506+}
crates/client/src/gui/settings_page.rsadded+588 -0
@@ -0,0 +1,588 @@
1+use std::path::Path;
2+
3+use common::{error::Error, model::User};
4+use gpui_kit::{
5+ AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement,
6+ ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window,
7+ assets::IconName,
8+ component::{Icon, input::InputState},
9+ div,
10+ prelude::FluentBuilder as _,
11+ px,
12+};
13+
14+use super::{
15+ Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable,
16+ notify_error, primary_button,
17+};
18+use crate::settings::{self, ThemeChoice};
19+
20+const THEMES: [(ThemeChoice, &str); 4] = [
21+ (ThemeChoice::System, "System"),
22+ (ThemeChoice::Light, "Light"),
23+ (ThemeChoice::Dark, "Dark"),
24+ (ThemeChoice::Black, "Black"),
25+];
26+
27+impl Yumush {
28+ pub(super) fn settings_page(
29+ &self,
30+ entity: &Entity<Self>,
31+ palette: Palette,
32+ cx: &App,
33+ ) -> impl IntoElement {
34+ let mut sections = Vec::new();
35+ if let Some(user) = self.user.as_ref() {
36+ sections.push(
37+ picture_card(
38+ Picture {
39+ id: "avatar_picker",
40+ image: avatar(palette, user, px(64.), px(24.), &self.chat.avatars),
41+ title: user.username.clone(),
42+ subtitle: user.status.clone(),
43+ removable: user.avatar_id.is_some(),
44+ upload: Yumush::upload_avatar,
45+ remove: Yumush::remove_avatar,
46+ },
47+ entity,
48+ palette,
49+ )
50+ .into_any_element(),
51+ );
52+ sections.push(
53+ section(
54+ "Account",
55+ palette,
56+ vec![
57+ text_row(
58+ Editable {
59+ id: "save_username_button",
60+ label: "Username",
61+ input: &self.chat.username_input,
62+ current: &user.username,
63+ save: Yumush::save_username,
64+ },
65+ entity,
66+ palette,
67+ cx,
68+ ),
69+ text_row(
70+ Editable {
71+ id: "save_status_button",
72+ label: "Status",
73+ input: &self.chat.status_input,
74+ current: &user.status,
75+ save: Yumush::save_status,
76+ },
77+ entity,
78+ palette,
79+ cx,
80+ ),
81+ ],
82+ )
83+ .into_any_element(),
84+ );
85+ }
86+ sections.push(
87+ section("Voice", palette, self.voice_rows(entity, palette, cx)).into_any_element(),
88+ );
89+ sections.push(
90+ section(
91+ "Appearance",
92+ palette,
93+ vec![row(
94+ "Theme",
95+ segmented(
96+ THEMES,
97+ self.settings.theme,
98+ entity,
99+ palette,
100+ Yumush::set_theme,
101+ ),
102+ )],
103+ )
104+ .into_any_element(),
105+ );
106+ if self.user.is_some() {
107+ sections.push(
108+ danger_section(
109+ palette,
110+ vec![row(
111+ "Delete account",
112+ delete_control(
113+ "delete_account_button",
114+ self.chat.delete_step,
115+ entity,
116+ palette,
117+ Yumush::delete_account,
118+ ),
119+ )],
120+ )
121+ .into_any_element(),
122+ );
123+ }
124+
125+ page("settings_scroll", entity, palette, "Settings", sections)
126+ }
127+
128+ pub(super) fn set_user(&mut self, user: User, cx: &mut Context<Self>) {
129+ self.chat.update_member(&user);
130+ self.request_user_avatar(&user, cx);
131+ self.user = Some(user);
132+ cx.notify();
133+ }
134+
135+ pub(super) fn save_username(&mut self, window: &mut Window, cx: &mut Context<Self>) {
136+ let username = self.chat.username_input.read(cx).text().to_string();
137+ let network = self.network.clone();
138+
139+ cx.spawn_in(window, async move |this, cx| {
140+ match network.update_user(&username).await {
141+ Ok(user) => {
142+ let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
143+ }
144+ Err(error) => notify_error(&this, cx, error),
145+ }
146+ })
147+ .detach();
148+ }
149+
150+ pub(super) fn save_status(&mut self, window: &mut Window, cx: &mut Context<Self>) {
151+ let status = self.chat.status_input.read(cx).text().to_string();
152+ let network = self.network.clone();
153+
154+ cx.spawn_in(window, async move |this, cx| {
155+ match network.update_status(&status).await {
156+ Ok(user) => {
157+ let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
158+ }
159+ Err(error) => notify_error(&this, cx, error),
160+ }
161+ })
162+ .detach();
163+ }
164+
165+ pub(super) fn upload_avatar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
166+ let picked = cx.prompt_for_paths(PathPromptOptions {
167+ files: true,
168+ directories: false,
169+ multiple: false,
170+ prompt: None,
171+ });
172+ let network = self.network.clone();
173+
174+ cx.spawn_in(window, async move |this, cx| {
175+ let Ok(Ok(Some(paths))) = picked.await else {
176+ return;
177+ };
178+ let Some(path) = paths.into_iter().next() else {
179+ return;
180+ };
181+
182+ let prepared = cx
183+ .background_executor()
184+ .spawn(async move { read_avatar_file(&path) })
185+ .await;
186+ let result = match prepared {
187+ Ok(bytes) => network.update_avatar(bytes).await,
188+ Err(error) => Err(error),
189+ };
190+
191+ match result {
192+ Ok(user) => {
193+ let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
194+ }
195+ Err(error) => notify_error(&this, cx, error),
196+ }
197+ })
198+ .detach();
199+ }
200+
201+ pub(super) fn remove_avatar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
202+ let network = self.network.clone();
203+
204+ cx.spawn_in(window, async move |this, cx| {
205+ match network.remove_avatar().await {
206+ Ok(user) => {
207+ let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx));
208+ }
209+ Err(error) => notify_error(&this, cx, error),
210+ }
211+ })
212+ .detach();
213+ }
214+
215+ pub(super) fn delete_account(&mut self, window: &mut Window, cx: &mut Context<Self>) {
216+ match self.chat.delete_step {
217+ DeleteStep::Idle => {
218+ self.chat.delete_step = DeleteStep::Confirm;
219+ cx.notify();
220+ }
221+ DeleteStep::Confirm => {
222+ let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else {
223+ return;
224+ };
225+ let network = self.network.clone();
226+
227+ cx.spawn_in(window, async move |this, cx| {
228+ match network.delete_user(&user_id).await {
229+ Ok(()) => {
230+ let _ = this.update_in(cx, |yumush, window, cx| {
231+ yumush.end_session(window, cx);
232+ });
233+ }
234+ Err(error) => notify_error(&this, cx, error),
235+ }
236+ })
237+ .detach();
238+ }
239+ }
240+ }
241+
242+ pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context<Self>) {
243+ self.settings.theme = theme;
244+ settings::apply(theme, cx);
245+ self.commit_settings(cx);
246+ }
247+
248+ pub(super) fn commit_settings(&mut self, cx: &mut Context<Self>) {
249+ settings::save(&self.settings);
250+ self.network.set_voice_settings(self.settings.voice.clone());
251+ cx.notify();
252+ }
253+}
254+
255+pub(super) fn header(
256+ entity: &Entity<Yumush>,
257+ palette: Palette,
258+ title: impl IntoElement,
259+) -> impl IntoElement {
260+ let entity = entity.clone();
261+
262+ div()
263+ .h(px(44.))
264+ .px(px(12.))
265+ .flex()
266+ .items_center()
267+ .gap(px(8.))
268+ .border_b_1()
269+ .border_color(palette.border)
270+ .child(
271+ clickable("settings_back_button", palette, move |window, cx| {
272+ entity.update(cx, |yumush, cx| yumush.show_view(View::Chat, window, cx));
273+ })
274+ .tip("Back")
275+ .size(px(26.))
276+ .flex()
277+ .items_center()
278+ .justify_center()
279+ .rounded(px(6.))
280+ .text_color(palette.muted)
281+ .child(Icon::new(IconName::ArrowLeft).w(px(14.)).h(px(14.))),
282+ )
283+ .child(div().font_weight(FontWeight::SEMIBOLD).child(title))
284+}
285+
286+pub(super) fn page(
287+ id: &'static str,
288+ entity: &Entity<Yumush>,
289+ palette: Palette,
290+ title: impl IntoElement,
291+ sections: Vec<AnyElement>,
292+) -> impl IntoElement {
293+ div()
294+ .flex_1()
295+ .min_h_0()
296+ .flex()
297+ .flex_col()
298+ .child(header(entity, palette, title))
299+ .child(
300+ div()
301+ .id(id)
302+ .flex_1()
303+ .min_h_0()
304+ .overflow_y_scroll()
305+ .flex()
306+ .justify_center()
307+ .child(
308+ div()
309+ .w_full()
310+ .max_w(px(600.))
311+ .px(px(24.))
312+ .py(px(32.))
313+ .flex()
314+ .flex_col()
315+ .gap(px(28.))
316+ .children(sections),
317+ ),
318+ )
319+}
320+
321+pub(super) fn section(title: &'static str, palette: Palette, rows: Vec<Div>) -> impl IntoElement {
322+ card(title, palette.muted, palette.border, palette, rows)
323+}
324+
325+pub(super) fn danger_section(palette: Palette, rows: Vec<Div>) -> impl IntoElement {
326+ card(
327+ "Danger zone",
328+ palette.danger,
329+ palette.danger.opacity(0.35),
330+ palette,
331+ rows,
332+ )
333+}
334+
335+fn card(
336+ title: &'static str,
337+ title_color: Hsla,
338+ border: Hsla,
339+ palette: Palette,
340+ rows: Vec<Div>,
341+) -> impl IntoElement {
342+ div()
343+ .flex()
344+ .flex_col()
345+ .gap(px(8.))
346+ .child(
347+ div()
348+ .px(px(2.))
349+ .text_size(px(12.))
350+ .font_weight(FontWeight::MEDIUM)
351+ .text_color(title_color)
352+ .child(title),
353+ )
354+ .child(
355+ div()
356+ .flex()
357+ .flex_col()
358+ .rounded(px(10.))
359+ .border_1()
360+ .border_color(border)
361+ .bg(palette.panel)
362+ .children(rows.into_iter().enumerate().map(|(index, row)| {
363+ row.when(index > 0, |row| {
364+ row.border_t_1().border_color(palette.border)
365+ })
366+ })),
367+ )
368+}
369+
370+pub(super) struct Editable<'a> {
371+ pub id: &'static str,
372+ pub label: &'static str,
373+ pub input: &'a Entity<InputState>,
374+ pub current: &'a str,
375+ pub save: fn(&mut Yumush, &mut Window, &mut Context<Yumush>),
376+}
377+
378+pub(super) fn text_row(
379+ editable: Editable,
380+ entity: &Entity<Yumush>,
381+ palette: Palette,
382+ cx: &App,
383+) -> Div {
384+ let dirty = editable.input.read(cx).text() != editable.current;
385+ let entity = entity.clone();
386+ let save = editable.save;
387+
388+ div()
389+ .p(px(12.))
390+ .flex()
391+ .flex_col()
392+ .gap(px(6.))
393+ .child(
394+ div()
395+ .text_size(px(12.))
396+ .text_color(palette.muted)
397+ .child(editable.label),
398+ )
399+ .child(
400+ div()
401+ .flex()
402+ .items_center()
403+ .gap(px(8.))
404+ .child(field(palette, editable.input).flex_1())
405+ .when(dirty, |this| {
406+ this.child(
407+ primary_button(editable.id, palette, move |window, cx| {
408+ entity.update(cx, |yumush, cx| save(yumush, window, cx));
409+ })
410+ .h(px(32.))
411+ .px(px(14.))
412+ .flex()
413+ .items_center()
414+ .rounded(px(8.))
415+ .font_weight(FontWeight::MEDIUM)
416+ .child("Save"),
417+ )
418+ }),
419+ )
420+}
421+
422+pub(super) struct Picture {
423+ pub id: &'static str,
424+ pub image: Div,
425+ pub title: String,
426+ pub subtitle: String,
427+ pub removable: bool,
428+ pub upload: fn(&mut Yumush, &mut Window, &mut Context<Yumush>),
429+ pub remove: fn(&mut Yumush, &mut Window, &mut Context<Yumush>),
430+}
431+
432+pub(super) fn picture_card(picture: Picture, entity: &Entity<Yumush>, palette: Palette) -> Div {
433+ let Picture {
434+ id,
435+ image,
436+ title,
437+ subtitle,
438+ removable,
439+ upload,
440+ remove,
441+ } = picture;
442+ let picture_entity = entity.clone();
443+ let remove_entity = entity.clone();
444+
445+ div()
446+ .p(px(16.))
447+ .flex()
448+ .items_center()
449+ .gap(px(16.))
450+ .rounded(px(10.))
451+ .border_1()
452+ .border_color(palette.border)
453+ .bg(palette.panel)
454+ .child(
455+ div()
456+ .id(id)
457+ .cursor_pointer()
458+ .hover(|style| style.opacity(0.8))
459+ .on_click(move |_, window, cx| {
460+ picture_entity.update(cx, |yumush, cx| upload(yumush, window, cx));
461+ })
462+ .tip("Change picture")
463+ .child(image),
464+ )
465+ .child(
466+ div()
467+ .flex_1()
468+ .min_w_0()
469+ .flex()
470+ .flex_col()
471+ .gap(px(2.))
472+ .child(
473+ div()
474+ .text_size(px(16.))
475+ .font_weight(FontWeight::SEMIBOLD)
476+ .truncate()
477+ .child(title),
478+ )
479+ .when(!subtitle.is_empty(), |this| {
480+ this.child(
481+ div()
482+ .text_size(px(12.))
483+ .text_color(palette.muted)
484+ .truncate()
485+ .child(subtitle),
486+ )
487+ }),
488+ )
489+ .children(removable.then(|| {
490+ small_button(
491+ "remove_picture_button",
492+ palette,
493+ palette.danger,
494+ move |window, cx| {
495+ remove_entity.update(cx, |yumush, cx| remove(yumush, window, cx));
496+ },
497+ )
498+ .child("Remove")
499+ }))
500+}
501+
502+fn small_button(
503+ id: &'static str,
504+ palette: Palette,
505+ color: Hsla,
506+ on_click: impl Fn(&mut Window, &mut App) + 'static,
507+) -> Stateful<Div> {
508+ clickable(id, palette, on_click)
509+ .h(px(28.))
510+ .px(px(10.))
511+ .flex()
512+ .items_center()
513+ .rounded(px(6.))
514+ .text_size(px(13.))
515+ .text_color(color)
516+}
517+
518+pub(super) fn delete_control(
519+ id: &'static str,
520+ step: DeleteStep,
521+ entity: &Entity<Yumush>,
522+ palette: Palette,
523+ action: fn(&mut Yumush, &mut Window, &mut Context<Yumush>),
524+) -> impl IntoElement {
525+ let entity = entity.clone();
526+ let confirming = step == DeleteStep::Confirm;
527+
528+ small_button(id, palette, palette.danger, move |window, cx| {
529+ entity.update(cx, |yumush, cx| action(yumush, window, cx));
530+ })
531+ .border_1()
532+ .border_color(palette.danger.opacity(0.5))
533+ .when(confirming, |this| {
534+ this.bg(palette.danger).text_color(palette.on_accent)
535+ })
536+ .child(if confirming { "Confirm" } else { "Delete" })
537+}
538+
539+pub(super) fn read_avatar_file(path: &Path) -> Result<Vec<u8>, Error> {
540+ let bytes = std::fs::read(path)?;
541+
542+ crate::avatar::prepare(&bytes)
543+}
544+
545+pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div {
546+ div()
547+ .min_h(px(48.))
548+ .py(px(10.))
549+ .px(px(12.))
550+ .flex()
551+ .items_center()
552+ .justify_between()
553+ .child(label)
554+ .child(control)
555+}
556+
557+pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>(
558+ options: [(T, &'static str); N],
559+ selected: T,
560+ entity: &Entity<Yumush>,
561+ palette: Palette,
562+ select: fn(&mut Yumush, T, &mut Context<Yumush>),
563+) -> impl IntoElement {
564+ div()
565+ .h(px(28.))
566+ .p(px(2.))
567+ .flex()
568+ .gap(px(2.))
569+ .rounded(px(6.))
570+ .border_1()
571+ .border_color(palette.border)
572+ .bg(palette.field)
573+ .children(options.map(|(choice, label)| {
574+ let entity = entity.clone();
575+ let active = choice == selected;
576+
577+ clickable(label, palette, move |_, cx| {
578+ entity.update(cx, |yumush, cx| select(yumush, choice, cx));
579+ })
580+ .px(px(10.))
581+ .flex()
582+ .items_center()
583+ .rounded(px(4.))
584+ .text_color(if active { palette.text } else { palette.muted })
585+ .when(active, |this| this.bg(palette.hover))
586+ .child(label)
587+ }))
588+}
crates/client/src/gui/sidebar.rsadded+694 -0
@@ -0,0 +1,694 @@
1+use common::{
2+ model::{CommunityKind, Invitation, User},
3+ permission,
4+ validate::validate_community_name,
5+};
6+use gpui_kit::{
7+ Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement,
8+ ParentElement, StatefulInteractiveElement, Styled, Window,
9+ assets::IconName,
10+ component::{
11+ Icon,
12+ input::{Input, InputState},
13+ menu::{ContextMenuExt, PopupMenu, PopupMenuItem},
14+ },
15+ div,
16+ prelude::FluentBuilder as _,
17+ px,
18+};
19+
20+use super::{
21+ Palette, Tooltip as _, Yumush, avatar,
22+ chat::{View, create_community},
23+ clickable, community_icon, community_name, entity_action, hoverable, hoverable_with,
24+ input_dialog,
25+ profile::profile_popover,
26+ social::Relation,
27+};
28+
29+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30+pub enum SidebarTab {
31+ Messages,
32+ Communities,
33+}
34+
35+impl Yumush {
36+ pub(super) fn sidebar(
37+ &self,
38+ entity: &Entity<Self>,
39+ query: &str,
40+ palette: Palette,
41+ ) -> impl IntoElement {
42+ let (top, list) = match self.chat.tab {
43+ SidebarTab::Messages => (
44+ Some(input_box(&self.chat.search_input, palette)),
45+ self.messages_list(entity, query, palette)
46+ .into_any_element(),
47+ ),
48+ SidebarTab::Communities => (
49+ None,
50+ self.communities_list(entity, palette).into_any_element(),
51+ ),
52+ };
53+
54+ div()
55+ .h_full()
56+ .w(px(232.))
57+ .flex_shrink_0()
58+ .flex()
59+ .flex_col()
60+ .py(px(12.))
61+ .px(px(10.))
62+ .gap(px(14.))
63+ .child(
64+ div()
65+ .flex()
66+ .items_center()
67+ .child(self.tab_bar(entity, palette)),
68+ )
69+ .children(top)
70+ .child(
71+ div()
72+ .id("sidebar_list")
73+ .flex_1()
74+ .min_h_0()
75+ .overflow_y_scroll()
76+ .child(list),
77+ )
78+ .children(self.account_row(entity, palette))
79+ }
80+
81+ fn tab_bar(&self, entity: &Entity<Self>, palette: Palette) -> impl IntoElement {
82+ let requests = !self.chat.friends.incoming.is_empty() || !self.chat.invitations.is_empty();
83+ let tabs = [
84+ (
85+ SidebarTab::Communities,
86+ "Communities",
87+ self.chat.has_unread(false),
88+ ),
89+ (
90+ SidebarTab::Messages,
91+ "Messages",
92+ requests || self.chat.has_unread(true),
93+ ),
94+ ];
95+
96+ div()
97+ .flex_1()
98+ .h(px(28.))
99+ .p(px(2.))
100+ .flex()
101+ .gap(px(2.))
102+ .rounded(px(6.))
103+ .border_1()
104+ .border_color(palette.border)
105+ .bg(palette.field)
106+ .children(tabs.map(|(tab, label, alert)| {
107+ let active = self.chat.tab == tab;
108+
109+ let item = clickable(
110+ label,
111+ palette,
112+ entity_action(entity, move |yumush, window, cx| {
113+ yumush.set_sidebar_tab(tab, window, cx)
114+ }),
115+ )
116+ .flex_1()
117+ .flex()
118+ .items_center()
119+ .justify_center()
120+ .gap(px(6.))
121+ .rounded(px(4.))
122+ .text_size(px(12.))
123+ .text_color(if active { palette.text } else { palette.muted })
124+ .when(active, |this| this.bg(palette.hover))
125+ .child(label)
126+ .children(alert.then(|| dot(palette)));
127+
128+ match tab {
129+ SidebarTab::Communities => item
130+ .context_menu(new_community_menu(entity))
131+ .into_any_element(),
132+ SidebarTab::Messages => item.into_any_element(),
133+ }
134+ }))
135+ }
136+
137+ fn messages_list(&self, entity: &Entity<Self>, query: &str, palette: Palette) -> Div {
138+ let found = self
139+ .chat
140+ .found
141+ .as_ref()
142+ .filter(|user| !self.is_listed(&user.id));
143+
144+ div()
145+ .flex()
146+ .flex_col()
147+ .gap(px(14.))
148+ .children(found.map(|user| self.found_row(entity, user, palette)))
149+ .children(
150+ query
151+ .is_empty()
152+ .then(|| self.requests(entity, palette))
153+ .flatten(),
154+ )
155+ .child(
156+ div()
157+ .flex()
158+ .flex_col()
159+ .gap(px(1.))
160+ .children(self.direct_rows(entity, query, palette)),
161+ )
162+ .children(group(
163+ "Friends",
164+ palette,
165+ self.friend_rows(entity, query, palette),
166+ ))
167+ }
168+
169+ fn is_listed(&self, user_id: &str) -> bool {
170+ self.chat
171+ .friends
172+ .friends
173+ .iter()
174+ .any(|user| user.id == user_id)
175+ || self.has_direct(user_id)
176+ }
177+
178+ fn has_direct(&self, user_id: &str) -> bool {
179+ self.chat.communities.iter().any(|community| {
180+ matches!(&community.kind, CommunityKind::Direct { peer } if peer.id == user_id)
181+ })
182+ }
183+
184+ fn communities_list(&self, entity: &Entity<Self>, palette: Palette) -> Div {
185+ div().flex().flex_col().gap(px(1.)).children(
186+ self.chat
187+ .communities
188+ .iter()
189+ .filter(|community| matches!(community.kind, CommunityKind::Group))
190+ .map(|community| {
191+ let active = self.chat.is_selected(&community.id);
192+ let alert = self.chat.unread.contains(&community.id);
193+ let can_leave = !active || permission::can_leave(self.actor_rank());
194+ let community_id = community.id.clone();
195+ let select = entity.clone();
196+
197+ let themed = palette.for_community(Some(community), &self.chat.hues);
198+ hoverable_with(
199+ format!("community_{}", community.id),
200+ entry(
201+ themed,
202+ active,
203+ community_icon(
204+ palette,
205+ community,
206+ px(16.),
207+ px(10.),
208+ &self.chat.avatars,
209+ ),
210+ community.name.clone(),
211+ alert.then(|| dot(palette).into_any_element()),
212+ ),
213+ themed.accent.opacity(0.1),
214+ )
215+ .on_click(move |_, window, cx| {
216+ select.update(cx, |yumush, cx| {
217+ yumush.select_community(community_id.clone(), window, cx)
218+ })
219+ })
220+ .context_menu(community_menu(entity, community.id.clone(), can_leave))
221+ .into_any_element()
222+ }),
223+ )
224+ }
225+
226+ fn requests(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
227+ let friends = &self.chat.friends;
228+ let rows: Vec<AnyElement> = friends
229+ .incoming
230+ .iter()
231+ .map(|user| self.incoming_row(entity, user, palette))
232+ .chain(
233+ friends
234+ .outgoing
235+ .iter()
236+ .map(|user| self.outgoing_row(entity, user, palette)),
237+ )
238+ .chain(
239+ self.chat
240+ .invitations
241+ .iter()
242+ .map(|invitation| self.invitation_row(entity, invitation, palette)),
243+ )
244+ .collect();
245+
246+ group("Requests", palette, rows)
247+ }
248+
249+ fn direct_rows(&self, entity: &Entity<Self>, query: &str, palette: Palette) -> Vec<AnyElement> {
250+ self.chat
251+ .communities
252+ .iter()
253+ .filter(|community| matches!(community.kind, CommunityKind::Direct { .. }))
254+ .filter(|community| matches_query(community_name(community), query))
255+ .map(|community| {
256+ let active = self.chat.is_selected(&community.id);
257+ let alert = self.chat.unread.contains(&community.id);
258+ let community_id = community.id.clone();
259+ let select = entity.clone();
260+
261+ let themed = palette.for_community(Some(community), &self.chat.hues);
262+ hoverable_with(
263+ format!("direct_{}", community.id),
264+ entry(
265+ themed,
266+ active,
267+ community_icon(palette, community, px(20.), px(10.), &self.chat.avatars),
268+ community_name(community).to_string(),
269+ alert.then(|| dot(palette).into_any_element()),
270+ ),
271+ themed.accent.opacity(0.1),
272+ )
273+ .on_click(move |_, window, cx| {
274+ select.update(cx, |yumush, cx| {
275+ yumush.select_community(community_id.clone(), window, cx)
276+ })
277+ })
278+ .into_any_element()
279+ })
280+ .collect()
281+ }
282+
283+ fn friend_rows(&self, entity: &Entity<Self>, query: &str, palette: Palette) -> Vec<AnyElement> {
284+ self.chat
285+ .friends
286+ .friends
287+ .iter()
288+ .filter(|user| matches_query(&user.username, query) && !self.has_direct(&user.id))
289+ .map(|user| {
290+ let user_id = user.id.clone();
291+ let open = entity.clone();
292+ let remove = entity.clone();
293+ let remove_id = user.id.clone();
294+
295+ hoverable(
296+ format!("friend_{}", user.id),
297+ entry(
298+ palette,
299+ false,
300+ avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
301+ user.username.clone(),
302+ Vec::new(),
303+ ),
304+ palette,
305+ )
306+ .on_click(move |_, window, cx| {
307+ open.update(cx, |yumush, cx| {
308+ yumush.open_direct(user_id.clone(), window, cx)
309+ })
310+ })
311+ .context_menu(move |menu, _, _| {
312+ let remove = remove.clone();
313+ let remove_id = remove_id.clone();
314+
315+ menu.item(
316+ PopupMenuItem::new("Remove friend").on_click(move |_, window, cx| {
317+ remove.update(cx, |yumush, cx| {
318+ yumush.remove_friend(remove_id.clone(), window, cx)
319+ })
320+ }),
321+ )
322+ })
323+ .into_any_element()
324+ })
325+ .collect()
326+ }
327+
328+ fn found_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {
329+ let relation = self.relation(&user.id);
330+ let mut trailing = Vec::new();
331+
332+ if relation != Relation::Myself {
333+ let user_id = user.id.clone();
334+ trailing.push(icon_button(
335+ format!("message_{}", user.id),
336+ palette,
337+ IconName::MessageSquare,
338+ "Message",
339+ entity_action(entity, move |yumush, window, cx| {
340+ yumush.open_direct(user_id.clone(), window, cx)
341+ }),
342+ ));
343+ }
344+ if let Some((label, icon)) = relation
345+ .action()
346+ .filter(|_| matches!(relation, Relation::Stranger | Relation::Incoming))
347+ {
348+ let user_id = user.id.clone();
349+ trailing.push(icon_button(
350+ format!("friend_action_{}", user.id),
351+ palette,
352+ icon,
353+ label,
354+ entity_action(entity, move |yumush, window, cx| {
355+ yumush.friend_action(relation, user_id.clone(), window, cx)
356+ }),
357+ ));
358+ }
359+
360+ entry(
361+ palette,
362+ false,
363+ avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
364+ user.username.clone(),
365+ trailing,
366+ )
367+ .into_any_element()
368+ }
369+
370+ fn incoming_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {
371+ let accept_id = user.id.clone();
372+ let decline_id = user.id.clone();
373+
374+ entry(
375+ palette,
376+ false,
377+ avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
378+ user.username.clone(),
379+ [
380+ icon_button(
381+ format!("accept_friend_{}", user.id),
382+ palette,
383+ IconName::Check,
384+ "Accept",
385+ entity_action(entity, move |yumush, window, cx| {
386+ yumush.accept_friend(accept_id.clone(), window, cx)
387+ }),
388+ ),
389+ icon_button(
390+ format!("decline_friend_{}", user.id),
391+ palette,
392+ IconName::X,
393+ "Decline",
394+ entity_action(entity, move |yumush, window, cx| {
395+ yumush.remove_friend(decline_id.clone(), window, cx)
396+ }),
397+ ),
398+ ],
399+ )
400+ .into_any_element()
401+ }
402+
403+ fn outgoing_row(&self, entity: &Entity<Self>, user: &User, palette: Palette) -> AnyElement {
404+ let cancel_id = user.id.clone();
405+
406+ entry(
407+ palette,
408+ false,
409+ avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
410+ user.username.clone(),
411+ [icon_button(
412+ format!("cancel_friend_{}", user.id),
413+ palette,
414+ IconName::X,
415+ "Cancel",
416+ entity_action(entity, move |yumush, window, cx| {
417+ yumush.remove_friend(cancel_id.clone(), window, cx)
418+ }),
419+ )],
420+ )
421+ .into_any_element()
422+ }
423+
424+ fn invitation_row(
425+ &self,
426+ entity: &Entity<Self>,
427+ invitation: &Invitation,
428+ palette: Palette,
429+ ) -> AnyElement {
430+ let community = &invitation.community;
431+ let accept_id = community.id.clone();
432+ let decline_id = community.id.clone();
433+ let label = div().flex().flex_col().child(community.name.clone()).child(
434+ div()
435+ .text_size(px(11.))
436+ .text_color(palette.muted)
437+ .child(format!("from {}", invitation.inviter.username)),
438+ );
439+
440+ entry(
441+ palette,
442+ false,
443+ community_icon(palette, community, px(16.), px(10.), &self.chat.avatars),
444+ label,
445+ [
446+ icon_button(
447+ format!("accept_invitation_{}", community.id),
448+ palette,
449+ IconName::Check,
450+ "Accept",
451+ entity_action(entity, move |yumush, window, cx| {
452+ yumush.accept_invitation(accept_id.clone(), window, cx)
453+ }),
454+ ),
455+ icon_button(
456+ format!("decline_invitation_{}", community.id),
457+ palette,
458+ IconName::X,
459+ "Decline",
460+ entity_action(entity, move |yumush, window, cx| {
461+ yumush.decline_invitation(decline_id.clone(), window, cx)
462+ }),
463+ ),
464+ ],
465+ )
466+ .into_any_element()
467+ }
468+
469+ fn account_row(&self, entity: &Entity<Self>, palette: Palette) -> Option<impl IntoElement> {
470+ let user = self.user.as_ref()?;
471+ let status = if self.connected {
472+ palette.ok
473+ } else {
474+ palette.danger
475+ };
476+
477+ Some(
478+ div()
479+ .h(px(32.))
480+ .pl(px(8.))
481+ .pr(px(4.))
482+ .flex()
483+ .items_center()
484+ .gap(px(8.))
485+ .child(
486+ profile_popover(
487+ "account_profile",
488+ Anchor::BottomLeft,
489+ user,
490+ entity,
491+ hoverable(
492+ "account_trigger",
493+ div()
494+ .flex()
495+ .items_center()
496+ .gap(px(8.))
497+ .px(px(4.))
498+ .rounded(px(6.))
499+ .child(avatar(palette, user, px(20.), px(11.), &self.chat.avatars))
500+ .child(
501+ div()
502+ .flex_1()
503+ .min_w_0()
504+ .font_weight(FontWeight::MEDIUM)
505+ .child(user.username.clone()),
506+ ),
507+ palette,
508+ ),
509+ )
510+ .flex_1()
511+ .min_w_0(),
512+ )
513+ .child(div().size(px(6.)).rounded_full().bg(status))
514+ .children(self.voice_controls(entity, palette)),
515+ )
516+ }
517+
518+ fn set_sidebar_tab(&mut self, tab: SidebarTab, window: &mut Window, cx: &mut Context<Self>) {
519+ self.chat.tab = tab;
520+ if tab == SidebarTab::Messages {
521+ self.chat
522+ .search_input
523+ .update(cx, |input, cx| input.focus(window, cx));
524+ }
525+ cx.notify();
526+ }
527+
528+ pub(super) fn open_community_settings(
529+ &mut self,
530+ community_id: String,
531+ window: &mut Window,
532+ cx: &mut Context<Self>,
533+ ) {
534+ self.select_community(community_id, window, cx);
535+ self.show_view(View::CommunitySettings, window, cx);
536+ }
537+}
538+
539+fn community_menu(
540+ entity: &Entity<Yumush>,
541+ community_id: String,
542+ can_leave: bool,
543+) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static {
544+ let entity = entity.clone();
545+
546+ move |menu, _, _| {
547+ let invite = entity.clone();
548+ let invite_id = community_id.clone();
549+ let settings = entity.clone();
550+ let settings_id = community_id.clone();
551+ let leave = entity.clone();
552+ let leave_id = community_id.clone();
553+
554+ let menu = menu
555+ .item(PopupMenuItem::new("Invite").on_click(move |_, window, cx| {
556+ invite.update(cx, |yumush, cx| {
557+ yumush.open_invite(invite_id.clone(), window, cx)
558+ })
559+ }))
560+ .item(
561+ PopupMenuItem::new("Settings").on_click(move |_, window, cx| {
562+ settings.update(cx, |yumush, cx| {
563+ yumush.open_community_settings(settings_id.clone(), window, cx)
564+ })
565+ }),
566+ );
567+
568+ if !can_leave {
569+ return menu;
570+ }
571+
572+ menu.item(PopupMenuItem::new("Leave").on_click(move |_, window, cx| {
573+ leave.update(cx, |yumush, cx| {
574+ yumush.leave_community(leave_id.clone(), window, cx)
575+ })
576+ }))
577+ }
578+}
579+
580+fn matches_query(name: &str, query: &str) -> bool {
581+ name.to_lowercase().contains(query)
582+}
583+
584+fn new_community_menu(
585+ entity: &Entity<Yumush>,
586+) -> impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static {
587+ let entity = entity.clone();
588+
589+ move |menu, _, _| {
590+ let entity = entity.clone();
591+
592+ menu.item(
593+ PopupMenuItem::new("New community").on_click(move |_, window, cx| {
594+ entity.update(cx, |_, cx| {
595+ input_dialog(
596+ "New community",
597+ "Create",
598+ "Name...",
599+ window,
600+ cx,
601+ |this, name, window, cx| {
602+ if validate_community_name(&name).is_ok() {
603+ create_community(this, name, window, cx);
604+ }
605+ },
606+ );
607+ });
608+ }),
609+ )
610+ }
611+}
612+
613+fn input_box(input: &Entity<InputState>, palette: Palette) -> Div {
614+ div()
615+ .h(px(30.))
616+ .px(px(10.))
617+ .flex()
618+ .items_center()
619+ .gap(px(8.))
620+ .rounded(px(8.))
621+ .border_1()
622+ .border_color(palette.border)
623+ .bg(palette.field)
624+ .text_color(palette.muted)
625+ .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.)))
626+ .child(
627+ Input::new(input)
628+ .appearance(false)
629+ .text_color(palette.text)
630+ .flex_1()
631+ .min_w_0(),
632+ )
633+}
634+
635+fn group(title: &'static str, palette: Palette, rows: Vec<AnyElement>) -> Option<Div> {
636+ (!rows.is_empty()).then(|| {
637+ div()
638+ .flex()
639+ .flex_col()
640+ .gap(px(1.))
641+ .child(
642+ div()
643+ .px(px(8.))
644+ .text_size(px(11.))
645+ .text_color(palette.muted)
646+ .child(title),
647+ )
648+ .children(rows)
649+ })
650+}
651+
652+fn entry(
653+ palette: Palette,
654+ active: bool,
655+ leading: impl IntoElement,
656+ label: impl IntoElement,
657+ trailing: impl IntoIterator<Item = AnyElement>,
658+) -> Div {
659+ div()
660+ .h(px(36.))
661+ .px(px(6.))
662+ .flex()
663+ .items_center()
664+ .gap(px(8.))
665+ .rounded(px(6.))
666+ .text_color(if active { palette.text } else { palette.body })
667+ .when(active, |this| this.bg(palette.accent.opacity(0.18)))
668+ .child(leading)
669+ .child(div().flex_1().min_w_0().truncate().child(label))
670+ .children(trailing)
671+}
672+
673+fn dot(palette: Palette) -> Div {
674+ div().size(px(6.)).rounded_full().bg(palette.alert)
675+}
676+
677+fn icon_button(
678+ id: String,
679+ palette: Palette,
680+ icon: IconName,
681+ tip: &'static str,
682+ on_click: impl Fn(&mut Window, &mut App) + 'static,
683+) -> AnyElement {
684+ clickable(id, palette, on_click)
685+ .tip(tip)
686+ .size(px(24.))
687+ .flex()
688+ .items_center()
689+ .justify_center()
690+ .rounded(px(6.))
691+ .text_color(palette.muted)
692+ .child(Icon::new(icon).w(px(14.)).h(px(14.)))
693+ .into_any_element()
694+}
crates/client/src/gui/snippet.rsadded+104 -0
@@ -0,0 +1,104 @@
1+use common::model::{Message, Role, SnippetMessage, User};
2+use gpui_kit::{
3+ Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px,
4+ relative,
5+};
6+
7+use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view};
8+
9+pub fn snippet_card(
10+ message: &Message,
11+ chat: &Chat,
12+ entity: &Entity<Yumush>,
13+ palette: Palette,
14+) -> Option<impl IntoElement> {
15+ let snippet = message.snippet.as_ref()?;
16+ let header = match &snippet.origin {
17+ Some(origin) => format!("Forwarded · {origin}"),
18+ None => "Forwarded".to_string(),
19+ };
20+
21+ Some(
22+ div()
23+ .flex()
24+ .flex_col()
25+ .gap(px(10.))
26+ .p(px(10.))
27+ .rounded(px(8.))
28+ .border_1()
29+ .border_color(palette.border)
30+ .bg(palette.panel)
31+ .child(
32+ div()
33+ .text_size(px(12.))
34+ .text_color(palette.muted)
35+ .child(header),
36+ )
37+ .children(
38+ snippet
39+ .messages
40+ .iter()
41+ .map(|item| snippet_row(item, chat, entity, palette)),
42+ ),
43+ )
44+}
45+
46+fn snippet_row(
47+ item: &SnippetMessage,
48+ chat: &Chat,
49+ entity: &Entity<Yumush>,
50+ palette: Palette,
51+) -> impl IntoElement {
52+ let user = User {
53+ id: item.user_id.clone(),
54+ username: item.username.clone(),
55+ role: Role::User,
56+ status: String::new(),
57+ avatar_id: item.avatar_id.clone(),
58+ };
59+
60+ div()
61+ .flex()
62+ .gap(px(8.))
63+ .child(avatar(palette, &user, px(20.), px(10.), &chat.avatars))
64+ .child(
65+ div()
66+ .flex_1()
67+ .min_w_0()
68+ .flex()
69+ .flex_col()
70+ .gap(px(4.))
71+ .child(
72+ div()
73+ .flex()
74+ .items_center()
75+ .gap(px(6.))
76+ .child(
77+ div()
78+ .font_weight(FontWeight::SEMIBOLD)
79+ .text_color(palette.tinted(&item.user_id))
80+ .child(item.username.clone()),
81+ )
82+ .child(
83+ div()
84+ .text_size(px(11.))
85+ .text_color(palette.muted)
86+ .child(id_time(&item.id, "%H:%M")),
87+ ),
88+ )
89+ .when(!item.body.is_empty(), |this| {
90+ this.child(
91+ div()
92+ .line_height(relative(1.5))
93+ .text_color(palette.body)
94+ .child(item.body.clone()),
95+ )
96+ })
97+ .children(media_view::attachments(
98+ &item.attachments,
99+ &chat.media,
100+ entity,
101+ palette,
102+ )),
103+ )
104+}
crates/client/src/gui/social.rsadded+461 -0
@@ -0,0 +1,461 @@
1+use std::{fmt::Display, future::Future};
2+
3+use common::{
4+ model::{Community, CommunityKind},
5+ validate::validate_username,
6+};
7+use gpui_kit::{
8+ Context, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
9+ assets::IconName,
10+ component::{
11+ WindowExt,
12+ input::{Input, InputEvent, InputState},
13+ },
14+ div, px,
15+};
16+
17+use super::{Palette, Yumush, avatar, new_input, notify_error, primary_button};
18+
19+#[derive(Debug, Clone, Default)]
20+pub enum InviteLookup {
21+ #[default]
22+ Idle,
23+ Found(common::model::User),
24+ Member(common::model::User),
25+ Missing,
26+}
27+
28+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29+pub enum Relation {
30+ Myself,
31+ Friend,
32+ Outgoing,
33+ Incoming,
34+ Stranger,
35+}
36+
37+impl Relation {
38+ pub fn action(self) -> Option<(&'static str, IconName)> {
39+ match self {
40+ Relation::Myself => None,
41+ Relation::Friend => Some(("Remove friend", IconName::UserX)),
42+ Relation::Outgoing => Some(("Cancel request", IconName::X)),
43+ Relation::Incoming => Some(("Accept friend", IconName::UserCheck)),
44+ Relation::Stranger => Some(("Add friend", IconName::UserPlus)),
45+ }
46+ }
47+}
48+
49+fn spawn_done<E: Display + 'static>(
50+ window: &mut Window,
51+ cx: &mut Context<Yumush>,
52+ call: impl Future<Output = Result<(), E>> + 'static,
53+) {
54+ cx.spawn_in(window, async move |this, cx| {
55+ if let Err(error) = call.await {
56+ notify_error(&this, cx, error);
57+ }
58+ })
59+ .detach();
60+}
61+
62+fn spawn_community<E: Display + 'static>(
63+ window: &mut Window,
64+ cx: &mut Context<Yumush>,
65+ call: impl Future<Output = Result<Community, E>> + 'static,
66+) {
67+ cx.spawn_in(window, async move |this, cx| match call.await {
68+ Ok(community) => {
69+ let _ = this.update_in(cx, |yumush, window, cx| {
70+ yumush.enter_community(community, window, cx);
71+ });
72+ }
73+ Err(error) => notify_error(&this, cx, error),
74+ })
75+ .detach();
76+}
77+
78+impl Yumush {
79+ pub(super) fn relation(&self, user_id: &str) -> Relation {
80+ let friends = &self.chat.friends;
81+
82+ if self.is_me(user_id) {
83+ Relation::Myself
84+ } else if friends.friends.iter().any(|user| user.id == user_id) {
85+ Relation::Friend
86+ } else if friends.outgoing.iter().any(|user| user.id == user_id) {
87+ Relation::Outgoing
88+ } else if friends.incoming.iter().any(|user| user.id == user_id) {
89+ Relation::Incoming
90+ } else {
91+ Relation::Stranger
92+ }
93+ }
94+
95+ pub(super) fn request_social_avatars(&mut self, cx: &mut Context<Self>) {
96+ let chat = &self.chat;
97+ let users = chat
98+ .friends
99+ .friends
100+ .iter()
101+ .chain(&chat.friends.incoming)
102+ .chain(&chat.friends.outgoing)
103+ .chain(
104+ chat.invitations
105+ .iter()
106+ .map(|invitation| &invitation.inviter),
107+ )
108+ .chain(
109+ chat.communities
110+ .iter()
111+ .filter_map(|community| match &community.kind {
112+ CommunityKind::Direct { peer } => Some(peer),
113+ CommunityKind::Group => None,
114+ }),
115+ );
116+ let avatar_ids: Vec<String> = users
117+ .filter_map(|user| user.avatar_id.clone())
118+ .chain(
119+ chat.communities
120+ .iter()
121+ .filter_map(|community| community.avatar_id.clone()),
122+ )
123+ .collect();
124+
125+ for avatar_id in avatar_ids {
126+ self.request_avatar(&avatar_id, cx);
127+ }
128+ }
129+
130+ pub(super) fn load_social(&self, window: &mut Window, cx: &mut Context<Self>) {
131+ let network = self.network.clone();
132+
133+ cx.spawn_in(window, async move |this, cx| {
134+ let (friends, invitations) =
135+ match (network.friends().await, network.invitations().await) {
136+ (Ok(friends), Ok(invitations)) => (friends, invitations),
137+ (Err(error), _) | (_, Err(error)) => {
138+ notify_error(&this, cx, error);
139+ return;
140+ }
141+ };
142+
143+ let _ = this.update(cx, |yumush, cx| {
144+ yumush.chat.friends = friends;
145+ yumush.chat.invitations = invitations;
146+ yumush.request_social_avatars(cx);
147+ cx.notify();
148+ });
149+ })
150+ .detach();
151+ }
152+
153+ pub(super) fn search_query(&self, cx: &Context<Self>) -> String {
154+ self.chat
155+ .search_input
156+ .read(cx)
157+ .text()
158+ .to_string()
159+ .trim()
160+ .to_lowercase()
161+ }
162+
163+ pub(super) fn search_user(&mut self, window: &mut Window, cx: &mut Context<Self>) {
164+ self.chat.found = None;
165+ cx.notify();
166+ let username = self.search_query(cx);
167+ if validate_username(&username).is_err() {
168+ return;
169+ }
170+ let network = self.network.clone();
171+
172+ cx.spawn_in(window, async move |this, cx| {
173+ let found = network.find_user(&username).await.ok();
174+ let _ = this.update(cx, |yumush, cx| {
175+ if yumush.search_query(cx) != username {
176+ return;
177+ }
178+ if let Some(user) = &found {
179+ yumush.request_user_avatar(user, cx);
180+ }
181+ yumush.chat.found = found;
182+ cx.notify();
183+ });
184+ })
185+ .detach();
186+ }
187+
188+ pub(super) fn open_found(&self, window: &mut Window, cx: &mut Context<Self>) {
189+ if let Some(user) = &self.chat.found {
190+ self.open_direct(user.id.clone(), window, cx);
191+ }
192+ }
193+
194+ pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {
195+ let network = self.network.clone();
196+
197+ spawn_community(
198+ window,
199+ cx,
200+ async move { network.open_direct(&user_id).await },
201+ );
202+ }
203+
204+ pub(super) fn friend_action(
205+ &self,
206+ relation: Relation,
207+ user_id: String,
208+ window: &mut Window,
209+ cx: &mut Context<Self>,
210+ ) {
211+ match relation {
212+ Relation::Myself => {}
213+ Relation::Stranger => self.add_friend(user_id, window, cx),
214+ Relation::Incoming => self.accept_friend(user_id, window, cx),
215+ Relation::Friend | Relation::Outgoing => self.remove_friend(user_id, window, cx),
216+ }
217+ }
218+
219+ pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context<Self>) {
220+ let network = self.network.clone();
221+
222+ spawn_done(
223+ window,
224+ cx,
225+ async move { network.add_friend(&user_id).await },
226+ );
227+ }
228+
229+ pub(super) fn accept_friend(
230+ &self,
231+ user_id: String,
232+ window: &mut Window,
233+ cx: &mut Context<Self>,
234+ ) {
235+ let network = self.network.clone();
236+
237+ spawn_done(
238+ window,
239+ cx,
240+ async move { network.accept_friend(&user_id).await },
241+ );
242+ }
243+
244+ pub(super) fn remove_friend(
245+ &self,
246+ user_id: String,
247+ window: &mut Window,
248+ cx: &mut Context<Self>,
249+ ) {
250+ let network = self.network.clone();
251+
252+ spawn_done(
253+ window,
254+ cx,
255+ async move { network.remove_friend(&user_id).await },
256+ );
257+ }
258+
259+ pub(super) fn accept_invitation(
260+ &self,
261+ community_id: String,
262+ window: &mut Window,
263+ cx: &mut Context<Self>,
264+ ) {
265+ let network = self.network.clone();
266+
267+ spawn_community(window, cx, async move {
268+ network.accept_invitation(&community_id).await
269+ });
270+ }
271+
272+ pub(super) fn decline_invitation(
273+ &self,
274+ community_id: String,
275+ window: &mut Window,
276+ cx: &mut Context<Self>,
277+ ) {
278+ let network = self.network.clone();
279+
280+ spawn_done(window, cx, async move {
281+ network.decline_invitation(&community_id).await
282+ });
283+ }
284+
285+ pub(super) fn open_invite(
286+ &mut self,
287+ community_id: String,
288+ window: &mut Window,
289+ cx: &mut Context<Self>,
290+ ) {
291+ self.chat.invite = InviteLookup::Idle;
292+ let input = new_input("Username...", window, cx);
293+ let enter_id = community_id.clone();
294+ let lookup_id = community_id.clone();
295+
296+ cx.subscribe_in(
297+ &input,
298+ window,
299+ move |this, input, event, window, cx| match event {
300+ InputEvent::Change => this.lookup_invite(lookup_id.clone(), input, window, cx),
301+ InputEvent::PressEnter { .. } => this.send_invite(enter_id.clone(), window, cx),
302+ _ => {}
303+ },
304+ )
305+ .detach();
306+
307+ let entity = cx.entity();
308+ let dialog_input = input.clone();
309+ window.open_dialog(cx, move |dialog, _, cx| {
310+ let yumush = entity.read(cx);
311+ let palette = yumush.themed(cx);
312+ let result =
313+ invite_result(&yumush.chat.invite, &community_id, &entity, yumush, palette);
314+
315+ dialog.title("Invite").child(
316+ div()
317+ .flex()
318+ .flex_col()
319+ .gap(px(12.))
320+ .child(Input::new(&dialog_input))
321+ .children(result),
322+ )
323+ });
324+ window.defer(cx, move |window, cx| {
325+ input.update(cx, |input, cx| input.focus(window, cx));
326+ });
327+ }
328+
329+ fn lookup_invite(
330+ &mut self,
331+ community_id: String,
332+ input: &Entity<InputState>,
333+ window: &mut Window,
334+ cx: &mut Context<Self>,
335+ ) {
336+ let username = input.read(cx).text().to_string().trim().to_string();
337+ self.chat.invite = InviteLookup::Idle;
338+ window.refresh();
339+ if validate_username(&username).is_err() {
340+ return;
341+ }
342+ let network = self.network.clone();
343+ let input = input.clone();
344+
345+ cx.spawn_in(window, async move |this, cx| {
346+ let lookup = match network.find_user(&username).await {
347+ Ok(user) => {
348+ let members = network.members(&community_id).await.unwrap_or_default();
349+ if members.iter().any(|member| member.user.id == user.id) {
350+ InviteLookup::Member(user)
351+ } else {
352+ InviteLookup::Found(user)
353+ }
354+ }
355+ Err(_) => InviteLookup::Missing,
356+ };
357+ let _ = this.update_in(cx, |yumush, window, cx| {
358+ if input.read(cx).text().to_string().trim() != username {
359+ return;
360+ }
361+ if let InviteLookup::Found(user) | InviteLookup::Member(user) = &lookup {
362+ yumush.request_user_avatar(user, cx);
363+ }
364+ yumush.chat.invite = lookup;
365+ window.refresh();
366+ });
367+ })
368+ .detach();
369+ }
370+
371+ fn send_invite(&self, community_id: String, window: &mut Window, cx: &mut Context<Self>) {
372+ let InviteLookup::Found(user) = &self.chat.invite else {
373+ return;
374+ };
375+ let network = self.network.clone();
376+ let user_id = user.id.clone();
377+
378+ cx.spawn_in(window, async move |this, cx| {
379+ match network.invite(&community_id, &user_id).await {
380+ Ok(()) => {
381+ let _ = this.update_in(cx, |_, window, cx| window.close_dialog(cx));
382+ }
383+ Err(error) => notify_error(&this, cx, error),
384+ }
385+ })
386+ .detach();
387+ }
388+}
389+
390+fn invite_result(
391+ lookup: &InviteLookup,
392+ community_id: &str,
393+ entity: &Entity<Yumush>,
394+ yumush: &Yumush,
395+ palette: Palette,
396+) -> Option<gpui_kit::AnyElement> {
397+ match lookup {
398+ InviteLookup::Idle => None,
399+ InviteLookup::Missing => Some(
400+ div()
401+ .text_size(px(13.))
402+ .text_color(palette.muted)
403+ .child("No such user")
404+ .into_any_element(),
405+ ),
406+ InviteLookup::Member(user) => Some(
407+ user_row(user, yumush, palette)
408+ .child(
409+ div()
410+ .text_size(px(13.))
411+ .text_color(palette.muted)
412+ .child("Member"),
413+ )
414+ .into_any_element(),
415+ ),
416+ InviteLookup::Found(user) => {
417+ let entity = entity.clone();
418+ let community_id = community_id.to_string();
419+
420+ Some(
421+ user_row(user, yumush, palette)
422+ .child(
423+ primary_button("invite_send", palette, move |window, cx| {
424+ entity.update(cx, |yumush, cx| {
425+ yumush.send_invite(community_id.clone(), window, cx)
426+ })
427+ })
428+ .h(px(30.))
429+ .px(px(14.))
430+ .flex()
431+ .items_center()
432+ .rounded(px(8.))
433+ .child("Invite"),
434+ )
435+ .into_any_element(),
436+ )
437+ }
438+ }
439+}
440+
441+fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gpui_kit::Div {
442+ div()
443+ .flex()
444+ .items_center()
445+ .gap(px(10.))
446+ .child(avatar(
447+ palette,
448+ user,
449+ px(32.),
450+ px(14.),
451+ &yumush.chat.avatars,
452+ ))
453+ .child(
454+ div()
455+ .flex_1()
456+ .min_w_0()
457+ .truncate()
458+ .font_weight(FontWeight::SEMIBOLD)
459+ .child(user.username.clone()),
460+ )
461+}
crates/client/src/gui/voice_settings.rsadded+536 -0
@@ -0,0 +1,536 @@
1+use std::time::Duration;
2+
3+use gpui_kit::{
4+ App, AppContext, Context, Div, Entity, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
5+ ModifiersChangedEvent, ParentElement, SharedString, Stateful, Styled, Subscription, Task,
6+ Window,
7+ assets::IconName,
8+ component::{
9+ Icon, IndexPath,
10+ kbd::Kbd,
11+ searchable_list::{SearchableListItem, SearchableVec},
12+ select::{Select, SelectEvent, SelectState},
13+ slider::{Slider, SliderEvent, SliderState},
14+ },
15+ div, px, relative,
16+};
17+
18+use super::{
19+ Palette, Yumush, clickable,
20+ settings_page::{row, segmented},
21+};
22+use crate::{
23+ settings::{Activation, SENSITIVITY_DB, VOLUME, VoiceSettings},
24+ voice::audio::{self, Device, Devices},
25+};
26+
27+const LEVEL_INTERVAL: Duration = Duration::from_millis(50);
28+const MODES: [(Activation, &str); 2] = [
29+ (Activation::VoiceActivity, "Voice activity"),
30+ (Activation::PushToTalk, "Push to talk"),
31+];
32+
33+#[derive(Clone, Copy, PartialEq, Eq)]
34+pub(super) enum Side {
35+ Input,
36+ Output,
37+}
38+
39+#[derive(Clone, Copy)]
40+pub(super) enum VoiceField {
41+ Sensitivity,
42+ InputVolume,
43+ OutputVolume,
44+}
45+
46+#[derive(Clone, Copy, PartialEq, Eq)]
47+pub(super) enum MicTest {
48+ Off,
49+ On,
50+}
51+
52+#[derive(Clone, Copy, PartialEq, Eq)]
53+pub(super) enum KeyCapture {
54+ Idle,
55+ Waiting,
56+}
57+
58+#[derive(Clone)]
59+pub(super) struct DeviceItem {
60+ id: Option<String>,
61+ name: SharedString,
62+}
63+
64+impl DeviceItem {
65+ fn default_choice() -> Self {
66+ Self {
67+ id: None,
68+ name: "Default".into(),
69+ }
70+ }
71+}
72+
73+impl SearchableListItem for DeviceItem {
74+ type Value = Option<String>;
75+
76+ fn title(&self) -> SharedString {
77+ self.name.clone()
78+ }
79+
80+ fn value(&self) -> &Option<String> {
81+ &self.id
82+ }
83+}
84+
85+type DeviceList = SearchableVec<DeviceItem>;
86+
87+pub(super) struct VoiceControls {
88+ pub(super) inputs: Entity<SelectState<DeviceList>>,
89+ pub(super) outputs: Entity<SelectState<DeviceList>>,
90+ pub(super) sensitivity: Entity<SliderState>,
91+ pub(super) input_volume: Entity<SliderState>,
92+ pub(super) output_volume: Entity<SliderState>,
93+ pub(super) mic_test: MicTest,
94+ pub(super) key: KeyCapture,
95+ level_poll: Option<Task<()>>,
96+ _subscriptions: Vec<Subscription>,
97+}
98+
99+impl VoiceControls {
100+ pub(super) fn new(
101+ settings: &VoiceSettings,
102+ window: &mut Window,
103+ cx: &mut Context<Yumush>,
104+ ) -> Self {
105+ let inputs = device_select(window, cx);
106+ let outputs = device_select(window, cx);
107+ let sensitivity = slider(&SENSITIVITY_DB, settings.sensitivity_db, cx);
108+ let input_volume = slider(&VOLUME, settings.input_volume, cx);
109+ let output_volume = slider(&VOLUME, settings.output_volume, cx);
110+
111+ let subscriptions = vec![
112+ cx.subscribe(&inputs, |this, _, event: &SelectEvent<DeviceList>, cx| {
113+ if let SelectEvent::Confirm(Some(id)) = event {
114+ this.set_voice_device(Side::Input, id.clone(), cx);
115+ }
116+ }),
117+ cx.subscribe(&outputs, |this, _, event: &SelectEvent<DeviceList>, cx| {
118+ if let SelectEvent::Confirm(Some(id)) = event {
119+ this.set_voice_device(Side::Output, id.clone(), cx);
120+ }
121+ }),
122+ cx.subscribe(&sensitivity, |this, _, event: &SliderEvent, cx| {
123+ this.slider_changed(VoiceField::Sensitivity, event, cx);
124+ }),
125+ cx.subscribe(&input_volume, |this, _, event: &SliderEvent, cx| {
126+ this.slider_changed(VoiceField::InputVolume, event, cx);
127+ }),
128+ cx.subscribe(&output_volume, |this, _, event: &SliderEvent, cx| {
129+ this.slider_changed(VoiceField::OutputVolume, event, cx);
130+ }),
131+ ];
132+
133+ Self {
134+ inputs,
135+ outputs,
136+ sensitivity,
137+ input_volume,
138+ output_volume,
139+ mic_test: MicTest::Off,
140+ key: KeyCapture::Idle,
141+ level_poll: None,
142+ _subscriptions: subscriptions,
143+ }
144+ }
145+}
146+
147+fn device_select(window: &mut Window, cx: &mut Context<Yumush>) -> Entity<SelectState<DeviceList>> {
148+ cx.new(|cx| {
149+ SelectState::new(
150+ SearchableVec::new(vec![DeviceItem::default_choice()]),
151+ Some(IndexPath::new(0)),
152+ window,
153+ cx,
154+ )
155+ })
156+}
157+
158+fn slider(
159+ range: &std::ops::RangeInclusive<f32>,
160+ value: f32,
161+ cx: &mut Context<Yumush>,
162+) -> Entity<SliderState> {
163+ cx.new(|_| {
164+ SliderState::new()
165+ .min(*range.start())
166+ .max(*range.end())
167+ .default_value(value)
168+ })
169+}
170+
171+fn device_list(devices: Vec<Device>) -> DeviceList {
172+ let mut items = vec![DeviceItem::default_choice()];
173+ items.extend(devices.into_iter().map(|device| DeviceItem {
174+ id: Some(device.id),
175+ name: device.name.into(),
176+ }));
177+ SearchableVec::new(items)
178+}
179+
180+fn volume_control(state: &Entity<SliderState>, value: f32, palette: Palette) -> Div {
181+ div()
182+ .flex()
183+ .items_center()
184+ .gap(px(8.))
185+ .child(Slider::new(state).w(px(160.)))
186+ .child(
187+ div()
188+ .w(px(44.))
189+ .text_right()
190+ .text_color(palette.muted)
191+ .child(format!("{value:.0}%")),
192+ )
193+}
194+
195+fn level_bar(level: Option<f32>, threshold: f32, palette: Palette) -> Div {
196+ let range = SENSITIVITY_DB;
197+ let fraction = level.map_or(0.0, |db| {
198+ ((db - range.start()) / (range.end() - range.start())).clamp(0.0, 1.0)
199+ });
200+ let color = if level.is_some_and(|db| db >= threshold) {
201+ palette.ok
202+ } else {
203+ palette.muted
204+ };
205+
206+ div()
207+ .h(px(4.))
208+ .w_full()
209+ .rounded(px(2.))
210+ .bg(palette.border)
211+ .child(
212+ div()
213+ .h_full()
214+ .w(relative(fraction))
215+ .rounded(px(2.))
216+ .bg(color),
217+ )
218+}
219+
220+impl Yumush {
221+ pub(super) fn voice_rows(&self, entity: &Entity<Self>, palette: Palette, cx: &App) -> Vec<Div> {
222+ let voice = &self.settings.voice;
223+ let controls = &self.voice;
224+
225+ let mut rows = vec![
226+ row(
227+ "Input device",
228+ div().child(Select::new(&controls.inputs).w(px(200.))),
229+ ),
230+ row(
231+ "Output device",
232+ div().child(Select::new(&controls.outputs).w(px(200.))),
233+ ),
234+ row(
235+ "Input volume",
236+ volume_control(&controls.input_volume, voice.input_volume, palette),
237+ ),
238+ row(
239+ "Output volume",
240+ volume_control(&controls.output_volume, voice.output_volume, palette),
241+ ),
242+ row(
243+ "Mode",
244+ segmented(
245+ MODES,
246+ voice.activation,
247+ entity,
248+ palette,
249+ Yumush::set_voice_mode,
250+ ),
251+ ),
252+ ];
253+
254+ if self.chat.voice_community().is_none() {
255+ rows.push(row("Test", self.test_control(entity, palette)));
256+ }
257+ match voice.activation {
258+ Activation::VoiceActivity => {
259+ rows.push(row("Sensitivity", self.sensitivity_control(palette)))
260+ }
261+ Activation::PushToTalk => rows.push(row(
262+ "Key",
263+ self.key_control(&voice.push_to_talk_key, entity, palette, cx),
264+ )),
265+ }
266+
267+ rows
268+ }
269+
270+ fn test_control(&self, entity: &Entity<Self>, palette: Palette) -> Div {
271+ let testing = self.voice.mic_test == MicTest::On;
272+ let mic = entity.clone();
273+ let speaker = entity.clone();
274+
275+ div()
276+ .flex()
277+ .items_center()
278+ .gap(px(6.))
279+ .child(
280+ test_button("mic_test_button", palette, testing, move |_, cx| {
281+ mic.update(cx, |yumush, cx| yumush.toggle_mic_test(cx));
282+ })
283+ .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.)))
284+ .child(if testing { "Stop" } else { "Hear yourself" }),
285+ )
286+ .child(
287+ test_button("speaker_test_button", palette, false, move |_, cx| {
288+ speaker.update(cx, |yumush, _| yumush.network.play_chime());
289+ })
290+ .child(Icon::new(IconName::Volume2).w(px(14.)).h(px(14.)))
291+ .child("Play sound"),
292+ )
293+ }
294+
295+ fn sensitivity_control(&self, palette: Palette) -> Div {
296+ let level = self.network.voice_level_db();
297+
298+ div().flex().items_center().gap(px(8.)).child(
299+ div()
300+ .w(px(200.))
301+ .flex()
302+ .flex_col()
303+ .gap(px(6.))
304+ .child(Slider::new(&self.voice.sensitivity))
305+ .child(level_bar(
306+ level,
307+ self.settings.voice.sensitivity_db,
308+ palette,
309+ )),
310+ )
311+ }
312+
313+ fn key_control(
314+ &self,
315+ key: &str,
316+ entity: &Entity<Self>,
317+ palette: Palette,
318+ cx: &App,
319+ ) -> impl IntoElement {
320+ let content = match self.voice.key {
321+ KeyCapture::Waiting => div().child("Press key").into_any_element(),
322+ KeyCapture::Idle => match Keystroke::parse_with_os(key, cx.platform_info().os) {
323+ Ok(stroke) if !key.is_empty() => Kbd::new(stroke).into_any_element(),
324+ _ => div().child("Set key").into_any_element(),
325+ },
326+ };
327+ let entity = entity.clone();
328+
329+ clickable("ptt_key_button", palette, move |window, cx| {
330+ entity.update(cx, |yumush, cx| yumush.capture_key(window, cx));
331+ })
332+ .h(px(28.))
333+ .px(px(8.))
334+ .flex()
335+ .items_center()
336+ .rounded(px(6.))
337+ .child(content)
338+ }
339+
340+ fn slider_changed(&mut self, field: VoiceField, event: &SliderEvent, cx: &mut Context<Self>) {
341+ let SliderEvent::Change(value) = event else {
342+ return;
343+ };
344+ let value = value.start();
345+ let voice = &mut self.settings.voice;
346+
347+ match field {
348+ VoiceField::Sensitivity => voice.sensitivity_db = value,
349+ VoiceField::InputVolume => voice.input_volume = value,
350+ VoiceField::OutputVolume => voice.output_volume = value,
351+ }
352+ self.commit_settings(cx);
353+ }
354+
355+ pub(super) fn set_voice_device(
356+ &mut self,
357+ side: Side,
358+ id: Option<String>,
359+ cx: &mut Context<Self>,
360+ ) {
361+ match side {
362+ Side::Input => self.settings.voice.choice.input = id,
363+ Side::Output => self.settings.voice.choice.output = id,
364+ }
365+ self.commit_settings(cx);
366+ }
367+
368+ pub(super) fn set_voice_mode(&mut self, activation: Activation, cx: &mut Context<Self>) {
369+ self.settings.voice.activation = activation;
370+ self.commit_settings(cx);
371+ }
372+
373+ pub(super) fn capture_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
374+ window.focus(&self.focus, cx);
375+ self.voice.key = KeyCapture::Waiting;
376+ cx.notify();
377+ }
378+
379+ fn is_push_key(&self, key: &str) -> bool {
380+ self.settings.voice.activation == Activation::PushToTalk
381+ && !key.is_empty()
382+ && self.settings.voice.push_to_talk_key == key
383+ }
384+
385+ pub(super) fn voice_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context<Self>) {
386+ let key = event.keystroke.key.clone();
387+
388+ match self.voice.key {
389+ KeyCapture::Waiting => {
390+ cx.stop_propagation();
391+ self.voice.key = KeyCapture::Idle;
392+ if key != "escape" {
393+ self.settings.voice.push_to_talk_key = key;
394+ self.commit_settings(cx);
395+ }
396+ cx.notify();
397+ }
398+ KeyCapture::Idle => {
399+ if self.is_push_key(&key) {
400+ self.network.set_talking(true);
401+ }
402+ }
403+ }
404+ }
405+
406+ pub(super) fn voice_key_up(&mut self, event: &KeyUpEvent, _: &mut Context<Self>) {
407+ if self.is_push_key(&event.keystroke.key) {
408+ self.network.set_talking(false);
409+ }
410+ }
411+
412+ pub(super) fn voice_modifiers(
413+ &mut self,
414+ event: &ModifiersChangedEvent,
415+ cx: &mut Context<Self>,
416+ ) {
417+ let modifiers = event.modifiers;
418+ let held = [
419+ ("ctrl", modifiers.control),
420+ ("shift", modifiers.shift),
421+ ("alt", modifiers.alt),
422+ ("super", modifiers.platform),
423+ ];
424+
425+ match self.voice.key {
426+ KeyCapture::Waiting => {
427+ let Some((key, _)) = held.iter().find(|(_, down)| *down) else {
428+ return;
429+ };
430+ self.voice.key = KeyCapture::Idle;
431+ self.settings.voice.push_to_talk_key = key.to_string();
432+ self.commit_settings(cx);
433+ cx.notify();
434+ }
435+ KeyCapture::Idle => {
436+ if let Some((_, down)) = held.iter().find(|(key, _)| self.is_push_key(key)) {
437+ self.network.set_talking(*down);
438+ }
439+ }
440+ }
441+ }
442+
443+ pub(super) fn toggle_mic_test(&mut self, cx: &mut Context<Self>) {
444+ match self.voice.mic_test {
445+ MicTest::On => self.stop_mic_test(),
446+ MicTest::Off => {
447+ self.network.start_mic_test();
448+ self.voice.mic_test = MicTest::On;
449+ self.start_level_poll(cx);
450+ }
451+ }
452+ cx.notify();
453+ }
454+
455+ pub(super) fn stop_mic_test(&mut self) {
456+ self.network.stop_mic_test();
457+ self.voice.mic_test = MicTest::Off;
458+ self.voice.level_poll = None;
459+ }
460+
461+ pub(super) fn leave_settings(&mut self) {
462+ self.stop_mic_test();
463+ self.voice.key = KeyCapture::Idle;
464+ }
465+
466+ pub(super) fn enter_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
467+ self.load_audio_devices(window, cx);
468+ if self.network.voice_level_db().is_some() {
469+ self.start_level_poll(cx);
470+ }
471+ }
472+
473+ fn start_level_poll(&mut self, cx: &mut Context<Self>) {
474+ self.voice.level_poll = Some(cx.spawn(async move |this, cx| {
475+ loop {
476+ cx.background_executor().timer(LEVEL_INTERVAL).await;
477+ let live = this.update(cx, |yumush, cx| {
478+ let live = yumush.network.voice_level_db().is_some();
479+ cx.notify();
480+ live
481+ });
482+ if !matches!(live, Ok(true)) {
483+ break;
484+ }
485+ }
486+ }));
487+ }
488+
489+ fn load_audio_devices(&self, window: &mut Window, cx: &mut Context<Self>) {
490+ cx.spawn_in(window, async move |this, cx| {
491+ let devices = cx
492+ .background_executor()
493+ .spawn(async { audio::devices() })
494+ .await;
495+ let _ = this.update_in(cx, |yumush, window, cx| {
496+ yumush.apply_devices(devices, window, cx);
497+ });
498+ })
499+ .detach();
500+ }
501+
502+ fn apply_devices(&mut self, devices: Devices, window: &mut Window, cx: &mut Context<Self>) {
503+ let choice = self.settings.voice.choice.clone();
504+
505+ self.voice.inputs.update(cx, |state, cx| {
506+ state.set_items(device_list(devices.inputs), window, cx);
507+ state.set_selected_value(&choice.input, window, cx);
508+ });
509+ self.voice.outputs.update(cx, |state, cx| {
510+ state.set_items(device_list(devices.outputs), window, cx);
511+ state.set_selected_value(&choice.output, window, cx);
512+ });
513+ }
514+}
515+
516+fn test_button(
517+ id: &'static str,
518+ palette: Palette,
519+ active: bool,
520+ on_click: impl Fn(&mut Window, &mut App) + 'static,
521+) -> Stateful<Div> {
522+ clickable(id, palette, on_click)
523+ .h(px(28.))
524+ .px(px(10.))
525+ .flex()
526+ .items_center()
527+ .gap(px(6.))
528+ .rounded(px(6.))
529+ .border_1()
530+ .border_color(if active {
531+ palette.accent
532+ } else {
533+ palette.border
534+ })
535+ .text_color(if active { palette.text } else { palette.body })
536+}
crates/client/src/lib.rsmodified+6 -0
@@ -1,7 +1,13 @@
1 use common::config::Config;1 use common::config::Config;
2 2
3+pub mod accounts;
4+pub mod avatar;
5+pub mod embed;
3 pub mod gui;6 pub mod gui;
7+pub mod media;
4 pub mod network;8 pub mod network;
9+pub mod settings;
10+pub mod voice;
5 11
6 pub const NAME: &str = "Yumush";12 pub const NAME: &str = "Yumush";
7 13
crates/client/src/main.rsmodified+45 -25
@@ -1,38 +1,58 @@
1-use client::{ClientConfig, NAME, gui::Yumush, network};1+use client::{
2+ ClientConfig, NAME,
3+ gui::{self, Yumush},
4+ network, settings,
5+};
2 use gpui_kit::{6 use gpui_kit::{
3 App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application,7 App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application,
4- component::Root, init, px, size,8+ assets::AllAssets, component::Root, init, px, size,
5 };9 };
6 10
11+use tracing::Level;
12+use tracing_subscriber::{filter::Targets, layer::SubscriberExt, util::SubscriberInitExt};
13+
7 fn main() {14 fn main() {
8- tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();15+ tracing_subscriber::registry()
16+ .with(tracing_subscriber::fmt::layer())
17+ .with(
18+ Targets::new()
19+ .with_default(Level::INFO)
20+ .with_target("zbus", Level::ERROR),
21+ )
22+ .init();
9 23
24+ let settings = settings::load();
10 let (network_handle, network_event_receiver) = network::start(ClientConfig::default());25 let (network_handle, network_event_receiver) = network::start(ClientConfig::default());
11 26
12- application().run(|cx: &mut App| {27+ application()
13- init(cx);28+ .with_assets(AllAssets)
29+ .run(move |cx: &mut App| {
30+ init(cx);
31+ settings::apply(settings.theme, cx);
32+ gui::bind_keys(cx);
14 33
15- let window_bounds = Bounds::centered(None, size(px(800.0), px(600.0)), cx);34+ let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx);
16 35
17- let titlebar = TitlebarOptions {36+ let titlebar = TitlebarOptions {
18- title: Some(NAME.into()),37+ title: Some(NAME.into()),
19- ..Default::default()
20- };
21-
22- cx.open_window(
23- WindowOptions {
24- window_bounds: Some(WindowBounds::Windowed(window_bounds)),
25- titlebar: Some(titlebar),
26 ..Default::default()38 ..Default::default()
27- },39+ };
28- |window, cx| {40+
29- let view =41+ cx.open_window(
30- cx.new(|cx| Yumush::new(network_handle, network_event_receiver, window, cx));42+ WindowOptions {
31- cx.new(|cx| Root::new(view, window, cx))43+ window_bounds: Some(WindowBounds::Windowed(window_bounds)),
32- },44+ titlebar: Some(titlebar),
33- )45+ ..Default::default()
34- .unwrap();46+ },
47+ |window, cx| {
48+ let view = cx.new(|cx| {
49+ Yumush::new(network_handle, network_event_receiver, settings, window, cx)
50+ });
51+ cx.new(|cx| Root::new(view, window, cx))
52+ },
53+ )
54+ .unwrap();
35 55
36- cx.activate(true);56+ cx.activate(true);
37- });57+ });
38 }58 }
crates/client/src/media/convert.rsadded+59 -0
@@ -0,0 +1,59 @@
1+const MAX_WIDTH: u32 = 1280;
2+
3+pub fn yuv_to_bgra(
4+ y: &[u8],
5+ y_stride: usize,
6+ u: &[u8],
7+ v: &[u8],
8+ uv_stride: usize,
9+ width: u32,
10+ height: u32,
11+) -> Option<(u32, u32, Vec<u8>)> {
12+ if width == 0 || height == 0 {
13+ return None;
14+ }
15+ let step = width.div_ceil(MAX_WIDTH);
16+ let out_width = width.div_ceil(step);
17+ let out_height = height.div_ceil(step);
18+ let mut out = Vec::with_capacity(out_width as usize * out_height as usize * 4);
19+ for row in 0..out_height {
20+ let py = (row * step).min(height - 1) as usize;
21+ for column in 0..out_width {
22+ let px = (column * step).min(width - 1) as usize;
23+ let luma = sample(y, y_stride, px, py) - 16;
24+ let cb = sample(u, uv_stride, px / 2, py / 2) - 128;
25+ let cr = sample(v, uv_stride, px / 2, py / 2) - 128;
26+ let scaled = 298 * luma;
27+ let red = clamp((scaled + 459 * cr + 128) >> 8);
28+ let green = clamp((scaled - 55 * cb - 136 * cr + 128) >> 8);
29+ let blue = clamp((scaled + 541 * cb + 128) >> 8);
30+ out.extend_from_slice(&[blue, green, red, 255]);
31+ }
32+ }
33+ Some((out_width, out_height, out))
34+}
35+
36+fn sample(plane: &[u8], stride: usize, x: usize, y: usize) -> i32 {
37+ plane
38+ .get(y * stride + x)
39+ .map_or(0, |&value| i32::from(value))
40+}
41+
42+fn clamp(value: i32) -> u8 {
43+ value.clamp(0, 255) as u8
44+}
45+
46+#[cfg(test)]
47+mod tests {
48+ use super::*;
49+
50+ fn bgra(luma: u8) -> Option<(u32, u32, Vec<u8>)> {
51+ yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2)
52+ }
53+
54+ #[test]
55+ fn i420_limits_map_to_black_and_white_bgra() {
56+ assert_eq!(bgra(235), Some((2, 2, [255, 255, 255, 255].repeat(4))));
57+ assert_eq!(bgra(16), Some((2, 2, [0, 0, 0, 255].repeat(4))));
58+ }
59+}
crates/client/src/media/decode.rsadded+579 -0
@@ -0,0 +1,579 @@
1+use std::{
2+ collections::VecDeque,
3+ path::PathBuf,
4+ sync::{
5+ Arc, Mutex, MutexGuard, PoisonError,
6+ atomic::{AtomicBool, Ordering},
7+ },
8+ time::{Duration, Instant},
9+};
10+
11+use common::constant::VOICE_SAMPLE_RATE;
12+use ec_core::frame::{Frame as CodecFrame, PixelFormat, VideoFrame};
13+use ec_core::packet::Packet;
14+use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekMode};
15+use ec_core::timebase::{TimeBase, Timestamp};
16+use ec_h264::H264Decoder;
17+use ec_probe::{Reader, decoder::AudioDecoder};
18+use rtrb::Producer;
19+use tracing::warn;
20+
21+use super::{
22+ Frame, Tracks, convert,
23+ resample::{self, Resampler},
24+};
25+use crate::voice::Playback;
26+
27+pub const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 4;
28+const QUEUE_LIMIT: usize = 8;
29+const BACKLOG_LIMIT: usize = 600;
30+const LATE: f64 = 0.1;
31+const TICK: Duration = Duration::from_millis(4);
32+const MAX_PAD: usize = VOICE_SAMPLE_RATE as usize * 5;
33+
34+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35+pub enum State {
36+ Playing,
37+ Paused,
38+ Finished,
39+}
40+
41+#[derive(Debug)]
42+pub struct Clock {
43+ pub state: State,
44+ pub base: f64,
45+ pub written: u64,
46+ pub started: Option<Instant>,
47+ pub audio: bool,
48+}
49+
50+impl Clock {
51+ pub fn new(audio: bool) -> Clock {
52+ Clock {
53+ state: State::Paused,
54+ base: 0.0,
55+ written: 0,
56+ started: None,
57+ audio,
58+ }
59+ }
60+
61+ pub fn position(&self, queued: usize) -> f64 {
62+ let played = if self.audio {
63+ self.written.saturating_sub(queued as u64) as f64 / f64::from(VOICE_SAMPLE_RATE)
64+ } else {
65+ self.started
66+ .map_or(0.0, |started| started.elapsed().as_secs_f64())
67+ };
68+ self.base + played
69+ }
70+
71+ pub fn set(&mut self, state: State) {
72+ if !self.audio {
73+ self.base = self.position(0);
74+ }
75+ self.state = state;
76+ self.started = self.wall_start();
77+ }
78+
79+ pub fn rebase(&mut self, to: f64) {
80+ self.base = to;
81+ self.written = 0;
82+ self.started = self.wall_start();
83+ }
84+
85+ fn wall_start(&self) -> Option<Instant> {
86+ (self.state == State::Playing && !self.audio).then(Instant::now)
87+ }
88+}
89+
90+#[derive(Debug, Default)]
91+pub struct Video {
92+ pub queue: VecDeque<(f64, Frame)>,
93+ pub current: Option<Frame>,
94+ pub generation: u64,
95+}
96+
97+#[derive(Debug)]
98+pub struct Shared {
99+ pub stop: AtomicBool,
100+ pub seek: Mutex<Option<f64>>,
101+ pub clock: Mutex<Clock>,
102+ pub video: Mutex<Video>,
103+ pub stash: Mutex<VecDeque<f32>>,
104+}
105+
106+impl Shared {
107+ pub fn new(audio: bool) -> Shared {
108+ Shared {
109+ stop: AtomicBool::new(false),
110+ seek: Mutex::new(None),
111+ clock: Mutex::new(Clock::new(audio)),
112+ video: Mutex::new(Video::default()),
113+ stash: Mutex::new(VecDeque::new()),
114+ }
115+ }
116+}
117+
118+pub fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
119+ mutex.lock().unwrap_or_else(PoisonError::into_inner)
120+}
121+
122+fn wait() {
123+ std::thread::sleep(TICK);
124+}
125+
126+pub struct Picture {
127+ pub y: Vec<u8>,
128+ pub y_stride: usize,
129+ pub u: Vec<u8>,
130+ pub v: Vec<u8>,
131+ pub uv_stride: usize,
132+ pub width: u32,
133+ pub height: u32,
134+}
135+
136+pub enum VideoDecoder {
137+ H264(Box<H264Decoder>),
138+ Vp8(Box<ec_vp8::decode::Decoder>),
139+}
140+
141+impl VideoDecoder {
142+ pub fn new(params: &CodecParameters) -> Option<VideoDecoder> {
143+ match params.codec {
144+ CodecId::H264 => {
145+ let decoder = H264Decoder::new(params.clone()).ok()?;
146+ let i420 = decoder
147+ .codec_parameters()
148+ .video()
149+ .is_some_and(|video| video.format == Some(PixelFormat::I420));
150+ i420.then_some(VideoDecoder::H264(Box::new(decoder)))
151+ }
152+ CodecId::Vp8 => Some(VideoDecoder::Vp8(Box::new(ec_vp8::decode::Decoder::new()))),
153+ _ => None,
154+ }
155+ }
156+
157+ pub fn send(&mut self, packet: &Packet) -> Vec<(f64, Picture)> {
158+ match self {
159+ VideoDecoder::H264(decoder) => {
160+ if let Err(error) = decoder.send_packet(packet) {
161+ warn!("video packet skipped: {error}");
162+ return Vec::new();
163+ }
164+ drain_h264(decoder)
165+ }
166+ VideoDecoder::Vp8(decoder) => {
167+ let Some(pts) = packet
168+ .pts
169+ .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64())
170+ else {
171+ return Vec::new();
172+ };
173+ match decoder.decode(&packet.data) {
174+ Ok(Some(picture)) => vec![(
175+ pts,
176+ Picture {
177+ y: picture.y,
178+ y_stride: picture.stride,
179+ u: picture.u,
180+ v: picture.v,
181+ uv_stride: picture.uv_stride,
182+ width: u32::from(picture.width),
183+ height: u32::from(picture.height),
184+ },
185+ )],
186+ Ok(None) => Vec::new(),
187+ Err(error) => {
188+ warn!("video packet skipped: {error}");
189+ Vec::new()
190+ }
191+ }
192+ }
193+ }
194+ }
195+
196+ pub fn flush(&mut self) -> Vec<(f64, Picture)> {
197+ match self {
198+ VideoDecoder::H264(decoder) => {
199+ let _ = CodecDecoder::flush(decoder.as_mut());
200+ drain_h264(decoder)
201+ }
202+ VideoDecoder::Vp8(_) => Vec::new(),
203+ }
204+ }
205+
206+ pub fn reset(&mut self) {
207+ match self {
208+ VideoDecoder::H264(decoder) => CodecDecoder::reset(decoder.as_mut()),
209+ VideoDecoder::Vp8(decoder) => **decoder = ec_vp8::decode::Decoder::new(),
210+ }
211+ }
212+}
213+
214+enum Queued {
215+ Packet(Packet),
216+ Flush,
217+}
218+
219+pub struct Worker {
220+ shared: Arc<Shared>,
221+ path: PathBuf,
222+ reader: Reader,
223+ playback: Playback,
224+ producer: Option<Producer<f32>>,
225+ video_index: Option<u32>,
226+ video: Option<VideoDecoder>,
227+ backlog: VecDeque<Queued>,
228+ audio_index: Option<u32>,
229+ audio: Option<AudioDecoder>,
230+ pending: VecDeque<f32>,
231+ resampler: Resampler,
232+ align: Option<f64>,
233+ skip: usize,
234+ scratch: Vec<f32>,
235+ eof: bool,
236+}
237+
238+impl Worker {
239+ pub fn new(
240+ shared: Arc<Shared>,
241+ path: PathBuf,
242+ reader: Reader,
243+ playback: Playback,
244+ producer: Option<Producer<f32>>,
245+ tracks: Tracks,
246+ ) -> Worker {
247+ Worker {
248+ shared,
249+ path,
250+ reader,
251+ playback,
252+ producer,
253+ video_index: tracks.video.as_ref().map(|(index, _, _)| *index),
254+ video: tracks.video.map(|(_, _, decoder)| decoder),
255+ backlog: VecDeque::new(),
256+ audio_index: tracks.audio.as_ref().map(|(index, _)| *index),
257+ audio: tracks.audio.map(|(_, decoder)| decoder),
258+ pending: VecDeque::new(),
259+ resampler: Resampler::default(),
260+ align: Some(0.0),
261+ skip: 0,
262+ scratch: Vec::new(),
263+ eof: false,
264+ }
265+ }
266+
267+ pub fn run(mut self) {
268+ while !self.shared.stop.load(Ordering::Relaxed) {
269+ let seek = lock(&self.shared.seek).take();
270+ if let Some(to) = seek {
271+ self.seek(to);
272+ continue;
273+ }
274+ let state = lock(&self.shared.clock).state;
275+ match state {
276+ State::Playing => self.play_step(),
277+ State::Paused => {
278+ if self.eof || self.primed() {
279+ wait();
280+ } else {
281+ self.decode_backlog();
282+ self.step();
283+ }
284+ }
285+ State::Finished => wait(),
286+ }
287+ }
288+ }
289+
290+ fn play_step(&mut self) {
291+ self.feed();
292+ self.decode_backlog();
293+ if self.eof {
294+ self.finish();
295+ }
296+ if self.eof || self.buffered() {
297+ wait();
298+ } else {
299+ self.fill();
300+ }
301+ }
302+
303+ fn buffered(&self) -> bool {
304+ self.pending.len() >= RING_SAMPLES
305+ }
306+
307+ fn fill(&mut self) {
308+ while !self.eof
309+ && !self.buffered()
310+ && self.backlog.len() < BACKLOG_LIMIT
311+ && (self.producer.is_some() || self.backlog.is_empty())
312+ {
313+ self.step();
314+ }
315+ }
316+
317+ fn primed(&self) -> bool {
318+ let base = lock(&self.shared.clock).base;
319+ self.video.is_none()
320+ || lock(&self.shared.video)
321+ .queue
322+ .back()
323+ .is_some_and(|(pts, _)| *pts >= base)
324+ }
325+
326+ fn ring_empty(&self) -> bool {
327+ self.producer
328+ .as_ref()
329+ .is_none_or(|producer| producer.slots() == RING_SAMPLES)
330+ }
331+
332+ fn feed(&mut self) {
333+ let Some(producer) = self.producer.as_mut() else {
334+ return;
335+ };
336+ let mut clock = lock(&self.shared.clock);
337+ if clock.state != State::Playing {
338+ return;
339+ }
340+ let mut stash = lock(&self.shared.stash);
341+ while let Some(sample) = stash.pop_back() {
342+ self.pending.push_front(sample);
343+ }
344+ drop(stash);
345+ while let Some(&sample) = self.pending.front() {
346+ if producer.push(sample).is_err() {
347+ break;
348+ }
349+ self.pending.pop_front();
350+ clock.written += 1;
351+ }
352+ }
353+
354+ fn finish(&self) {
355+ let mut clock = lock(&self.shared.clock);
356+ if clock.state == State::Playing
357+ && self.pending.is_empty()
358+ && self.ring_empty()
359+ && self.backlog.is_empty()
360+ && lock(&self.shared.seek).is_none()
361+ && lock(&self.shared.video).queue.is_empty()
362+ {
363+ clock.set(State::Finished);
364+ }
365+ }
366+
367+ fn step(&mut self) {
368+ if self.backlog.len() >= BACKLOG_LIMIT {
369+ wait();
370+ return;
371+ }
372+ match self.reader.next_packet() {
373+ Ok(packet) => self.packet(packet),
374+ Err(error) => {
375+ if !error.is_eof() {
376+ warn!("media demux ended: {error}");
377+ }
378+ self.end_of_input();
379+ }
380+ }
381+ }
382+
383+ fn packet(&mut self, packet: Packet) {
384+ if Some(packet.stream) == self.video_index && self.video.is_some() {
385+ self.backlog.push_back(Queued::Packet(packet));
386+ } else if Some(packet.stream) == self.audio_index {
387+ self.audio_packet(&packet);
388+ }
389+ }
390+
391+ fn decode_backlog(&mut self) {
392+ let Some(video) = self.video.as_mut() else {
393+ return;
394+ };
395+ if lock(&self.shared.video).queue.len() >= QUEUE_LIMIT {
396+ return;
397+ }
398+ let pictures = match self.backlog.pop_front() {
399+ Some(Queued::Packet(packet)) => video.send(&packet),
400+ Some(Queued::Flush) => video.flush(),
401+ None => return,
402+ };
403+ let position = position(&self.shared, &self.playback);
404+ for (pts, picture) in pictures {
405+ if pts + LATE >= position {
406+ show(&self.shared, pts, picture);
407+ }
408+ }
409+ }
410+
411+ fn audio_packet(&mut self, packet: &Packet) {
412+ if self.producer.is_none() {
413+ return;
414+ }
415+ let Some(audio) = self.audio.as_mut() else {
416+ return;
417+ };
418+ let mut samples = std::mem::take(&mut self.scratch);
419+ if let Err(error) = audio.decode(packet, &mut samples) {
420+ warn!("audio packet skipped: {error}");
421+ } else {
422+ let (rate, channels) = (audio.sample_rate(), audio.channels());
423+ let pts = packet
424+ .pts
425+ .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64());
426+ self.queue_audio(&samples, channels, rate, pts);
427+ }
428+ self.scratch = samples;
429+ }
430+
431+ fn queue_audio(&mut self, interleaved: &[f32], channels: usize, rate: u32, pts: Option<f64>) {
432+ if rate == 0 {
433+ return;
434+ }
435+ let mono = resample::downmix(interleaved, channels);
436+ let mut out = self.resampler.process(&mono, rate);
437+ if let Some(target) = self.align.filter(|_| !out.is_empty()) {
438+ self.align = None;
439+ self.align_to(&mut out, target, pts.unwrap_or(target));
440+ }
441+ let dropped = self.skip.min(out.len());
442+ out.drain(..dropped);
443+ self.skip -= dropped;
444+ self.pending.extend(out);
445+ }
446+
447+ fn align_to(&mut self, out: &mut Vec<f32>, target: f64, pts: f64) {
448+ let shift = ((target - pts) * f64::from(VOICE_SAMPLE_RATE)).round() as i64;
449+ if shift > 0 {
450+ self.skip = shift as usize;
451+ } else if shift < 0 {
452+ let pad = ((-shift) as usize).min(MAX_PAD);
453+ out.splice(0..0, std::iter::repeat_n(0.0, pad));
454+ }
455+ }
456+
457+ fn end_of_input(&mut self) {
458+ self.eof = true;
459+ if self.video.is_some() {
460+ self.backlog.push_back(Queued::Flush);
461+ }
462+ if self.producer.is_some() {
463+ let mut samples = std::mem::take(&mut self.scratch);
464+ let params = self.audio.as_mut().and_then(|audio| {
465+ audio
466+ .flush(&mut samples)
467+ .ok()
468+ .map(|()| (audio.sample_rate(), audio.channels()))
469+ });
470+ if let Some((rate, channels)) = params {
471+ self.queue_audio(&samples, channels, rate, None);
472+ }
473+ self.scratch = samples;
474+ }
475+ }
476+
477+ fn seek(&mut self, to: f64) {
478+ self.pending.clear();
479+ self.scratch.clear();
480+ self.resampler = Resampler::default();
481+ self.align = Some(to);
482+ self.skip = 0;
483+ self.eof = false;
484+ self.backlog.clear();
485+ if let Some(video) = self.video.as_mut() {
486+ video.reset();
487+ }
488+ if let Some(audio) = self.audio.as_mut() {
489+ audio.reset();
490+ }
491+ lock(&self.shared.video).queue.clear();
492+ {
493+ let mut clock = lock(&self.shared.clock);
494+ let mut playback = lock(&self.playback);
495+ while playback.pop().is_ok() {}
496+ drop(playback);
497+ lock(&self.shared.stash).clear();
498+ clock.rebase(to);
499+ }
500+ if let Some(stream) = self.video_index.or(self.audio_index) {
501+ let at = Timestamp::new((to * 1_000_000.0) as i64, TimeBase::MICROS);
502+ if self.reader.seek(stream, at, SeekMode::SyncBefore).is_err() {
503+ self.restart();
504+ }
505+ }
506+ }
507+
508+ fn restart(&mut self) {
509+ match Reader::open(&self.path) {
510+ Ok(reader) => self.reader = reader,
511+ Err(error) => {
512+ warn!("media restart failed: {error}");
513+ self.eof = true;
514+ }
515+ }
516+ }
517+}
518+
519+pub fn position(shared: &Shared, playback: &Playback) -> f64 {
520+ let clock = lock(&shared.clock);
521+ let queued = if clock.audio {
522+ lock(playback).slots()
523+ } else {
524+ 0
525+ };
526+ clock.position(queued).max(0.0)
527+}
528+
529+fn show(shared: &Shared, pts: f64, picture: Picture) {
530+ let Some((width, height, bgra)) = convert::yuv_to_bgra(
531+ &picture.y,
532+ picture.y_stride,
533+ &picture.u,
534+ &picture.v,
535+ picture.uv_stride,
536+ picture.width,
537+ picture.height,
538+ ) else {
539+ return;
540+ };
541+ let frame = Frame {
542+ width,
543+ height,
544+ bgra: Arc::new(bgra),
545+ generation: 0,
546+ };
547+ lock(&shared.video).queue.push_back((pts, frame));
548+}
549+
550+fn drain_h264(decoder: &mut H264Decoder) -> Vec<(f64, Picture)> {
551+ std::iter::from_fn(|| decoder.receive_frame().ok())
552+ .filter_map(|frame| match frame {
553+ CodecFrame::Video(picture) => h264_picture(&picture),
554+ CodecFrame::Audio(_) => None,
555+ })
556+ .collect()
557+}
558+
559+fn h264_picture(frame: &VideoFrame) -> Option<(f64, Picture)> {
560+ let pts = frame.pts?.as_secs_f64();
561+ if frame.format != PixelFormat::I420 {
562+ return None;
563+ }
564+ let [y, u, v] = frame.planes.as_slice() else {
565+ return None;
566+ };
567+ Some((
568+ pts,
569+ Picture {
570+ y: y.data.to_vec(),
571+ y_stride: y.stride,
572+ u: u.data.to_vec(),
573+ v: v.data.to_vec(),
574+ uv_stride: u.stride,
575+ width: frame.width,
576+ height: frame.height,
577+ },
578+ ))
579+}
crates/client/src/media/mod.rsadded+307 -0
@@ -0,0 +1,307 @@
1+mod convert;
2+mod decode;
3+mod resample;
4+
5+use std::{
6+ fmt,
7+ path::Path,
8+ sync::{Arc, Mutex, atomic::Ordering},
9+ thread::JoinHandle,
10+ time::Duration,
11+};
12+
13+use ec_core::registry::MediaType;
14+use ec_probe::{Reader, decoder::AudioDecoder};
15+use rtrb::RingBuffer;
16+
17+use crate::voice::{
18+ Playback,
19+ audio::{self, Audio, Choice},
20+};
21+use decode::{RING_SAMPLES, Shared, State, VideoDecoder, Worker, lock};
22+
23+#[derive(Debug, Clone)]
24+pub struct Frame {
25+ pub width: u32,
26+ pub height: u32,
27+ pub bgra: Arc<Vec<u8>>,
28+ pub generation: u64,
29+}
30+
31+#[derive(Debug, Clone, Copy, PartialEq)]
32+pub struct Info {
33+ pub duration: Option<Duration>,
34+ pub video: Option<(u32, u32)>,
35+ pub audio: bool,
36+}
37+
38+#[derive(Debug)]
39+pub enum MediaError {
40+ Unsupported,
41+ Io(std::io::Error),
42+ Decode(String),
43+}
44+
45+impl fmt::Display for MediaError {
46+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47+ match self {
48+ MediaError::Unsupported => write!(f, "no playable video or audio track"),
49+ MediaError::Io(error) => write!(f, "{error}"),
50+ MediaError::Decode(message) => write!(f, "{message}"),
51+ }
52+ }
53+}
54+
55+impl std::error::Error for MediaError {}
56+
57+impl From<std::io::Error> for MediaError {
58+ fn from(error: std::io::Error) -> MediaError {
59+ MediaError::Io(error)
60+ }
61+}
62+
63+impl From<ec_core::Error> for MediaError {
64+ fn from(error: ec_core::Error) -> MediaError {
65+ match error {
66+ ec_core::Error::Unsupported { .. } => MediaError::Unsupported,
67+ ec_core::Error::Io(error) => MediaError::Io(error),
68+ other => MediaError::Decode(other.to_string()),
69+ }
70+ }
71+}
72+
73+pub struct Tracks {
74+ video: Option<(u32, (u32, u32), VideoDecoder)>,
75+ audio: Option<(u32, AudioDecoder)>,
76+}
77+
78+impl Tracks {
79+ fn find(reader: &Reader) -> Tracks {
80+ let video = reader.streams().iter().find_map(|stream| {
81+ let size = stream
82+ .params
83+ .video()
84+ .map(|video| (video.width, video.height))?;
85+ VideoDecoder::new(&stream.params).map(|decoder| (stream.index, size, decoder))
86+ });
87+ let audio = reader
88+ .streams()
89+ .iter()
90+ .filter(|stream| stream.params.codec.media_type() == MediaType::Audio)
91+ .find_map(|stream| {
92+ AudioDecoder::new(&stream.params)
93+ .ok()
94+ .map(|decoder| (stream.index, decoder))
95+ });
96+ Tracks { video, audio }
97+ }
98+}
99+
100+impl Info {
101+ fn of(path: &Path, reader: &Reader, tracks: &Tracks) -> Info {
102+ let stated = reader
103+ .duration()
104+ .map(|length| length.as_secs_f64())
105+ .filter(|seconds| *seconds > 0.0);
106+ let scanned = || tracks.video.is_none().then(|| flac_end(path)).flatten();
107+
108+ Info {
109+ duration: stated
110+ .or_else(scanned)
111+ .map(|seconds| Duration::from_secs_f64(seconds.max(0.0))),
112+ video: tracks.video.as_ref().map(|(_, size, _)| *size),
113+ audio: tracks.audio.is_some(),
114+ }
115+ }
116+}
117+
118+pub fn probe(path: &Path) -> Result<Info, MediaError> {
119+ let reader = Reader::open(path)?;
120+ let tracks = Tracks::find(&reader);
121+ if tracks.video.is_none() && tracks.audio.is_none() {
122+ return Err(MediaError::Unsupported);
123+ }
124+ Ok(Info::of(path, &reader, &tracks))
125+}
126+
127+const FLAC_TAIL: u64 = 256 * 1024;
128+
129+fn flac_end(path: &Path) -> Option<f64> {
130+ use std::io::{Read, Seek, SeekFrom};
131+
132+ let mut file = std::fs::File::open(path).ok()?;
133+ let mut head = [0u8; 42];
134+ file.read_exact(&mut head).ok()?;
135+ if &head[..4] != b"fLaC" {
136+ return None;
137+ }
138+ let info = ec_flac::StreamInfo::parse(&head[8..]).ok()?;
139+
140+ let length = file.metadata().ok()?.len();
141+ let tail = length.min(FLAC_TAIL);
142+ file.seek(SeekFrom::Start(length - tail)).ok()?;
143+ let mut data = Vec::with_capacity(tail as usize);
144+ file.read_to_end(&mut data).ok()?;
145+
146+ let mut last = None;
147+ let mut at = 0;
148+ while let Some(found) = ec_flac::decode::find_frame_sync(&data, at, Some(&info)) {
149+ last = Some(found);
150+ at = found + 1;
151+ }
152+ let mut reader = ec_core::BitReader::new(&data[last?..]);
153+ let header = ec_flac::decode::parse_frame_header(&mut reader, Some(&info)).ok()?;
154+ let first = header.first_sample(Some(info.max_block_size as usize))?;
155+
156+ Some((first + header.block_size as u64) as f64 / info.sample_rate as f64)
157+}
158+
159+pub struct Player {
160+ info: Info,
161+ shared: Arc<Shared>,
162+ playback: Playback,
163+ _audio: Audio,
164+ worker: Option<JoinHandle<()>>,
165+}
166+
167+impl Player {
168+ pub fn open(path: &Path, choice: Choice) -> Result<Player, MediaError> {
169+ let reader = Reader::open(path)?;
170+ let tracks = Tracks::find(&reader);
171+ if tracks.video.is_none() && tracks.audio.is_none() {
172+ return Err(MediaError::Unsupported);
173+ }
174+ let info = Info::of(path, &reader, &tracks);
175+ let (producer, consumer) = RingBuffer::new(RING_SAMPLES);
176+ let playback: Playback = Arc::new(Mutex::new(consumer));
177+ let audio = if tracks.audio.is_some() {
178+ audio::start(None, playback.clone(), choice)
179+ } else {
180+ Audio::Silent
181+ };
182+ let audio_on = tracks.audio.is_some() && !matches!(audio, Audio::Silent);
183+ let shared = Arc::new(Shared::new(audio_on));
184+ let worker = Worker::new(
185+ shared.clone(),
186+ path.to_path_buf(),
187+ reader,
188+ playback.clone(),
189+ audio_on.then_some(producer),
190+ tracks,
191+ );
192+ let handle = std::thread::Builder::new()
193+ .name("media-decode".to_string())
194+ .spawn(move || worker.run())?;
195+ Ok(Player {
196+ info,
197+ shared,
198+ playback,
199+ _audio: audio,
200+ worker: Some(handle),
201+ })
202+ }
203+
204+ pub fn play(&self) {
205+ if self.finished() {
206+ *lock(&self.shared.seek) = Some(0.0);
207+ }
208+ let mut clock = lock(&self.shared.clock);
209+ if clock.state != State::Playing {
210+ clock.set(State::Playing);
211+ }
212+ }
213+
214+ pub fn pause(&self) {
215+ let mut clock = lock(&self.shared.clock);
216+ if clock.state != State::Playing {
217+ return;
218+ }
219+ if clock.audio {
220+ let mut playback = lock(&self.playback);
221+ let mut stash = lock(&self.shared.stash);
222+ while let Ok(sample) = playback.pop() {
223+ stash.push_back(sample);
224+ clock.written = clock.written.saturating_sub(1);
225+ }
226+ }
227+ clock.set(State::Paused);
228+ }
229+
230+ pub fn toggle(&self) {
231+ if self.playing() {
232+ self.pause();
233+ } else {
234+ self.play();
235+ }
236+ }
237+
238+ pub fn seek(&self, to: Duration) {
239+ *lock(&self.shared.seek) = Some(to.as_secs_f64());
240+ }
241+
242+ pub fn playing(&self) -> bool {
243+ lock(&self.shared.clock).state == State::Playing
244+ }
245+
246+ pub fn finished(&self) -> bool {
247+ lock(&self.shared.clock).state == State::Finished
248+ }
249+
250+ pub fn position(&self) -> Duration {
251+ Duration::from_secs_f64(decode::position(&self.shared, &self.playback))
252+ }
253+
254+ pub fn info(&self) -> &Info {
255+ &self.info
256+ }
257+
258+ pub fn frame(&self) -> Option<Frame> {
259+ let position = self.position().as_secs_f64();
260+ let mut video = lock(&self.shared.video);
261+ while let Some(pts) = video.queue.front().map(|(pts, _)| *pts) {
262+ if pts > position && video.current.is_some() {
263+ break;
264+ }
265+ let Some((_, mut frame)) = video.queue.pop_front() else {
266+ break;
267+ };
268+ video.generation += 1;
269+ frame.generation = video.generation;
270+ video.current = Some(frame);
271+ }
272+ video.current.clone()
273+ }
274+}
275+
276+impl Drop for Player {
277+ fn drop(&mut self) {
278+ self.shared.stop.store(true, Ordering::Relaxed);
279+ if let Some(worker) = self.worker.take() {
280+ let _ = worker.join();
281+ }
282+ }
283+}
284+
285+#[cfg(test)]
286+mod tests {
287+ use super::*;
288+
289+ #[test]
290+ fn random_bytes_are_unsupported() {
291+ let mut seed = 0x2545_f491_4f6c_dd1du64;
292+ let bytes: Vec<u8> = (0..4096)
293+ .map(|_| {
294+ seed ^= seed << 13;
295+ seed ^= seed >> 7;
296+ seed ^= seed << 17;
297+ seed as u8
298+ })
299+ .collect();
300+ let path =
301+ std::env::temp_dir().join(format!("yumush-media-probe-{}.bin", std::process::id()));
302+ std::fs::write(&path, &bytes).unwrap();
303+ let result = probe(&path);
304+ let _ = std::fs::remove_file(&path);
305+ assert!(matches!(result, Err(MediaError::Unsupported)));
306+ }
307+}
crates/client/src/media/resample.rsadded+40 -0
@@ -0,0 +1,40 @@
1+use common::constant::VOICE_SAMPLE_RATE;
2+
3+pub fn downmix(interleaved: &[f32], channels: usize) -> Vec<f32> {
4+ interleaved
5+ .chunks(channels.max(1))
6+ .map(|frame| frame.iter().sum::<f32>() / frame.len() as f32)
7+ .collect()
8+}
9+
10+#[derive(Debug, Default)]
11+pub struct Resampler {
12+ last: f32,
13+ position: f64,
14+}
15+
16+impl Resampler {
17+ pub fn process(&mut self, input: &[f32], rate: u32) -> Vec<f32> {
18+ let step = f64::from(rate) / f64::from(VOICE_SAMPLE_RATE);
19+ let count = input.len() as f64;
20+ let mut out = Vec::new();
21+ let mut position = self.position;
22+ while position < count {
23+ let index = position.floor() as usize;
24+ let fraction = (position - index as f64) as f32;
25+ let before = at(self.last, input, index);
26+ let after = at(self.last, input, index + 1);
27+ out.push(before + (after - before) * fraction);
28+ position += step;
29+ }
30+ self.position = position - count;
31+ if let Some(&last) = input.last() {
32+ self.last = last;
33+ }
34+ out
35+ }
36+}
37+
38+fn at(last: f32, input: &[f32], index: usize) -> f32 {
39+ if index == 0 { last } else { input[index - 1] }
40+}
crates/client/src/network.rsmodified+728 -45
@@ -1,32 +1,47 @@
1-use std::sync::Arc;1+use std::{
2-use std::time::Duration;2+ path::{Path, PathBuf},
3+ sync::{Arc, Mutex},
4+ time::Duration,
5+};
3 6
4 use common::{7 use common::{
8+ constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_BYTES},
5 error::Error,9 error::Error,
6 event::Event,10 event::Event,
7- model::{Community, Message, User},11+ model::{
8- network::{receive_event, send_request},12+ Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, User,
9- request::Request,13+ },
14+ network::{
15+ DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,
16+ receive_download_status, receive_event, send_download_request, send_request,
17+ send_stream_kind, send_upload_header,
18+ },
19+ request::{DownloadRequest, Request, UploadHeader},
10 response::Response,20 response::Response,
11 validate::{21 validate::{
12- validate_community_name, validate_message_body, validate_password, validate_username,22+ validate_attachment_name, validate_attachment_size, validate_avatar_size,
23+ validate_community_name, validate_forward, validate_message_body, validate_new_message,
24+ validate_password, validate_reason, validate_status, validate_username,
13 },25 },
14 };26 };
27+use quinn::Endpoint;
15 #[cfg(debug_assertions)]28 #[cfg(debug_assertions)]
16 use quinn::{29 use quinn::{
17 crypto::rustls::QuicClientConfig,30 crypto::rustls::QuicClientConfig,
18 rustls::{31 rustls::{
19- self,32+ self, DigitallySignedStruct, SignatureScheme,
20 client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},33 client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
21 pki_types::{CertificateDer, ServerName, UnixTime},34 pki_types::{CertificateDer, ServerName, UnixTime},
22- DigitallySignedStruct, SignatureScheme,
23 },35 },
24 };36 };
25-use quinn::Endpoint;
26 use tokio::sync::{mpsc, oneshot};37 use tokio::sync::{mpsc, oneshot};
27 use tracing::{info, warn};38 use tracing::{info, warn};
28 39
29-use crate::ClientConfig;40+use crate::{
41+ ClientConfig,
42+ settings::VoiceSettings,
43+ voice::{self, Voice},
44+};
30 45
31 const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1);46 const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1);
32 const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);47 const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);
@@ -34,23 +49,41 @@ const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3);
34 const CHANNEL_SIZE: usize = 32;49 const CHANNEL_SIZE: usize = 32;
35 const RECONNECT_DELAY: Duration = Duration::from_secs(1);50 const RECONNECT_DELAY: Duration = Duration::from_secs(1);
36 51
52+type SharedVoice = Arc<Mutex<Option<Voice>>>;
53+type SharedSettings = Arc<Mutex<VoiceSettings>>;
54+
37 #[derive(Debug)]55 #[derive(Debug)]
38 pub enum NetworkEvent {56 pub enum NetworkEvent {
39 Connected,57 Connected,
40 Disconnected(Error),58 Disconnected(Error),
41 SessionLost,59 SessionLost,
42- Pushed(Event),60+ Pushed(Box<Event>),
43 }61 }
44 62
45 #[derive(Debug)]63 #[derive(Debug)]
46-struct Command {64+enum Command {
47- request: Request,65+ Request {
48- reply: oneshot::Sender<Result<Response, Error>>,66+ request: Request,
67+ reply: oneshot::Sender<Result<Response, Error>>,
68+ },
69+ Upload {
70+ community_id: String,
71+ path: PathBuf,
72+ reply: oneshot::Sender<Result<Attachment, Error>>,
73+ },
74+ Download {
75+ attachment_id: String,
76+ thumbnail: bool,
77+ reply: oneshot::Sender<Result<Vec<u8>, Error>>,
78+ },
49 }79 }
50 80
51-#[derive(Debug, Clone)]81+#[derive(Clone)]
52 pub struct NetworkHandle {82 pub struct NetworkHandle {
53 command_sender: mpsc::Sender<Command>,83 command_sender: mpsc::Sender<Command>,
84+ voice: SharedVoice,
85+ mic_test: SharedVoice,
86+ voice_settings: SharedSettings,
54 }87 }
55 88
56 impl NetworkHandle {89 impl NetworkHandle {
@@ -58,7 +91,7 @@ impl NetworkHandle {
58 let (reply, response) = oneshot::channel();91 let (reply, response) = oneshot::channel();
59 92
60 self.command_sender93 self.command_sender
61- .send(Command { request, reply })94+ .send(Command::Request { request, reply })
62 .await95 .await
63 .map_err(|_| Error::ChannelClosed)?;96 .map_err(|_| Error::ChannelClosed)?;
64 97
@@ -68,14 +101,28 @@ impl NetworkHandle {
68 }101 }
69 }102 }
70 103
71- async fn sign_in(&self, request: Request) -> Result<User, Error> {104+ async fn sign_in(&self, request: Request) -> Result<(User, String), Error> {
72 match self.request(request).await? {105 match self.request(request).await? {
73- Response::Session { user, .. } => Ok(user),106+ Response::Session { user, token } => Ok((user, token)),
74 _ => Err(Error::Server),107 _ => Err(Error::Server),
75 }108 }
76 }109 }
77 110
78- pub async fn register(&self, username: &str, password: &str) -> Result<User, Error> {111+ pub async fn resume(&self, token: &str) -> Result<(User, String), Error> {
112+ self.sign_in(Request::Resume {
113+ token: token.to_string(),
114+ })
115+ .await
116+ }
117+
118+ pub async fn detach(&self) -> Result<(), Error> {
119+ match self.request(Request::Detach).await? {
120+ Response::Done => Ok(()),
121+ _ => Err(Error::Server),
122+ }
123+ }
124+
125+ pub async fn register(&self, username: &str, password: &str) -> Result<(User, String), Error> {
79 validate_username(username)?;126 validate_username(username)?;
80 validate_password(password)?;127 validate_password(password)?;
81 128
@@ -86,7 +133,7 @@ impl NetworkHandle {
86 .await133 .await
87 }134 }
88 135
89- pub async fn login(&self, username: &str, password: &str) -> Result<User, Error> {136+ pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Error> {
90 validate_username(username)?;137 validate_username(username)?;
91 validate_password(password)?;138 validate_password(password)?;
92 139
@@ -104,6 +151,32 @@ impl NetworkHandle {
104 }151 }
105 }152 }
106 153
154+ pub async fn update_user(&self, username: &str) -> Result<User, Error> {
155+ validate_username(username)?;
156+
157+ match self
158+ .request(Request::UpdateUser {
159+ username: username.to_string(),
160+ })
161+ .await?
162+ {
163+ Response::User(user) => Ok(user),
164+ _ => Err(Error::Server),
165+ }
166+ }
167+
168+ pub async fn delete_user(&self, user_id: &str) -> Result<(), Error> {
169+ match self
170+ .request(Request::DeleteUser {
171+ user_id: user_id.to_string(),
172+ })
173+ .await?
174+ {
175+ Response::User(_) => Ok(()),
176+ _ => Err(Error::Server),
177+ }
178+ }
179+
107 pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {180 pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {
108 match self181 match self
109 .request(Request::ReadUser {182 .request(Request::ReadUser {
@@ -130,10 +203,17 @@ impl NetworkHandle {
130 }203 }
131 }204 }
132 205
133- pub async fn join_community(&self, community_id: &str) -> Result<Community, Error> {206+ pub async fn update_community(
207+ &self,
208+ community_id: &str,
209+ name: &str,
210+ ) -> Result<Community, Error> {
211+ validate_community_name(name)?;
212+
134 match self213 match self
135- .request(Request::JoinCommunity {214+ .request(Request::UpdateCommunity {
136 community_id: community_id.to_string(),215 community_id: community_id.to_string(),
216+ name: name.to_string(),
137 })217 })
138 .await?218 .await?
139 {219 {
@@ -142,28 +222,26 @@ impl NetworkHandle {
142 }222 }
143 }223 }
144 224
145- pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> {225+ pub async fn delete_community(&self, community_id: &str) -> Result<(), Error> {
146 match self226 match self
147- .request(Request::LeaveCommunity {227+ .request(Request::DeleteCommunity {
148 community_id: community_id.to_string(),228 community_id: community_id.to_string(),
149 })229 })
150 .await?230 .await?
151 {231 {
152- Response::Done => Ok(()),232+ Response::Community(_) => Ok(()),
153 _ => Err(Error::Server),233 _ => Err(Error::Server),
154 }234 }
155 }235 }
156 236
157- pub async fn search_community(&self, name: &str) -> Result<Vec<Community>, Error> {237+ pub async fn leave_community(&self, community_id: &str) -> Result<(), Error> {
158- validate_community_name(name)?;
159-
160 match self238 match self
161- .request(Request::SearchCommunity {239+ .request(Request::LeaveCommunity {
162- name: name.to_string(),240+ community_id: community_id.to_string(),
163 })241 })
164 .await?242 .await?
165 {243 {
166- Response::Communities(communities) => Ok(communities),244+ Response::Done => Ok(()),
167 _ => Err(Error::Server),245 _ => Err(Error::Server),
168 }246 }
169 }247 }
@@ -175,25 +253,156 @@ impl NetworkHandle {
175 }253 }
176 }254 }
177 255
178- pub async fn members(&self, community_id: &str) -> Result<Vec<User>, Error> {256+ pub async fn members(&self, community_id: &str) -> Result<Vec<Member>, Error> {
179 match self257 match self
180 .request(Request::Members {258 .request(Request::Members {
181 community_id: community_id.to_string(),259 community_id: community_id.to_string(),
182 })260 })
183 .await?261 .await?
184 {262 {
185- Response::Members(users) => Ok(users),263+ Response::Members(members) => Ok(members),
186 _ => Err(Error::Server),264 _ => Err(Error::Server),
187 }265 }
188 }266 }
189 267
190- pub async fn create_message(&self, community_id: &str, body: &str) -> Result<Message, Error> {268+ pub async fn kick(
191- validate_message_body(body)?;269+ &self,
270+ community_id: &str,
271+ user_id: &str,
272+ reason: Option<&str>,
273+ ) -> Result<(), Error> {
274+ validate_reason(reason)?;
275+ match self
276+ .request(Request::Kick {
277+ community_id: community_id.to_string(),
278+ user_id: user_id.to_string(),
279+ reason: reason.map(str::to_string),
280+ })
281+ .await?
282+ {
283+ Response::Done => Ok(()),
284+ _ => Err(Error::Server),
285+ }
286+ }
287+
288+ pub async fn ban(
289+ &self,
290+ community_id: &str,
291+ user_id: &str,
292+ reason: Option<&str>,
293+ ) -> Result<(), Error> {
294+ validate_reason(reason)?;
295+ match self
296+ .request(Request::Ban {
297+ community_id: community_id.to_string(),
298+ user_id: user_id.to_string(),
299+ reason: reason.map(str::to_string),
300+ })
301+ .await?
302+ {
303+ Response::Done => Ok(()),
304+ _ => Err(Error::Server),
305+ }
306+ }
307+
308+ pub async fn unban(&self, community_id: &str, user_id: &str) -> Result<(), Error> {
309+ match self
310+ .request(Request::Unban {
311+ community_id: community_id.to_string(),
312+ user_id: user_id.to_string(),
313+ })
314+ .await?
315+ {
316+ Response::Done => Ok(()),
317+ _ => Err(Error::Server),
318+ }
319+ }
320+
321+ pub async fn bans(&self, community_id: &str) -> Result<Vec<Ban>, Error> {
322+ match self
323+ .request(Request::Bans {
324+ community_id: community_id.to_string(),
325+ })
326+ .await?
327+ {
328+ Response::Bans(users) => Ok(users),
329+ _ => Err(Error::Server),
330+ }
331+ }
332+
333+ pub async fn logs(&self, community_id: &str) -> Result<Vec<LogEntry>, Error> {
334+ match self
335+ .request(Request::Logs {
336+ community_id: community_id.to_string(),
337+ })
338+ .await?
339+ {
340+ Response::Logs(entries) => Ok(entries),
341+ _ => Err(Error::Server),
342+ }
343+ }
344+
345+ pub async fn set_rank(
346+ &self,
347+ community_id: &str,
348+ user_id: &str,
349+ rank: Rank,
350+ ) -> Result<(), Error> {
351+ match self
352+ .request(Request::SetRank {
353+ community_id: community_id.to_string(),
354+ user_id: user_id.to_string(),
355+ rank,
356+ })
357+ .await?
358+ {
359+ Response::Done => Ok(()),
360+ _ => Err(Error::Server),
361+ }
362+ }
363+
364+ pub async fn delete_message(&self, message_id: &str) -> Result<(), Error> {
365+ match self
366+ .request(Request::DeleteMessage {
367+ message_id: message_id.to_string(),
368+ })
369+ .await?
370+ {
371+ Response::Message(_) => Ok(()),
372+ _ => Err(Error::Server),
373+ }
374+ }
375+
376+ pub async fn create_message(
377+ &self,
378+ community_id: &str,
379+ body: &str,
380+ attachments: Vec<String>,
381+ reply_to: Option<String>,
382+ ) -> Result<Message, Error> {
383+ validate_new_message(body, attachments.len())?;
192 384
193 match self385 match self
194 .request(Request::CreateMessage {386 .request(Request::CreateMessage {
195 community_id: community_id.to_string(),387 community_id: community_id.to_string(),
196 body: body.to_string(),388 body: body.to_string(),
389+ attachments,
390+ reply_to,
391+ })
392+ .await?
393+ {
394+ Response::Message(message) => Ok(message),
395+ _ => Err(Error::Server),
396+ }
397+ }
398+
399+ pub async fn update_message(&self, message_id: &str, body: &str) -> Result<Message, Error> {
400+ validate_message_body(body)?;
401+
402+ match self
403+ .request(Request::UpdateMessage {
404+ message_id: message_id.to_string(),
405+ body: body.to_string(),
197 })406 })
198 .await?407 .await?
199 {408 {
@@ -202,6 +411,160 @@ impl NetworkHandle {
202 }411 }
203 }412 }
204 413
414+ pub async fn forward_messages(
415+ &self,
416+ message_ids: Vec<String>,
417+ community_id: &str,
418+ snippet: bool,
419+ ) -> Result<Vec<Message>, Error> {
420+ validate_forward(message_ids.len())?;
421+
422+ match self
423+ .request(Request::ForwardMessages {
424+ message_ids,
425+ community_id: community_id.to_string(),
426+ snippet,
427+ })
428+ .await?
429+ {
430+ Response::Messages(messages) => Ok(messages),
431+ _ => Err(Error::Server),
432+ }
433+ }
434+
435+ pub async fn find_user(&self, username: &str) -> Result<User, Error> {
436+ validate_username(username)?;
437+
438+ match self
439+ .request(Request::FindUser {
440+ username: username.to_string(),
441+ })
442+ .await?
443+ {
444+ Response::User(user) => Ok(user),
445+ _ => Err(Error::Server),
446+ }
447+ }
448+
449+ pub async fn open_direct(&self, user_id: &str) -> Result<Community, Error> {
450+ match self
451+ .request(Request::OpenDirect {
452+ user_id: user_id.to_string(),
453+ })
454+ .await?
455+ {
456+ Response::Community(community) => Ok(community),
457+ _ => Err(Error::Server),
458+ }
459+ }
460+
461+ pub async fn friends(&self) -> Result<Friends, Error> {
462+ match self.request(Request::Friends).await? {
463+ Response::Friends(friends) => Ok(friends),
464+ _ => Err(Error::Server),
465+ }
466+ }
467+
468+ pub async fn add_friend(&self, user_id: &str) -> Result<(), Error> {
469+ self.done(Request::AddFriend {
470+ user_id: user_id.to_string(),
471+ })
472+ .await
473+ }
474+
475+ pub async fn accept_friend(&self, user_id: &str) -> Result<(), Error> {
476+ self.done(Request::AcceptFriend {
477+ user_id: user_id.to_string(),
478+ })
479+ .await
480+ }
481+
482+ pub async fn remove_friend(&self, user_id: &str) -> Result<(), Error> {
483+ self.done(Request::RemoveFriend {
484+ user_id: user_id.to_string(),
485+ })
486+ .await
487+ }
488+
489+ pub async fn invite(&self, community_id: &str, user_id: &str) -> Result<(), Error> {
490+ self.done(Request::Invite {
491+ community_id: community_id.to_string(),
492+ user_id: user_id.to_string(),
493+ })
494+ .await
495+ }
496+
497+ pub async fn invitations(&self) -> Result<Vec<Invitation>, Error> {
498+ match self.request(Request::Invitations).await? {
499+ Response::Invitations(invitations) => Ok(invitations),
500+ _ => Err(Error::Server),
501+ }
502+ }
503+
504+ pub async fn accept_invitation(&self, community_id: &str) -> Result<Community, Error> {
505+ match self
506+ .request(Request::AcceptInvitation {
507+ community_id: community_id.to_string(),
508+ })
509+ .await?
510+ {
511+ Response::Community(community) => Ok(community),
512+ _ => Err(Error::Server),
513+ }
514+ }
515+
516+ pub async fn decline_invitation(&self, community_id: &str) -> Result<(), Error> {
517+ self.done(Request::DeclineInvitation {
518+ community_id: community_id.to_string(),
519+ })
520+ .await
521+ }
522+
523+ async fn done(&self, request: Request) -> Result<(), Error> {
524+ match self.request(request).await? {
525+ Response::Done => Ok(()),
526+ _ => Err(Error::Server),
527+ }
528+ }
529+
530+ pub async fn upload_attachment(
531+ &self,
532+ community_id: &str,
533+ path: PathBuf,
534+ ) -> Result<Attachment, Error> {
535+ let (reply, response) = oneshot::channel();
536+
537+ self.command_sender
538+ .send(Command::Upload {
539+ community_id: community_id.to_string(),
540+ path,
541+ reply,
542+ })
543+ .await
544+ .map_err(|_| Error::ChannelClosed)?;
545+
546+ response.await.map_err(|_| Error::ChannelClosed)?
547+ }
548+
549+ pub async fn download_attachment(
550+ &self,
551+ attachment_id: &str,
552+ thumbnail: bool,
553+ ) -> Result<Vec<u8>, Error> {
554+ let (reply, response) = oneshot::channel();
555+
556+ self.command_sender
557+ .send(Command::Download {
558+ attachment_id: attachment_id.to_string(),
559+ thumbnail,
560+ reply,
561+ })
562+ .await
563+ .map_err(|_| Error::ChannelClosed)?;
564+
565+ response.await.map_err(|_| Error::ChannelClosed)?
566+ }
567+
205 pub async fn read_messages(568 pub async fn read_messages(
206 &self,569 &self,
207 community_id: &str,570 community_id: &str,
@@ -218,24 +581,200 @@ impl NetworkHandle {
218 _ => Err(Error::Server),581 _ => Err(Error::Server),
219 }582 }
220 }583 }
584+
585+ pub async fn update_status(&self, status: &str) -> Result<User, Error> {
586+ validate_status(status)?;
587+
588+ match self
589+ .request(Request::UpdateStatus {
590+ status: status.to_string(),
591+ })
592+ .await?
593+ {
594+ Response::User(user) => Ok(user),
595+ _ => Err(Error::Server),
596+ }
597+ }
598+
599+ pub async fn update_avatar(&self, bytes: Vec<u8>) -> Result<User, Error> {
600+ validate_avatar_size(&bytes)?;
601+
602+ match self.request(Request::UpdateAvatar { image: bytes }).await? {
603+ Response::User(user) => Ok(user),
604+ _ => Err(Error::Server),
605+ }
606+ }
607+
608+ pub async fn update_community_avatar(
609+ &self,
610+ community_id: &str,
611+ image: Option<Vec<u8>>,
612+ ) -> Result<Community, Error> {
613+ if let Some(bytes) = &image {
614+ validate_avatar_size(bytes)?;
615+ }
616+
617+ match self
618+ .request(Request::UpdateCommunityAvatar {
619+ community_id: community_id.to_string(),
620+ image,
621+ })
622+ .await?
623+ {
624+ Response::Community(community) => Ok(community),
625+ _ => Err(Error::Server),
626+ }
627+ }
628+
629+ pub async fn remove_avatar(&self) -> Result<User, Error> {
630+ match self.request(Request::RemoveAvatar).await? {
631+ Response::User(user) => Ok(user),
632+ _ => Err(Error::Server),
633+ }
634+ }
635+
636+ pub async fn read_avatar(&self, avatar_id: &str) -> Result<Vec<u8>, Error> {
637+ match self
638+ .request(Request::ReadAvatar {
639+ avatar_id: avatar_id.to_string(),
640+ })
641+ .await?
642+ {
643+ Response::Avatar(bytes) => Ok(bytes),
644+ _ => Err(Error::Server),
645+ }
646+ }
647+
648+ pub async fn join_voice(&self, community_id: &str) -> Result<Vec<String>, Error> {
649+ match self
650+ .request(Request::JoinVoice {
651+ community_id: community_id.to_string(),
652+ })
653+ .await?
654+ {
655+ Response::Voice(participants) => Ok(participants),
656+ _ => Err(Error::Server),
657+ }
658+ }
659+
660+ pub async fn leave_voice(&self) -> Result<(), Error> {
661+ match self.request(Request::LeaveVoice).await? {
662+ Response::Done => Ok(()),
663+ _ => Err(Error::Server),
664+ }
665+ }
666+
667+ pub async fn voice_participants(&self, community_id: &str) -> Result<Vec<String>, Error> {
668+ match self
669+ .request(Request::VoiceParticipants {
670+ community_id: community_id.to_string(),
671+ })
672+ .await?
673+ {
674+ Response::Voice(participants) => Ok(participants),
675+ _ => Err(Error::Server),
676+ }
677+ }
678+
679+ pub fn set_voice_settings(&self, settings: VoiceSettings) {
680+ *self.voice_settings.lock().unwrap() = settings.clone();
681+
682+ if let Some(voice) = self.voice.lock().unwrap().as_mut() {
683+ voice.apply(&settings);
684+ }
685+ if let Some(voice) = self.mic_test.lock().unwrap().as_mut() {
686+ voice.apply(&settings);
687+ }
688+ }
689+
690+ pub fn start_mic_test(&self) {
691+ if self.voice.lock().unwrap().is_some() {
692+ return;
693+ }
694+ let settings = self.voice_settings.lock().unwrap().clone();
695+ *self.mic_test.lock().unwrap() = Some(voice::start(None, &settings));
696+ }
697+
698+ pub fn play_chime(&self) {
699+ voice::play_chime(&self.voice_settings.lock().unwrap());
700+ }
701+
702+ pub fn stop_mic_test(&self) {
703+ self.mic_test.lock().unwrap().take();
704+ }
705+
706+ pub fn voice_level_db(&self) -> Option<f32> {
707+ let live = self.voice.lock().unwrap().as_ref().map(Voice::level_db);
708+ live.or_else(|| self.mic_test.lock().unwrap().as_ref().map(Voice::level_db))
709+ }
710+
711+ pub fn set_talking(&self, talking: bool) {
712+ if let Some(voice) = self.voice.lock().unwrap().as_ref() {
713+ voice.set_talking(talking);
714+ }
715+ }
716+
717+ pub fn set_muted(&self, muted: bool) {
718+ if let Some(voice) = self.voice.lock().unwrap().as_ref() {
719+ voice.set_muted(muted);
720+ }
721+ }
722+
723+ pub fn set_deafened(&self, deafened: bool) {
724+ if let Some(voice) = self.voice.lock().unwrap().as_ref() {
725+ voice.set_deafened(deafened);
726+ }
727+ }
728+
729+ pub fn speaking(&self) -> Vec<String> {
730+ self.voice
731+ .lock()
732+ .unwrap()
733+ .as_ref()
734+ .map(Voice::speaking)
735+ .unwrap_or_default()
736+ }
221 }737 }
222 738
223 pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) {739 pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) {
224 let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE);740 let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE);
225 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE);741 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE);
742+ let voice: SharedVoice = Arc::new(Mutex::new(None));
743+ let mic_test: SharedVoice = Arc::new(Mutex::new(None));
744+ let voice_settings: SharedSettings = Arc::new(Mutex::new(VoiceSettings::default()));
226 745
227 std::thread::Builder::new()746 std::thread::Builder::new()
228 .name("network".to_string())747 .name("network".to_string())
229- .spawn(move || {748+ .spawn({
230- tokio::runtime::Builder::new_current_thread()749+ let voice = voice.clone();
231- .enable_all()750+ let mic_test = mic_test.clone();
232- .build()751+ let voice_settings = voice_settings.clone();
233- .expect("network runtime")752+ move || {
234- .block_on(actor(client_config, command_receiver, event_sender));753+ tokio::runtime::Builder::new_current_thread()
754+ .enable_all()
755+ .build()
756+ .expect("network runtime")
757+ .block_on(actor(
758+ client_config,
759+ command_receiver,
760+ event_sender,
761+ voice,
762+ mic_test,
763+ voice_settings,
764+ ));
765+ }
235 })766 })
236 .expect("network thread");767 .expect("network thread");
237 768
238- (NetworkHandle { command_sender }, event_receiver)769+ (
770+ NetworkHandle {
771+ command_sender,
772+ voice,
773+ mic_test,
774+ voice_settings,
775+ },
776+ event_receiver,
777+ )
239 }778 }
240 779
241 async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Error> {780 async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Error> {
@@ -347,6 +886,99 @@ async fn send(connection: &quinn::Connection, request: &Request) -> Result<Respo
347 send_request(request, send_stream, receive_stream).await886 send_request(request, send_stream, receive_stream).await
348 }887 }
349 888
889+async fn send_body(
890+ send_stream: &mut quinn::SendStream,
891+ file: &mut tokio::fs::File,
892+) -> Result<(), Error> {
893+ use tokio::io::AsyncReadExt;
894+
895+ let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
896+ loop {
897+ let read = file.read(&mut buffer).await?;
898+ if read == 0 {
899+ return Ok(());
900+ }
901+
902+ send_stream.write_all(&buffer[..read]).await?;
903+ }
904+}
905+
906+async fn upload(
907+ connection: &quinn::Connection,
908+ community_id: &str,
909+ path: &Path,
910+) -> Result<Attachment, Error> {
911+ let name = path
912+ .file_name()
913+ .map(|name| name.to_string_lossy().into_owned())
914+ .unwrap_or_default();
915+ validate_attachment_name(&name)?;
916+
917+ let mut file = tokio::fs::File::open(path).await?;
918+ let size = file.metadata().await?.len();
919+ validate_attachment_size(size)?;
920+
921+ let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
922+ send_stream_kind(StreamKind::Upload, &mut send_stream).await?;
923+ let header = UploadHeader {
924+ community_id: community_id.to_string(),
925+ name,
926+ size,
927+ };
928+ send_upload_header(&header, &mut send_stream).await?;
929+
930+ let sent = match send_body(&mut send_stream, &mut file).await {
931+ Ok(()) => send_stream.finish().map_err(Error::from),
932+ Err(error) => Err(error),
933+ };
934+ let response = receive_decoded::<Response>(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await;
935+
936+ match (sent, response) {
937+ (_, Ok(Response::Attachment(attachment))) => Ok(attachment),
938+ (_, Ok(Response::Error(error))) => Err(error),
939+ (Err(error), _) | (_, Err(error)) => Err(error),
940+ (Ok(()), Ok(_)) => Err(Error::Server),
941+ }
942+}
943+
944+async fn download(
945+ connection: &quinn::Connection,
946+ attachment_id: &str,
947+ thumbnail: bool,
948+) -> Result<Vec<u8>, Error> {
949+ let (mut send_stream, mut receive_stream) = connection.open_bi().await?;
950+ send_stream_kind(StreamKind::Download, &mut send_stream).await?;
951+ let request = DownloadRequest {
952+ attachment_id: attachment_id.to_string(),
953+ thumbnail,
954+ };
955+ send_download_request(&request, &mut send_stream).await?;
956+ send_stream.finish()?;
957+
958+ match receive_download_status(&mut receive_stream).await? {
959+ DownloadStatus::Error => {
960+ Err(receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await?)
961+ }
962+ DownloadStatus::Ok => {
963+ let mut length_bytes = [0u8; 8];
964+ receive_stream.read_exact(&mut length_bytes).await?;
965+
966+ let length = u64::from_le_bytes(length_bytes);
967+ if length > MAXIMUM_ATTACHMENT_BYTES {
968+ return Err(Error::ReadBoundExceed {
969+ actual: length as usize,
970+ maximum: MAXIMUM_ATTACHMENT_BYTES as usize,
971+ });
972+ }
973+
974+ let mut bytes = vec![0u8; length as usize];
975+ receive_stream.read_exact(&mut bytes).await?;
976+
977+ Ok(bytes)
978+ }
979+ }
980+}
981+
350 async fn dispatch(982 async fn dispatch(
351 connection: quinn::Connection,983 connection: quinn::Connection,
352 request: Request,984 request: Request,
@@ -359,6 +991,9 @@ async fn actor(
359 client_config: ClientConfig,991 client_config: ClientConfig,
360 mut command_receiver: mpsc::Receiver<Command>,992 mut command_receiver: mpsc::Receiver<Command>,
361 event_sender: mpsc::Sender<NetworkEvent>,993 event_sender: mpsc::Sender<NetworkEvent>,
994+ voice: SharedVoice,
995+ mic_test: SharedVoice,
996+ voice_settings: SharedSettings,
362 ) {997 ) {
363 let mut token: Option<String> = None;998 let mut token: Option<String> = None;
364 let mut token_epoch = 0;999 let mut token_epoch = 0;
@@ -404,12 +1039,14 @@ async fn actor(
404 }1039 }
405 1040
406 tokio::spawn(event_receive_loop(connection.clone(), event_sender.clone()));1041 tokio::spawn(event_receive_loop(connection.clone(), event_sender.clone()));
1042+ tokio::spawn(datagram_receive_loop(connection.clone(), voice.clone()));
407 1043
408 loop {1044 loop {
409 tokio::select! {1045 tokio::select! {
410 command = command_receiver.recv() => match command {1046 command = command_receiver.recv() => match command {
411- Some(Command { request, reply }) => match &request {1047+ Some(Command::Request { request, reply }) => match &request {
412 Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => {1048 Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => {
1049+ voice.lock().unwrap().take();
413 let token_sender = token_sender.clone();1050 let token_sender = token_sender.clone();
414 let epoch = token_epoch;1051 let epoch = token_epoch;
415 let connection = connection.clone();1052 let connection = connection.clone();
@@ -423,9 +1060,32 @@ async fn actor(
423 let _ = reply.send(response);1060 let _ = reply.send(response);
424 });1061 });
425 }1062 }
426- Request::Logout => {1063+ Request::Logout | Request::Detach => {
427 token = None;1064 token = None;
428 token_epoch += 1;1065 token_epoch += 1;
1066+ voice.lock().unwrap().take();
1067+
1068+ tokio::spawn(dispatch(connection.clone(), request, reply));
1069+ }
1070+ Request::JoinVoice { .. } => {
1071+ let voice = voice.clone();
1072+ let mic_test = mic_test.clone();
1073+ let settings = voice_settings.lock().unwrap().clone();
1074+ let connection = connection.clone();
1075+
1076+ tokio::spawn(async move {
1077+ let response = send(&connection, &request).await;
1078+ if let Ok(Response::Voice(_)) = &response {
1079+ mic_test.lock().unwrap().take();
1080+ *voice.lock().unwrap() =
1081+ Some(voice::start(Some(connection), &settings));
1082+ }
1083+
1084+ let _ = reply.send(response);
1085+ });
1086+ }
1087+ Request::LeaveVoice => {
1088+ voice.lock().unwrap().take();
429 1089
430 tokio::spawn(dispatch(connection.clone(), request, reply));1090 tokio::spawn(dispatch(connection.clone(), request, reply));
431 }1091 }
@@ -433,6 +1093,20 @@ async fn actor(
433 tokio::spawn(dispatch(connection.clone(), request, reply));1093 tokio::spawn(dispatch(connection.clone(), request, reply));
434 }1094 }
435 },1095 },
1096+ Some(Command::Upload { community_id, path, reply }) => {
1097+ let connection = connection.clone();
1098+
1099+ tokio::spawn(async move {
1100+ let _ = reply.send(upload(&connection, &community_id, &path).await);
1101+ });
1102+ }
1103+ Some(Command::Download { attachment_id, thumbnail, reply }) => {
1104+ let connection = connection.clone();
1105+
1106+ tokio::spawn(async move {
1107+ let _ = reply.send(download(&connection, &attachment_id, thumbnail).await);
1108+ });
1109+ }
436 None => break 'session,1110 None => break 'session,
437 },1111 },
438 Some((epoch, session_token)) = token_receiver.recv() => {1112 Some((epoch, session_token)) = token_receiver.recv() => {
@@ -443,6 +1117,7 @@ async fn actor(
443 1117
444 error = connection.closed() => {1118 error = connection.closed() => {
445 warn!("disconnected: {error}");1119 warn!("disconnected: {error}");
1120+ voice.lock().unwrap().take();
446 1121
447 if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() {1122 if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() {
448 return;1123 return;
@@ -465,7 +1140,7 @@ async fn event_receive_loop(
465 1140
466 while let Ok(event) = receive_event(&mut receive_stream).await {1141 while let Ok(event) = receive_event(&mut receive_stream).await {
467 if event_sender1142 if event_sender
468- .send(NetworkEvent::Pushed(event))1143+ .send(NetworkEvent::Pushed(Box::new(event)))
469 .await1144 .await
470 .is_err()1145 .is_err()
471 {1146 {
@@ -473,3 +1148,11 @@ async fn event_receive_loop(
473 }1148 }
474 }1149 }
475 }1150 }
1151+
1152+async fn datagram_receive_loop(connection: quinn::Connection, voice: SharedVoice) {
1153+ while let Ok(datagram) = connection.read_datagram().await {
1154+ if let Some(voice) = voice.lock().unwrap().as_ref() {
1155+ voice.receive(&datagram);
1156+ }
1157+ }
1158+}
crates/client/src/settings.rsadded+183 -0
@@ -0,0 +1,183 @@
1+use std::{fmt::Display, fs, ops::RangeInclusive, path::PathBuf};
2+
3+use common::config::Config;
4+use gpui_kit::{
5+ App, Global,
6+ component::{Theme, ThemeMode},
7+};
8+use tracing::warn;
9+
10+use crate::voice::audio::Choice;
11+
12+pub const SENSITIVITY_DB: RangeInclusive<f32> = -80.0..=0.0;
13+pub const VOLUME: RangeInclusive<f32> = 0.0..=200.0;
14+
15+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16+pub enum ThemeChoice {
17+ System,
18+ Light,
19+ Dark,
20+ Black,
21+}
22+
23+pub struct Look(pub ThemeChoice);
24+
25+impl Global for Look {}
26+
27+impl ThemeChoice {
28+ fn name(self) -> &'static str {
29+ match self {
30+ ThemeChoice::System => "system",
31+ ThemeChoice::Light => "light",
32+ ThemeChoice::Dark => "dark",
33+ ThemeChoice::Black => "black",
34+ }
35+ }
36+
37+ fn parse(value: &str) -> Option<Self> {
38+ match value {
39+ "system" => Some(ThemeChoice::System),
40+ "light" => Some(ThemeChoice::Light),
41+ "dark" => Some(ThemeChoice::Dark),
42+ "black" => Some(ThemeChoice::Black),
43+ _ => None,
44+ }
45+ }
46+}
47+
48+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49+pub enum Activation {
50+ VoiceActivity,
51+ PushToTalk,
52+}
53+
54+#[derive(Debug, Clone, PartialEq)]
55+pub struct VoiceSettings {
56+ pub sensitivity_db: f32,
57+ pub input_volume: f32,
58+ pub output_volume: f32,
59+ pub choice: Choice,
60+ pub activation: Activation,
61+ pub push_to_talk_key: String,
62+}
63+
64+impl Default for VoiceSettings {
65+ fn default() -> Self {
66+ Self {
67+ sensitivity_db: -40.0,
68+ input_volume: 100.0,
69+ output_volume: 100.0,
70+ choice: Choice::default(),
71+ activation: Activation::VoiceActivity,
72+ push_to_talk_key: String::new(),
73+ }
74+ }
75+}
76+
77+#[derive(Debug, Clone, PartialEq)]
78+pub struct Settings {
79+ pub theme: ThemeChoice,
80+ pub voice: VoiceSettings,
81+}
82+
83+fn path() -> Option<PathBuf> {
84+ dirs::config_dir().map(|dir| dir.join("yumush").join("settings"))
85+}
86+
87+pub fn load() -> Settings {
88+ let config = path()
89+ .and_then(|path| fs::read_to_string(path).ok())
90+ .and_then(|content| Config::parse(&content).ok());
91+ let text = |key: &str| {
92+ config
93+ .as_ref()
94+ .and_then(|config| config.get(key).ok())
95+ .filter(|value| !value.is_empty())
96+ };
97+ let number = |key: &str, default: f32, range: &RangeInclusive<f32>| {
98+ text(key)
99+ .and_then(|value| value.parse::<f32>().ok())
100+ .filter(|value| range.contains(value))
101+ .unwrap_or(default)
102+ };
103+
104+ let defaults = VoiceSettings::default();
105+ let voice = VoiceSettings {
106+ sensitivity_db: number(
107+ "voice.sensitivity",
108+ defaults.sensitivity_db,
109+ &SENSITIVITY_DB,
110+ ),
111+ input_volume: number("voice.input_volume", defaults.input_volume, &VOLUME),
112+ output_volume: number("voice.output_volume", defaults.output_volume, &VOLUME),
113+ choice: Choice {
114+ input: text("voice.input"),
115+ output: text("voice.output"),
116+ },
117+ activation: match text("voice.activation").as_deref() {
118+ Some("push_to_talk") => Activation::PushToTalk,
119+ _ => Activation::VoiceActivity,
120+ },
121+ push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(),
122+ };
123+
124+ Settings {
125+ theme: text("theme")
126+ .and_then(|value| ThemeChoice::parse(&value))
127+ .unwrap_or(ThemeChoice::Dark),
128+ voice,
129+ }
130+}
131+
132+fn line(key: &str, value: impl Display) -> String {
133+ format!("{key} = \"{value}\"\n")
134+}
135+
136+pub fn save(settings: &Settings) {
137+ let Some(path) = path() else {
138+ return;
139+ };
140+
141+ let voice = &settings.voice;
142+ let activation = match voice.activation {
143+ Activation::VoiceActivity => "voice_activity",
144+ Activation::PushToTalk => "push_to_talk",
145+ };
146+ let key = voice.push_to_talk_key.as_str();
147+ let content = [
148+ line("theme", settings.theme.name()),
149+ line("voice.sensitivity", voice.sensitivity_db),
150+ line("voice.input_volume", voice.input_volume),
151+ line("voice.output_volume", voice.output_volume),
152+ line(
153+ "voice.input",
154+ voice.choice.input.as_deref().unwrap_or_default(),
155+ ),
156+ line(
157+ "voice.output",
158+ voice.choice.output.as_deref().unwrap_or_default(),
159+ ),
160+ line("voice.activation", activation),
161+ line("voice.push_to_talk", key),
162+ ]
163+ .concat();
164+
165+ let result = path
166+ .parent()
167+ .map_or(Ok(()), fs::create_dir_all)
168+ .and_then(|()| fs::write(&path, content));
169+
170+ if let Err(error) = result {
171+ warn!("save settings failed: {error}");
172+ }
173+}
174+
175+pub fn apply(choice: ThemeChoice, cx: &mut App) {
176+ cx.set_global(Look(choice));
177+ match choice {
178+ ThemeChoice::System => Theme::sync_system_appearance(None, cx),
179+ ThemeChoice::Light => Theme::change(ThemeMode::Light, None, cx),
180+ ThemeChoice::Dark | ThemeChoice::Black => Theme::change(ThemeMode::Dark, None, cx),
181+ }
182+ crate::gui::sync_theme(cx);
183+}
crates/client/src/voice/audio.rsadded+245 -0
@@ -0,0 +1,245 @@
1+use std::{
2+ error::Error,
3+ sync::{
4+ Arc,
5+ atomic::{AtomicBool, Ordering},
6+ },
7+ thread::JoinHandle,
8+ time::Duration,
9+};
10+
11+use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE};
12+use tracing::{info, warn};
13+
14+use super::{Capture, Playback};
15+
16+#[cfg(target_os = "macos")]
17+#[path = "audio/coreaudio.rs"]
18+mod backend;
19+#[cfg(target_os = "linux")]
20+#[path = "audio/pipewire.rs"]
21+mod backend;
22+#[cfg(target_os = "windows")]
23+#[path = "audio/wasapi.rs"]
24+mod backend;
25+
26+const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1);
27+const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100);
28+const STOP_CHECK: Duration = Duration::from_millis(100);
29+
30+#[derive(Debug, Clone, PartialEq, Eq)]
31+pub struct Device {
32+ pub id: String,
33+ pub name: String,
34+}
35+
36+#[derive(Debug, Clone, Default, PartialEq, Eq)]
37+pub struct Devices {
38+ pub inputs: Vec<Device>,
39+ pub outputs: Vec<Device>,
40+}
41+
42+#[derive(Debug, Clone, Default, PartialEq, Eq)]
43+pub struct Choice {
44+ pub input: Option<String>,
45+ pub output: Option<String>,
46+}
47+
48+pub enum Audio {
49+ Silent,
50+ Tone(Worker),
51+ #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
52+ Device(backend::Backend),
53+}
54+
55+pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Audio {
56+ match std::env::var("YUMUSH_AUDIO").as_deref() {
57+ Ok("off") => Audio::Silent,
58+ Ok("tone") => Audio::Tone(Worker::spawn("voice-tone", move |stop| {
59+ tone(capture.as_ref(), &playback, stop)
60+ })),
61+ _ => device(capture, playback, choice),
62+ }
63+}
64+
65+#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
66+fn device(capture: Option<Capture>, playback: Playback, choice: Choice) -> Audio {
67+ Audio::Device(backend::start(capture, playback, choice))
68+}
69+
70+#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
71+fn device(_: Option<Capture>, _: Playback, _: Choice) -> Audio {
72+ Audio::Silent
73+}
74+
75+#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
76+pub fn devices() -> Devices {
77+ match std::env::var("YUMUSH_AUDIO").as_deref() {
78+ Ok("off" | "tone") => Devices::default(),
79+ _ => backend::devices(),
80+ }
81+}
82+
83+#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
84+pub fn devices() -> Devices {
85+ Devices::default()
86+}
87+
88+pub fn record(capture: &Capture, samples: impl IntoIterator<Item = f32>) {
89+ let Ok(mut capture) = capture.try_lock() else {
90+ return;
91+ };
92+ for sample in samples {
93+ if capture.push(sample).is_err() {
94+ return;
95+ }
96+ }
97+}
98+
99+pub fn stereo_frame(bytes: &[u8; 8]) -> [f32; 2] {
100+ let (left, right) = bytes.split_at(4);
101+ [left, right].map(|half| f32::from_le_bytes(half.try_into().unwrap_or_default()))
102+}
103+
104+pub fn stereo_bytes(sample: f32) -> [u8; 8] {
105+ let bytes = sample.to_le_bytes();
106+ let mut frame = [0; 8];
107+ frame[..4].copy_from_slice(&bytes);
108+ frame[4..].copy_from_slice(&bytes);
109+ frame
110+}
111+
112+#[derive(Default)]
113+pub struct Downmix {
114+ energy: [f32; 2],
115+}
116+
117+impl Downmix {
118+ const SMOOTHING: f32 = 0.9;
119+ const SILENCE: f32 = 1e-9;
120+
121+ pub fn mix<I>(&mut self, frames: I) -> impl Iterator<Item = f32> + use<I>
122+ where
123+ I: Iterator<Item = [f32; 2]> + Clone,
124+ {
125+ let (mut sum, mut count) = ([0.0f32; 2], 0.0f32);
126+ for frame in frames.clone() {
127+ sum[0] += frame[0] * frame[0];
128+ sum[1] += frame[1] * frame[1];
129+ count += 1.0;
130+ }
131+ for (energy, sum) in self.energy.iter_mut().zip(sum) {
132+ *energy = *energy * Self::SMOOTHING + sum / count.max(1.0) * (1.0 - Self::SMOOTHING);
133+ }
134+ let total = self.energy[0] + self.energy[1];
135+ let left = if total > Self::SILENCE {
136+ self.energy[0] / total
137+ } else {
138+ 0.5
139+ };
140+ frames.map(move |frame| frame[0] * left + frame[1] * (1.0 - left))
141+ }
142+}
143+
144+pub fn play(playback: &Playback, count: usize, mut write: impl FnMut(usize, f32)) {
145+ let mut playback = playback.try_lock().ok();
146+ for index in 0..count {
147+ let sample = playback
148+ .as_mut()
149+ .and_then(|playback| playback.pop().ok())
150+ .unwrap_or(0.0);
151+ write(index, sample);
152+ }
153+}
154+
155+pub struct Worker {
156+ stop: Arc<AtomicBool>,
157+ thread: Option<JoinHandle<()>>,
158+}
159+
160+impl Worker {
161+ pub fn spawn(name: &str, body: impl FnOnce(&AtomicBool) + Send + 'static) -> Self {
162+ let stop = Arc::new(AtomicBool::new(false));
163+ let thread = {
164+ let stop = stop.clone();
165+ std::thread::Builder::new()
166+ .name(name.to_string())
167+ .spawn(move || body(&stop))
168+ .inspect_err(|error| warn!("audio thread not started: {error}"))
169+ .ok()
170+ };
171+
172+ Self { stop, thread }
173+ }
174+}
175+
176+impl Drop for Worker {
177+ fn drop(&mut self) {
178+ self.stop.store(true, Ordering::Relaxed);
179+ if let Some(thread) = self.thread.take() {
180+ let _ = thread.join();
181+ }
182+ }
183+}
184+
185+pub fn supervise(
186+ name: &str,
187+ stop: &AtomicBool,
188+ mut attempt: impl FnMut() -> Result<(), Box<dyn Error>>,
189+) {
190+ while !stop.load(Ordering::Relaxed) {
191+ let pause = match attempt() {
192+ Ok(()) => RETRY_AFTER_CHANGE,
193+ Err(error) => {
194+ warn!("{name}: {error}, retrying");
195+ RETRY_AFTER_ERROR
196+ }
197+ };
198+ wait(stop, pause);
199+ }
200+}
201+
202+pub fn wait(stop: &AtomicBool, duration: Duration) -> bool {
203+ let mut waited = Duration::ZERO;
204+ while waited < duration {
205+ if stop.load(Ordering::Relaxed) {
206+ return false;
207+ }
208+ let step = STOP_CHECK.min(duration - waited);
209+ std::thread::sleep(step);
210+ waited += step;
211+ }
212+
213+ !stop.load(Ordering::Relaxed)
214+}
215+
216+fn tone(capture: Option<&Capture>, playback: &Playback, stop: &AtomicBool) {
217+ let step = 440.0 * std::f32::consts::TAU / VOICE_SAMPLE_RATE as f32;
218+ let mut phase = 0.0f32;
219+ let mut energy = 0.0f32;
220+ let mut frames = 0;
221+
222+ while wait(stop, Duration::from_millis(20)) {
223+ if let Some(capture) = capture {
224+ record(
225+ capture,
226+ (0..VOICE_FRAME_SAMPLES).map(|_| {
227+ phase = (phase + step) % std::f32::consts::TAU;
228+ phase.sin() * 0.5
229+ }),
230+ );
231+ }
232+ play(playback, VOICE_FRAME_SAMPLES, |_, sample| {
233+ energy += sample * sample
234+ });
235+ frames += 1;
236+ if frames == 50 {
237+ info!(
238+ "voice tone rms {:.3}",
239+ (energy / (50 * VOICE_FRAME_SAMPLES) as f32).sqrt()
240+ );
241+ energy = 0.0;
242+ frames = 0;
243+ }
244+ }
245+}
crates/client/src/voice/audio/coreaudio.rsadded+264 -0
@@ -0,0 +1,264 @@
1+use std::{error::Error as StdError, sync::atomic::AtomicBool, time::Duration};
2+
3+use common::constant::VOICE_SAMPLE_RATE;
4+use coreaudio::Error;
5+use coreaudio::audio_unit::audio_format::LinearPcmFlags;
6+use coreaudio::audio_unit::macos_helpers::{
7+ audio_unit_from_device_id_uninitialized, get_audio_device_ids_for_scope,
8+ get_audio_device_supports_scope, get_default_device_id, get_device_id_from_name,
9+ get_device_name,
10+};
11+use coreaudio::audio_unit::render_callback::{self, data};
12+use coreaudio::audio_unit::{AudioUnit, Element, IOType, SampleFormat, Scope, StreamFormat};
13+use tracing::warn;
14+
15+use super::{Choice, Device, Devices, Downmix, Worker, play, record, supervise, wait};
16+use crate::voice::{Capture, Playback};
17+
18+type Args = render_callback::Args<data::NonInterleaved<f32>>;
19+
20+const DEVICE_CHECK: Duration = Duration::from_millis(500);
21+
22+pub type Backend = Worker;
23+
24+pub fn devices() -> Devices {
25+ list_devices().unwrap_or_default()
26+}
27+
28+fn list_devices() -> Result<Devices, Error> {
29+ Ok(Devices {
30+ inputs: list(Scope::Input)?,
31+ outputs: list(Scope::Output)?,
32+ })
33+}
34+
35+fn list(scope: Scope) -> Result<Vec<Device>, Error> {
36+ Ok(get_audio_device_ids_for_scope(scope)?
37+ .into_iter()
38+ .filter(|id| get_audio_device_supports_scope(*id, scope).unwrap_or(false))
39+ .filter_map(|id| get_device_name(id).ok())
40+ .map(|name| Device {
41+ id: name.clone(),
42+ name,
43+ })
44+ .collect())
45+}
46+
47+pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend {
48+ Worker::spawn("voice audio", move |stop| {
49+ supervise("voice audio", stop, || {
50+ attempt(capture.as_ref(), &playback, &choice, stop)
51+ })
52+ })
53+}
54+
55+fn input_device(choice: &Choice) -> Option<u32> {
56+ choice
57+ .input
58+ .as_deref()
59+ .and_then(|name| get_device_id_from_name(name, true))
60+ .or_else(|| get_default_device_id(true))
61+}
62+
63+fn output_device(choice: &Choice) -> (Option<u32>, Option<u32>) {
64+ let chosen = choice
65+ .output
66+ .as_deref()
67+ .and_then(|name| get_device_id_from_name(name, false));
68+
69+ (chosen, chosen.and_then(|_| get_default_device_id(false)))
70+}
71+
72+fn attempt(
73+ capture: Option<&Capture>,
74+ playback: &Playback,
75+ choice: &Choice,
76+ stop: &AtomicBool,
77+) -> Result<(), Box<dyn StdError>> {
78+ let output_id = output_device(choice);
79+ let mut output = playback_unit(playback.clone(), output_id.0)?;
80+ let device = capture.and_then(|_| input_device(choice));
81+ let mut input = capture.zip(device).and_then(|(capture, device)| {
82+ capture_unit(device, capture.clone())
83+ .inspect_err(|error| warn!("voice capture unavailable: {error}"))
84+ .ok()
85+ });
86+ let outcome = watch(
87+ stop,
88+ choice,
89+ capture.is_some(),
90+ input.as_ref(),
91+ device,
92+ output_id,
93+ );
94+ stop_unit(&mut output);
95+ if let Some((unit, _)) = input.as_mut() {
96+ stop_unit(unit);
97+ }
98+ outcome?;
99+ Ok(())
100+}
101+
102+fn watch(
103+ stop: &AtomicBool,
104+ choice: &Choice,
105+ capturing: bool,
106+ input: Option<&(AudioUnit, f64)>,
107+ device: Option<u32>,
108+ output: (Option<u32>, Option<u32>),
109+) -> Result<(), Error> {
110+ while wait(stop, DEVICE_CHECK) {
111+ let input_moved = capturing && input_device(choice) != device;
112+ if input_moved || output_device(choice) != output {
113+ break;
114+ }
115+ let Some((unit, rate)) = input else {
116+ continue;
117+ };
118+ if unit
119+ .stream_format(Scope::Input, Element::Input)?
120+ .sample_rate
121+ != *rate
122+ {
123+ break;
124+ }
125+ }
126+ Ok(())
127+}
128+
129+fn stop_unit(unit: &mut AudioUnit) {
130+ if let Err(error) = unit.stop() {
131+ warn!("voice audio stop failed: {error}");
132+ }
133+}
134+
135+fn format(sample_rate: f64, channels: u32) -> StreamFormat {
136+ StreamFormat {
137+ sample_rate,
138+ sample_format: SampleFormat::F32,
139+ flags: LinearPcmFlags::IS_FLOAT
140+ | LinearPcmFlags::IS_PACKED
141+ | LinearPcmFlags::IS_NON_INTERLEAVED,
142+ channels,
143+ }
144+}
145+
146+fn playback_unit(playback: Playback, device: Option<u32>) -> Result<AudioUnit, Error> {
147+ let mut unit = match device {
148+ Some(device) => audio_unit_from_device_id_uninitialized(device, false)?,
149+ None => AudioUnit::new_uninitialized(IOType::DefaultOutput)?,
150+ };
151+ unit.set_stream_format(
152+ format(f64::from(VOICE_SAMPLE_RATE), 2),
153+ Scope::Input,
154+ Element::Output,
155+ )?;
156+ unit.set_render_callback(move |args: Args| {
157+ let Args { mut data, .. } = args;
158+ let mut channels = data.channels_mut();
159+ let Some(left) = channels.next() else {
160+ return Ok(());
161+ };
162+ play(&playback, left.len(), |index, sample| left[index] = sample);
163+ if let Some(right) = channels.next() {
164+ right.copy_from_slice(left);
165+ }
166+ Ok(())
167+ })?;
168+ unit.initialize()?;
169+ unit.start()?;
170+ Ok(unit)
171+}
172+
173+fn capture_unit(device: u32, capture: Capture) -> Result<(AudioUnit, f64), Error> {
174+ let mut unit = audio_unit_from_device_id_uninitialized(device, true)?;
175+ let rate = unit
176+ .stream_format(Scope::Input, Element::Input)?
177+ .sample_rate;
178+ unit.set_stream_format(format(rate, 2), Scope::Output, Element::Input)?;
179+ let mut resampler = (rate != f64::from(VOICE_SAMPLE_RATE)).then(|| Resampler::new(rate));
180+ let mut downmix = Downmix::default();
181+ let mut mixed = Vec::new();
182+ unit.set_input_callback(move |args: Args| {
183+ let Args { data, .. } = args;
184+ let mut channels = data.channels();
185+ let Some(left) = channels.next() else {
186+ return Ok(());
187+ };
188+ let right = channels.next().unwrap_or(left);
189+ let frames = left.iter().zip(right).map(|(left, right)| [*left, *right]);
190+ mixed.clear();
191+ mixed.extend(downmix.mix(frames));
192+ match resampler.as_mut() {
193+ Some(resampler) => record(&capture, resampler.resample(&mixed)),
194+ None => record(&capture, mixed.iter().copied()),
195+ }
196+ Ok(())
197+ })?;
198+ unit.initialize()?;
199+ unit.start()?;
200+ Ok((unit, rate))
201+}
202+
203+struct Resampler {
204+ step: f64,
205+ position: f64,
206+ previous: f32,
207+}
208+
209+impl Resampler {
210+ fn new(rate: f64) -> Self {
211+ Self {
212+ step: rate / f64::from(VOICE_SAMPLE_RATE),
213+ position: 0.0,
214+ previous: 0.0,
215+ }
216+ }
217+
218+ fn resample<'a>(&'a mut self, input: &'a [f32]) -> Resampled<'a> {
219+ Resampled {
220+ resampler: self,
221+ input,
222+ }
223+ }
224+}
225+
226+struct Resampled<'a> {
227+ resampler: &'a mut Resampler,
228+ input: &'a [f32],
229+}
230+
231+impl Resampled<'_> {
232+ fn at(&self, index: usize) -> f32 {
233+ if index == 0 {
234+ self.resampler.previous
235+ } else {
236+ self.input[index - 1]
237+ }
238+ }
239+}
240+
241+impl Iterator for Resampled<'_> {
242+ type Item = f32;
243+
244+ fn next(&mut self) -> Option<f32> {
245+ let index = self.resampler.position as usize;
246+ if index >= self.input.len() {
247+ return None;
248+ }
249+ let fraction = (self.resampler.position - index as f64) as f32;
250+ let (a, b) = (self.at(index), self.at(index + 1));
251+ self.resampler.position += self.resampler.step;
252+ Some(a + (b - a) * fraction)
253+ }
254+}
255+
256+impl Drop for Resampled<'_> {
257+ fn drop(&mut self) {
258+ for _ in self.by_ref() {}
259+ self.resampler.position -= self.input.len() as f64;
260+ if let Some(&last) = self.input.last() {
261+ self.resampler.previous = last;
262+ }
263+ }
264+}
crates/client/src/voice/audio/pipewire.rsadded+291 -0
@@ -0,0 +1,291 @@
1+use std::{
2+ cell::{Cell, RefCell},
3+ error::Error,
4+ rc::Rc,
5+ sync::atomic::{AtomicBool, Ordering},
6+ time::Duration,
7+};
8+
9+use common::constant::VOICE_SAMPLE_RATE;
10+use pipewire as pw;
11+use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType};
12+use spa::pod::Pod;
13+
14+use super::{
15+ Choice, Device, Devices, Downmix, Worker, play, record, stereo_bytes, stereo_frame, supervise,
16+};
17+use crate::voice::{Capture, Playback};
18+
19+const STOP_CHECK: Duration = Duration::from_millis(100);
20+const BYTES_PER_FRAME: usize = 8;
21+
22+pub struct Backend {
23+ _worker: Worker,
24+}
25+
26+pub fn devices() -> Devices {
27+ collect_devices().unwrap_or_default()
28+}
29+
30+fn collect_devices() -> Result<Devices, Box<dyn Error>> {
31+ pw::init();
32+ let mainloop = pw::main_loop::MainLoopRc::new(None)?;
33+ let context = pw::context::ContextRc::new(&mainloop, None)?;
34+ let core = context.connect_rc(None)?;
35+ let registry = core.get_registry_rc()?;
36+
37+ let devices = Rc::new(RefCell::new(Devices::default()));
38+ let done = Rc::new(Cell::new(false));
39+ let failed = Rc::new(Cell::new(false));
40+
41+ let pending = core.sync(0)?;
42+
43+ let _core_listener = core
44+ .add_listener_local()
45+ .done({
46+ let done = done.clone();
47+ let mainloop = mainloop.clone();
48+ move |id, seq| {
49+ if id == pw::core::PW_ID_CORE && seq == pending {
50+ done.set(true);
51+ mainloop.quit();
52+ }
53+ }
54+ })
55+ .error({
56+ let done = done.clone();
57+ let failed = failed.clone();
58+ let mainloop = mainloop.clone();
59+ move |_, _, _, _| {
60+ failed.set(true);
61+ done.set(true);
62+ mainloop.quit();
63+ }
64+ })
65+ .register();
66+
67+ let _registry_listener = registry
68+ .add_listener_local()
69+ .global({
70+ let devices = devices.clone();
71+ move |global| {
72+ if !matches!(global.type_, ObjectType::Node) {
73+ return;
74+ }
75+ let Some(props) = global.props else {
76+ return;
77+ };
78+ let Some(node) = props.get(*pw::keys::NODE_NAME) else {
79+ return;
80+ };
81+ if node == "yumush" {
82+ return;
83+ }
84+ let device = Device {
85+ id: node.to_string(),
86+ name: props
87+ .get(*pw::keys::NODE_DESCRIPTION)
88+ .or_else(|| props.get(*pw::keys::NODE_NICK))
89+ .unwrap_or(node)
90+ .to_string(),
91+ };
92+ match props.get(*pw::keys::MEDIA_CLASS) {
93+ Some("Audio/Source") => devices.borrow_mut().inputs.push(device),
94+ Some("Audio/Sink") => devices.borrow_mut().outputs.push(device),
95+ _ => {}
96+ }
97+ }
98+ })
99+ .register();
100+
101+ while !done.get() {
102+ mainloop.run();
103+ }
104+
105+ if failed.get() {
106+ return Err("pipewire devices".into());
107+ }
108+ Ok(devices.take())
109+}
110+
111+pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend {
112+ Backend {
113+ _worker: Worker::spawn("voice-audio", move |stop| {
114+ supervise("voice audio", stop, || {
115+ run(capture.as_ref(), &playback, &choice, stop)
116+ })
117+ }),
118+ }
119+}
120+
121+fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::PropertiesBox {
122+ let mut props = properties! {
123+ *pw::keys::MEDIA_TYPE => "Audio",
124+ *pw::keys::MEDIA_CATEGORY => category,
125+ *pw::keys::MEDIA_ROLE => "Communication",
126+ *pw::keys::NODE_NAME => "yumush",
127+ };
128+ if let Some(target) = target {
129+ props.insert(*pw::keys::TARGET_OBJECT, target);
130+ }
131+ props
132+}
133+
134+fn format_values() -> Option<Vec<u8>> {
135+ let mut info = spa::param::audio::AudioInfoRaw::new();
136+ info.set_format(spa::param::audio::AudioFormat::F32LE);
137+ info.set_rate(VOICE_SAMPLE_RATE);
138+ let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize];
139+ position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL;
140+ position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR;
141+ info.set_channels(2);
142+ info.set_position(position);
143+
144+ let object = spa::pod::Object {
145+ type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(),
146+ id: spa::param::ParamType::EnumFormat.as_raw(),
147+ properties: info.into(),
148+ };
149+ let (cursor, _) = spa::pod::serialize::PodSerializer::serialize(
150+ std::io::Cursor::new(Vec::new()),
151+ &spa::pod::Value::Object(object),
152+ )
153+ .ok()?;
154+
155+ Some(cursor.into_inner())
156+}
157+
158+fn run(
159+ capture: Option<&Capture>,
160+ playback: &Playback,
161+ choice: &Choice,
162+ stop: &AtomicBool,
163+) -> Result<(), Box<dyn Error>> {
164+ pw::init();
165+ let mainloop = pw::main_loop::MainLoopRc::new(None)?;
166+ let context = pw::context::ContextRc::new(&mainloop, None)?;
167+ let core = context.connect_rc(None)?;
168+ let failed = Rc::new(Cell::new(false));
169+
170+ let error_failed = failed.clone();
171+ let _core_listener = core
172+ .add_listener_local()
173+ .error(move |_, _, _, message| {
174+ tracing::warn!("pipewire: {message}");
175+ error_failed.set(true);
176+ })
177+ .register();
178+
179+ let values = format_values().ok_or("pipewire format")?;
180+ let flags = pw::stream::StreamFlags::AUTOCONNECT
181+ | pw::stream::StreamFlags::MAP_BUFFERS
182+ | pw::stream::StreamFlags::RT_PROCESS;
183+
184+ let capture_stream = pw::stream::StreamBox::new(
185+ &core,
186+ "yumush-capture",
187+ stream_properties("Capture", choice.input.as_deref()),
188+ )?;
189+ let capture = capture.cloned();
190+ let connect_capture = capture.is_some();
191+ let mut downmix = Downmix::default();
192+ let _capture_listener = capture_stream
193+ .add_local_listener_with_user_data(())
194+ .state_changed(state_watch(&failed))
195+ .process(move |stream, _| {
196+ let Some(mut buffer) = stream.dequeue_buffer() else {
197+ return;
198+ };
199+ let Some(data) = buffer.datas_mut().first_mut() else {
200+ return;
201+ };
202+ let size = data.chunk().size() as usize;
203+ let Some(bytes) = data.data() else {
204+ return;
205+ };
206+ let bytes = &bytes[..size.min(bytes.len())];
207+ let Some(capture) = &capture else {
208+ return;
209+ };
210+ let frames = bytes
211+ .as_chunks::<BYTES_PER_FRAME>()
212+ .0
213+ .iter()
214+ .map(stereo_frame);
215+ record(capture, downmix.mix(frames));
216+ })
217+ .register()?;
218+ if connect_capture {
219+ let mut capture_params = [Pod::from_bytes(&values).ok_or("pipewire format")?];
220+ capture_stream.connect(
221+ spa::utils::Direction::Input,
222+ None,
223+ flags,
224+ &mut capture_params,
225+ )?;
226+ }
227+
228+ let playback_stream = pw::stream::StreamBox::new(
229+ &core,
230+ "yumush-playback",
231+ stream_properties("Playback", choice.output.as_deref()),
232+ )?;
233+ let playback = playback.clone();
234+ let _playback_listener = playback_stream
235+ .add_local_listener_with_user_data(())
236+ .state_changed(state_watch(&failed))
237+ .process(move |stream, _| {
238+ let Some(mut buffer) = stream.dequeue_buffer() else {
239+ return;
240+ };
241+ let requested = buffer.requested() as usize;
242+ let Some(data) = buffer.datas_mut().first_mut() else {
243+ return;
244+ };
245+ let Some(bytes) = data.data() else {
246+ return;
247+ };
248+ let chunks = bytes.as_chunks_mut::<BYTES_PER_FRAME>().0;
249+ let frames = match requested {
250+ 0 => chunks.len(),
251+ requested => requested.min(chunks.len()),
252+ };
253+ play(&playback, frames, |index, sample| {
254+ chunks[index] = stereo_bytes(sample);
255+ });
256+
257+ let chunk = data.chunk_mut();
258+ *chunk.offset_mut() = 0;
259+ *chunk.stride_mut() = BYTES_PER_FRAME as i32;
260+ *chunk.size_mut() = (frames * BYTES_PER_FRAME) as u32;
261+ })
262+ .register()?;
263+ let mut playback_params = [Pod::from_bytes(&values).ok_or("pipewire format")?];
264+ playback_stream.connect(
265+ spa::utils::Direction::Output,
266+ None,
267+ flags,
268+ &mut playback_params,
269+ )?;
270+
271+ while !stop.load(Ordering::Relaxed) {
272+ if failed.get() {
273+ return Err("pipewire connection lost".into());
274+ }
275+ mainloop.loop_().iterate(Timeout::Finite(STOP_CHECK));
276+ }
277+
278+ Ok(())
279+}
280+
281+fn state_watch(
282+ failed: &Rc<Cell<bool>>,
283+) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static {
284+ let failed = failed.clone();
285+ move |_, _, _, new| {
286+ if let StreamState::Error(message) = new {
287+ tracing::warn!("pipewire stream: {message}");
288+ failed.set(true);
289+ }
290+ }
291+}
crates/client/src/voice/audio/wasapi.rsadded+286 -0
@@ -0,0 +1,286 @@
1+use std::{
2+ collections::VecDeque,
3+ error::Error,
4+ sync::atomic::{AtomicBool, Ordering},
5+ time::{Duration, Instant},
6+};
7+
8+use common::constant::VOICE_SAMPLE_RATE;
9+use tracing::warn;
10+use wasapi::{
11+ AudioCaptureClient, AudioClient, AudioRenderClient, DeviceEnumerator, Direction, Handle, Role,
12+ SampleType, StreamMode, WaveFormat, deinitialize, initialize_mta,
13+};
14+
15+use super::{
16+ Choice, Device, Devices, Downmix, Worker, play, record, stereo_bytes, stereo_frame, supervise,
17+};
18+use crate::voice::{Capture, Playback};
19+
20+const WAIT_MS: u32 = 100;
21+const BYTES_PER_FRAME: usize = 8;
22+const CHECK_DEFAULT_EVERY: Duration = Duration::from_secs(1);
23+
24+pub struct Backend {
25+ _workers: Vec<Worker>,
26+}
27+
28+struct Target<'a> {
29+ enumerator: &'a DeviceEnumerator,
30+ direction: Direction,
31+ id: String,
32+ choice: Option<&'a str>,
33+}
34+
35+pub fn devices() -> Devices {
36+ std::thread::spawn(|| {
37+ with_com(|| match enumerate() {
38+ Ok(devices) => devices,
39+ Err(error) => {
40+ warn!("devices: {error}");
41+ Devices::default()
42+ }
43+ })
44+ })
45+ .join()
46+ .unwrap_or_default()
47+}
48+
49+fn enumerate() -> Result<Devices, Box<dyn Error>> {
50+ let enumerator = DeviceEnumerator::new()?;
51+ Ok(Devices {
52+ inputs: list(&enumerator, Direction::Capture)?,
53+ outputs: list(&enumerator, Direction::Render)?,
54+ })
55+}
56+
57+fn list(
58+ enumerator: &DeviceEnumerator,
59+ direction: Direction,
60+) -> Result<Vec<Device>, Box<dyn Error>> {
61+ let collection = enumerator.get_device_collection(direction)?;
62+ let mut devices = Vec::new();
63+ for index in 0..collection.get_nbr_devices()? {
64+ let device = collection.get_device_at_index(index)?;
65+ devices.push(Device {
66+ id: device.get_id()?,
67+ name: device.get_friendlyname()?,
68+ });
69+ }
70+ Ok(devices)
71+}
72+
73+pub fn start(capture: Option<Capture>, playback: Playback, choice: Choice) -> Backend {
74+ let input = choice.input;
75+ let output = choice.output;
76+ let mut workers = vec![Worker::spawn("voice render", move |stop| {
77+ with_com(|| {
78+ supervise("voice render", stop, || {
79+ run_render(&playback, stop, output.as_deref())
80+ })
81+ })
82+ })];
83+ if let Some(capture) = capture {
84+ workers.push(Worker::spawn("voice capture", move |stop| {
85+ with_com(|| {
86+ supervise("voice capture", stop, || {
87+ run_capture(&capture, stop, input.as_deref())
88+ })
89+ })
90+ }));
91+ }
92+ Backend { _workers: workers }
93+}
94+
95+fn with_com<T: Default>(body: impl FnOnce() -> T) -> T {
96+ if let Err(error) = initialize_mta().ok() {
97+ warn!("COM not initialized: {error}");
98+ return T::default();
99+ }
100+ let value = body();
101+ deinitialize();
102+ value
103+}
104+
105+fn wave_format() -> WaveFormat {
106+ WaveFormat::new(
107+ 32,
108+ 32,
109+ SampleType::Float,
110+ VOICE_SAMPLE_RATE as usize,
111+ 2,
112+ None,
113+ )
114+}
115+
116+fn init_shared_event(client: &mut AudioClient, direction: Direction) -> Result<(), Box<dyn Error>> {
117+ let (period, _) = client.get_device_period()?;
118+ client.initialize_client(
119+ &wave_format(),
120+ direction,
121+ StreamMode::EventsShared {
122+ autoconvert: true,
123+ buffer_duration_hns: period * 2,
124+ },
125+ None,
126+ )?;
127+ Ok(())
128+}
129+
130+fn default_id(
131+ enumerator: &DeviceEnumerator,
132+ direction: Direction,
133+) -> Result<String, Box<dyn Error>> {
134+ Ok(enumerator
135+ .get_default_device_for_role(direction, Role::Console)?
136+ .get_id()?)
137+}
138+
139+fn find_device(
140+ enumerator: &DeviceEnumerator,
141+ direction: Direction,
142+ id: &str,
143+) -> Option<wasapi::Device> {
144+ let collection = enumerator.get_device_collection(direction).ok()?;
145+ for index in 0..collection.get_nbr_devices().ok()? {
146+ let Ok(device) = collection.get_device_at_index(index) else {
147+ continue;
148+ };
149+ if device.get_id().is_ok_and(|found| found == id) {
150+ return Some(device);
151+ }
152+ }
153+ None
154+}
155+
156+fn open_device(
157+ enumerator: &DeviceEnumerator,
158+ direction: Direction,
159+ choice: Option<&str>,
160+) -> Result<wasapi::Device, Box<dyn Error>> {
161+ if let Some(device) = choice.and_then(|id| find_device(enumerator, direction, id)) {
162+ return Ok(device);
163+ }
164+ Ok(enumerator.get_default_device_for_role(direction, Role::Console)?)
165+}
166+
167+fn default_changed(target: &Target, checked: &mut Instant) -> Result<bool, Box<dyn Error>> {
168+ if checked.elapsed() < CHECK_DEFAULT_EVERY {
169+ return Ok(false);
170+ }
171+ *checked = Instant::now();
172+ match target.choice {
173+ Some(chosen) if chosen == target.id => Ok(false),
174+ Some(chosen) if find_device(target.enumerator, target.direction, chosen).is_some() => {
175+ Ok(true)
176+ }
177+ _ => Ok(default_id(target.enumerator, target.direction)? != target.id),
178+ }
179+}
180+
181+fn run_capture(
182+ capture: &Capture,
183+ stop: &AtomicBool,
184+ choice: Option<&str>,
185+) -> Result<(), Box<dyn Error>> {
186+ let enumerator = DeviceEnumerator::new()?;
187+ let device = open_device(&enumerator, Direction::Capture, choice)?;
188+ let target = Target {
189+ enumerator: &enumerator,
190+ direction: Direction::Capture,
191+ id: device.get_id()?,
192+ choice,
193+ };
194+ let mut client = device.get_iaudioclient()?;
195+ init_shared_event(&mut client, Direction::Capture)?;
196+ let event = client.set_get_eventhandle()?;
197+ let reader = client.get_audiocaptureclient()?;
198+
199+ client.start_stream()?;
200+ let result = capture_frames(capture, stop, &target, &event, &reader);
201+ client.stop_stream()?;
202+ result
203+}
204+
205+fn capture_frames(
206+ capture: &Capture,
207+ stop: &AtomicBool,
208+ target: &Target,
209+ event: &Handle,
210+ reader: &AudioCaptureClient,
211+) -> Result<(), Box<dyn Error>> {
212+ let mut bytes = VecDeque::new();
213+ let mut downmix = Downmix::default();
214+ let mut checked = Instant::now();
215+ while !stop.load(Ordering::Relaxed) {
216+ let _ = event.wait_for_event(WAIT_MS);
217+ while reader.get_next_packet_size()?.unwrap_or(0) > 0 {
218+ reader.read_from_device_to_deque(&mut bytes)?;
219+ }
220+ let frames = bytes
221+ .make_contiguous()
222+ .as_chunks::<BYTES_PER_FRAME>()
223+ .0
224+ .iter()
225+ .map(stereo_frame);
226+ record(capture, downmix.mix(frames));
227+ bytes.clear();
228+ if default_changed(target, &mut checked)? {
229+ return Ok(());
230+ }
231+ }
232+ Ok(())
233+}
234+
235+fn run_render(
236+ playback: &Playback,
237+ stop: &AtomicBool,
238+ choice: Option<&str>,
239+) -> Result<(), Box<dyn Error>> {
240+ let enumerator = DeviceEnumerator::new()?;
241+ let device = open_device(&enumerator, Direction::Render, choice)?;
242+ let target = Target {
243+ enumerator: &enumerator,
244+ direction: Direction::Render,
245+ id: device.get_id()?,
246+ choice,
247+ };
248+ let mut client = device.get_iaudioclient()?;
249+ init_shared_event(&mut client, Direction::Render)?;
250+ let event = client.set_get_eventhandle()?;
251+ let writer = client.get_audiorenderclient()?;
252+
253+ let silence = vec![0u8; client.get_available_space_in_frames()? as usize * BYTES_PER_FRAME];
254+ writer.write_to_device(&silence, None)?;
255+
256+ client.start_stream()?;
257+ let result = render_frames(playback, stop, &target, &event, &client, &writer);
258+ client.stop_stream()?;
259+ result
260+}
261+
262+fn render_frames(
263+ playback: &Playback,
264+ stop: &AtomicBool,
265+ target: &Target,
266+ event: &Handle,
267+ client: &AudioClient,
268+ writer: &AudioRenderClient,
269+) -> Result<(), Box<dyn Error>> {
270+ let mut bytes: Vec<u8> = Vec::new();
271+ let mut checked = Instant::now();
272+ while !stop.load(Ordering::Relaxed) {
273+ let _ = event.wait_for_event(WAIT_MS);
274+ let frames = client.get_available_space_in_frames()? as usize;
275+ bytes.resize(frames * BYTES_PER_FRAME, 0);
276+ let chunks = bytes.as_chunks_mut::<BYTES_PER_FRAME>().0;
277+ play(playback, frames, |index, sample| {
278+ chunks[index] = stereo_bytes(sample);
279+ });
280+ writer.write_to_device(&bytes, None)?;
281+ if default_changed(target, &mut checked)? {
282+ return Ok(());
283+ }
284+ }
285+ Ok(())
286+}
crates/client/src/voice/engine.rsadded+293 -0
@@ -0,0 +1,293 @@
1+use std::{
2+ collections::{BTreeMap, HashMap, VecDeque},
3+ time::{Duration, Instant},
4+};
5+
6+use common::{
7+ constant::{VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE},
8+ voice::{decode_relay, encode_packet},
9+};
10+use ec_opus::{Application, Decoder, Encoder};
11+
12+pub const SILENT_DB: f32 = -100.0;
13+const JITTER_CAPACITY: usize = 10;
14+const START_FRAMES: usize = 2;
15+const SPEAKING_WINDOW: Duration = Duration::from_millis(300);
16+const RESTART_AFTER: Duration = Duration::from_secs(1);
17+const MAX_DECODE_SAMPLES: usize = 5760;
18+const HANGOVER_FRAMES: u32 = 15;
19+
20+fn rms(samples: &[f32]) -> f32 {
21+ (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()
22+}
23+
24+fn db(amplitude: f32) -> f32 {
25+ (20.0 * amplitude.log10()).max(SILENT_DB)
26+}
27+
28+struct Speaker {
29+ decoder: Decoder,
30+ scratch: Vec<f32>,
31+ jitter: BTreeMap<u32, Vec<u8>>,
32+ next: u32,
33+ pending: VecDeque<f32>,
34+ last_heard: Instant,
35+ started: bool,
36+}
37+
38+impl Speaker {
39+ fn new(sequence: u32, now: Instant) -> Self {
40+ Self {
41+ decoder: Decoder::new(VOICE_SAMPLE_RATE, 1).expect("opus decoder"),
42+ scratch: vec![0.0; MAX_DECODE_SAMPLES],
43+ jitter: BTreeMap::new(),
44+ next: sequence,
45+ pending: VecDeque::new(),
46+ last_heard: now,
47+ started: false,
48+ }
49+ }
50+
51+ fn next_frame(&mut self) -> Option<Vec<f32>> {
52+ if self.jitter.is_empty() {
53+ return None;
54+ }
55+ let decoded = match self.jitter.remove(&self.next) {
56+ Some(payload) => self.decoder.decode_float(&payload, &mut self.scratch),
57+ None => self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch),
58+ };
59+ self.next += 1;
60+
61+ Some(match decoded {
62+ Ok(samples) => self.scratch[..samples].to_vec(),
63+ Err(_) => vec![0.0; VOICE_FRAME_SAMPLES],
64+ })
65+ }
66+
67+ fn mix(&mut self, out: &mut [f32]) {
68+ for sample in out.iter_mut() {
69+ if self.pending.is_empty() {
70+ let Some(frame) = self.next_frame() else {
71+ self.started = false;
72+ return;
73+ };
74+ self.pending.extend(frame);
75+ }
76+ *sample += self.pending.pop_front().unwrap_or(0.0);
77+ }
78+ }
79+}
80+
81+pub struct Engine {
82+ encoder: Encoder,
83+ capture_buffer: Vec<f32>,
84+ sequence: u32,
85+ muted: bool,
86+ deafened: bool,
87+ gate: f32,
88+ input_gain: f32,
89+ output_gain: f32,
90+ push_to_talk: bool,
91+ talking: bool,
92+ hangover: u32,
93+ level_db: f32,
94+ speakers: HashMap<String, Speaker>,
95+}
96+
97+impl Default for Engine {
98+ fn default() -> Self {
99+ Self::new()
100+ }
101+}
102+
103+impl Engine {
104+ pub fn new() -> Self {
105+ let mut encoder =
106+ Encoder::new(VOICE_SAMPLE_RATE, 1, Application::Voip).expect("opus encoder");
107+ encoder.set_bitrate(VOICE_BITRATE as u32);
108+
109+ Self {
110+ encoder,
111+ capture_buffer: Vec::new(),
112+ sequence: 0,
113+ muted: false,
114+ deafened: false,
115+ gate: 0.0,
116+ input_gain: 1.0,
117+ output_gain: 1.0,
118+ push_to_talk: false,
119+ talking: false,
120+ hangover: 0,
121+ level_db: SILENT_DB,
122+ speakers: HashMap::new(),
123+ }
124+ }
125+
126+ pub fn capture(&mut self, samples: &[f32]) -> Vec<Vec<u8>> {
127+ self.capture_buffer.extend_from_slice(samples);
128+
129+ let full = self.capture_buffer.len() / VOICE_FRAME_SAMPLES * VOICE_FRAME_SAMPLES;
130+ let mut frames: Vec<f32> = self.capture_buffer.drain(..full).collect();
131+ for sample in &mut frames {
132+ *sample *= self.input_gain;
133+ }
134+
135+ let mut packets = Vec::new();
136+ for frame in frames.as_chunks::<VOICE_FRAME_SAMPLES>().0 {
137+ let loud = rms(frame);
138+ self.level_db = db(loud);
139+ if loud >= self.gate {
140+ self.hangover = HANGOVER_FRAMES;
141+ }
142+ let speaking = if self.push_to_talk {
143+ self.talking
144+ } else {
145+ self.hangover > 0
146+ };
147+ self.hangover = self.hangover.saturating_sub(1);
148+ if self.muted || self.deafened || !speaking {
149+ continue;
150+ }
151+
152+ let mut payload = [0u8; VOICE_MAX_PAYLOAD];
153+ let Ok(length) = self
154+ .encoder
155+ .encode_float(frame, VOICE_FRAME_SAMPLES, &mut payload)
156+ else {
157+ continue;
158+ };
159+
160+ packets.push(encode_packet(self.sequence, &payload[..length]));
161+ self.sequence = self.sequence.wrapping_add(1);
162+ }
163+
164+ packets
165+ }
166+
167+ pub fn receive(&mut self, datagram: &[u8]) {
168+ let Some((user_id, sequence, payload)) = decode_relay(datagram) else {
169+ return;
170+ };
171+ let now = Instant::now();
172+
173+ let stale = self
174+ .speakers
175+ .get(&user_id)
176+ .is_none_or(|speaker| now.duration_since(speaker.last_heard) > RESTART_AFTER);
177+ if stale {
178+ self.speakers
179+ .insert(user_id.clone(), Speaker::new(sequence, now));
180+ }
181+
182+ let Some(speaker) = self.speakers.get_mut(&user_id) else {
183+ return;
184+ };
185+ speaker.last_heard = now;
186+ if payload.is_empty() || sequence < speaker.next {
187+ return;
188+ }
189+
190+ speaker.jitter.insert(sequence, payload.to_vec());
191+ while speaker.jitter.len() > JITTER_CAPACITY {
192+ speaker.jitter.pop_first();
193+ }
194+ if speaker.jitter.len() >= START_FRAMES {
195+ speaker.started = true;
196+ }
197+ }
198+
199+ pub fn playback(&mut self, out: &mut [f32]) {
200+ out.fill(0.0);
201+ if self.deafened {
202+ return;
203+ }
204+
205+ for speaker in self.speakers.values_mut() {
206+ if speaker.started {
207+ speaker.mix(out);
208+ }
209+ }
210+
211+ for sample in out.iter_mut() {
212+ *sample = (*sample * self.output_gain).clamp(-1.0, 1.0);
213+ }
214+ }
215+
216+ pub fn speaking(&self) -> Vec<String> {
217+ let now = Instant::now();
218+
219+ self.speakers
220+ .iter()
221+ .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW)
222+ .map(|(user_id, _)| user_id.clone())
223+ .collect()
224+ }
225+
226+ pub fn forget(&mut self, user_id: &str) {
227+ self.speakers.remove(user_id);
228+ }
229+
230+ pub fn set_muted(&mut self, muted: bool) {
231+ self.muted = muted;
232+ }
233+
234+ pub fn set_deafened(&mut self, deafened: bool) {
235+ self.deafened = deafened;
236+ }
237+
238+ pub fn configure(
239+ &mut self,
240+ sensitivity_db: f32,
241+ input_volume: f32,
242+ output_volume: f32,
243+ push_to_talk: bool,
244+ ) {
245+ self.gate = 10f32.powf(sensitivity_db / 20.0);
246+ self.input_gain = input_volume / 100.0;
247+ self.output_gain = output_volume / 100.0;
248+ self.push_to_talk = push_to_talk;
249+ }
250+
251+ pub fn set_talking(&mut self, talking: bool) {
252+ self.talking = talking;
253+ }
254+
255+ pub fn level_db(&self) -> f32 {
256+ self.level_db
257+ }
258+
259+ pub fn output_gain(&self) -> f32 {
260+ self.output_gain
261+ }
262+}
263+
264+#[cfg(test)]
265+mod tests {
266+ use std::f32::consts::TAU;
267+
268+ use common::voice::encode_relay;
269+
270+ use super::*;
271+
272+ #[test]
273+ fn voice_round_trip() {
274+ let mut sender = Engine::new();
275+ let mut receiver = Engine::new();
276+ let user_id = "0190a3b4-c5d6-7e8f-9a0b-1c2d3e4f5a6b";
277+ let frames = 10;
278+
279+ let tone: Vec<f32> = (0..VOICE_FRAME_SAMPLES * frames)
280+ .map(|i| 0.5 * (TAU * 440.0 * i as f32 / VOICE_SAMPLE_RATE as f32).sin())
281+ .collect();
282+
283+ for packet in sender.capture(&tone) {
284+ let datagram = encode_relay(user_id, &packet).unwrap();
285+ receiver.receive(&datagram);
286+ }
287+
288+ let mut out = vec![0.0; VOICE_FRAME_SAMPLES * frames];
289+ receiver.playback(&mut out);
290+
291+ assert!(rms(&out) > 0.1);
292+ }
293+}
crates/client/src/voice/mod.rsadded+225 -0
@@ -0,0 +1,225 @@
1+use std::{
2+ sync::{
3+ Arc, Mutex,
4+ atomic::{AtomicBool, Ordering},
5+ },
6+ thread::JoinHandle,
7+ time::Duration,
8+};
9+
10+use bytes::Bytes;
11+use common::{
12+ constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE},
13+ voice::encode_relay,
14+};
15+use quinn::Connection;
16+use rtrb::{Consumer, Producer, RingBuffer};
17+use tracing::warn;
18+
19+pub mod audio;
20+pub mod engine;
21+
22+use crate::settings::{Activation, VoiceSettings};
23+use audio::{Audio, Choice};
24+use engine::{Engine, SILENT_DB};
25+
26+const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2;
27+const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2;
28+const TICK: Duration = Duration::from_millis(5);
29+const LOOPBACK: &str = "00000000-0000-0000-0000-000000000000";
30+const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)];
31+
32+pub type Capture = Arc<Mutex<Producer<f32>>>;
33+pub type Playback = Arc<Mutex<Consumer<f32>>>;
34+
35+pub struct Voice {
36+ engine: Arc<Mutex<Engine>>,
37+ stop: Arc<AtomicBool>,
38+ worker: Option<JoinHandle<()>>,
39+ capture: Capture,
40+ playback: Playback,
41+ choice: Choice,
42+ audio: Audio,
43+}
44+
45+pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice {
46+ let engine = Arc::new(Mutex::new(Engine::new()));
47+ let stop = Arc::new(AtomicBool::new(false));
48+ let (capture_producer, from_capture) = RingBuffer::new(RING_SAMPLES);
49+ let (to_playback, playback_consumer) = RingBuffer::new(RING_SAMPLES);
50+ let capture: Capture = Arc::new(Mutex::new(capture_producer));
51+ let playback: Playback = Arc::new(Mutex::new(playback_consumer));
52+
53+ let audio = audio::start(
54+ Some(capture.clone()),
55+ playback.clone(),
56+ settings.choice.clone(),
57+ );
58+ let worker = {
59+ let engine = engine.clone();
60+ let stop = stop.clone();
61+ std::thread::Builder::new()
62+ .name("voice-worker".to_string())
63+ .spawn(move || {
64+ work(
65+ &engine,
66+ connection.as_ref(),
67+ from_capture,
68+ to_playback,
69+ &stop,
70+ )
71+ })
72+ .inspect_err(|error| warn!("voice worker not started: {error}"))
73+ .ok()
74+ };
75+
76+ let mut voice = Voice {
77+ engine,
78+ stop,
79+ worker,
80+ capture,
81+ playback,
82+ choice: settings.choice.clone(),
83+ audio,
84+ };
85+ voice.apply(settings);
86+ voice
87+}
88+
89+pub fn play_chime(settings: &VoiceSettings) {
90+ let rate = VOICE_SAMPLE_RATE as f32;
91+ let gain = 0.3 * settings.output_volume / 100.0;
92+ let mut samples = Vec::new();
93+ for (frequency, seconds) in CHIME {
94+ let length = (rate * seconds) as usize;
95+ samples.extend((0..length).map(|index| {
96+ let time = index as f32 / rate;
97+ let fade = (1.0 - index as f32 / length as f32).powi(2);
98+ (std::f32::consts::TAU * frequency * time).sin() * fade * gain
99+ }));
100+ }
101+ let duration = Duration::from_secs_f32(samples.len() as f32 / rate + 0.3);
102+ let (mut producer, consumer) = RingBuffer::new(samples.len());
103+ for sample in samples {
104+ let _ = producer.push(sample);
105+ }
106+ let choice = settings.choice.clone();
107+
108+ let _ = std::thread::Builder::new()
109+ .name("chime".to_string())
110+ .spawn(move || {
111+ let _audio = audio::start(None, Arc::new(Mutex::new(consumer)), choice);
112+ std::thread::sleep(duration);
113+ });
114+}
115+
116+fn work(
117+ engine: &Mutex<Engine>,
118+ connection: Option<&Connection>,
119+ mut from_capture: Consumer<f32>,
120+ mut to_playback: Producer<f32>,
121+ stop: &AtomicBool,
122+) {
123+ let mut captured = Vec::with_capacity(RING_SAMPLES);
124+ let mut frame = vec![0.0; VOICE_FRAME_SAMPLES];
125+
126+ while !stop.load(Ordering::Relaxed) {
127+ captured.clear();
128+ while let Ok(sample) = from_capture.pop() {
129+ captured.push(sample);
130+ }
131+ let Ok(mut locked) = engine.lock() else {
132+ return;
133+ };
134+ for packet in locked.capture(&captured) {
135+ match connection {
136+ Some(connection) => {
137+ let _ = connection.send_datagram(Bytes::from(packet));
138+ }
139+ None => {
140+ if let Some(relay) = encode_relay(LOOPBACK, &packet) {
141+ locked.receive(&relay);
142+ }
143+ }
144+ }
145+ }
146+ while RING_SAMPLES - to_playback.slots() < PLAYBACK_AHEAD {
147+ locked.playback(&mut frame);
148+ for sample in &frame {
149+ let _ = to_playback.push(*sample);
150+ }
151+ }
152+ drop(locked);
153+
154+ std::thread::sleep(TICK);
155+ }
156+}
157+
158+impl Voice {
159+ pub fn apply(&mut self, settings: &VoiceSettings) {
160+ if settings.choice != self.choice {
161+ self.audio = Audio::Silent;
162+ self.audio = audio::start(
163+ Some(self.capture.clone()),
164+ self.playback.clone(),
165+ settings.choice.clone(),
166+ );
167+ self.choice = settings.choice.clone();
168+ }
169+
170+ if let Ok(mut engine) = self.engine.lock() {
171+ engine.configure(
172+ settings.sensitivity_db,
173+ settings.input_volume,
174+ settings.output_volume,
175+ settings.activation == Activation::PushToTalk,
176+ );
177+ }
178+ }
179+
180+ pub fn receive(&self, datagram: &[u8]) {
181+ if let Ok(mut engine) = self.engine.lock() {
182+ engine.receive(datagram);
183+ }
184+ }
185+
186+ pub fn speaking(&self) -> Vec<String> {
187+ self.engine
188+ .lock()
189+ .map(|engine| engine.speaking())
190+ .unwrap_or_default()
191+ }
192+
193+ pub fn level_db(&self) -> f32 {
194+ self.engine
195+ .lock()
196+ .map_or(SILENT_DB, |engine| engine.level_db())
197+ }
198+
199+ pub fn set_muted(&self, muted: bool) {
200+ if let Ok(mut engine) = self.engine.lock() {
201+ engine.set_muted(muted);
202+ }
203+ }
204+
205+ pub fn set_deafened(&self, deafened: bool) {
206+ if let Ok(mut engine) = self.engine.lock() {
207+ engine.set_deafened(deafened);
208+ }
209+ }
210+
211+ pub fn set_talking(&self, talking: bool) {
212+ if let Ok(mut engine) = self.engine.lock() {
213+ engine.set_talking(talking);
214+ }
215+ }
216+}
217+
218+impl Drop for Voice {
219+ fn drop(&mut self) {
220+ self.stop.store(true, Ordering::Relaxed);
221+ if let Some(worker) = self.worker.take() {
222+ let _ = worker.join();
223+ }
224+ }
225+}
crates/common/Cargo.tomlmodified+1 -0
@@ -7,6 +7,7 @@ edition = "2024"
7 bitcode.workspace = true7 bitcode.workspace = true
8 quinn.workspace = true8 quinn.workspace = true
9 thiserror = "2.0.21"9 thiserror = "2.0.21"
10+uuid = { version = "1.29.3", features = ["v7"] }
10 11
11 [lints]12 [lints]
12 workspace = true13 workspace = true
crates/common/src/constant.rsmodified+16 -0
@@ -7,3 +7,19 @@ pub const MINIMUM_MESSAGE_LENGTH: usize = 1;
7 pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16;7 pub const MAXIMUM_COMMUNITY_NAME_LENGTH: usize = 16;
8 pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3;8 pub const MINIMUM_COMMUNITY_NAME_LENGTH: usize = 3;
9 pub const MESSAGE_PAGE_LIMIT: usize = 50;9 pub const MESSAGE_PAGE_LIMIT: usize = 50;
10+pub const AVATAR_SIZE: u32 = 128;
11+pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024;
12+pub const MAXIMUM_STATUS_LENGTH: usize = 64;
13+pub const VOICE_SAMPLE_RATE: u32 = 48_000;
14+pub const VOICE_FRAME_SAMPLES: usize = 960;
15+pub const VOICE_BITRATE: i32 = 32_000;
16+pub const VOICE_MAX_PAYLOAD: usize = 1000;
17+pub const MAXIMUM_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;
18+pub const MAXIMUM_ATTACHMENTS_PER_MESSAGE: usize = 10;
19+pub const MAXIMUM_FORWARD_MESSAGES: usize = 20;
20+pub const MAXIMUM_QUOTE_LENGTH: usize = 120;
21+pub const MAXIMUM_REASON_LENGTH: usize = 128;
22+pub const MAXIMUM_ATTACHMENT_NAME_LENGTH: usize = 128;
23+pub const THUMBNAIL_SIZE: u32 = 400;
24+pub const ATTACHMENT_CHUNK_BYTES: usize = 64 * 1024;
25+pub const ATTACHMENT_HEAD_BYTES: usize = 64;
crates/common/src/error.rsmodified+47 -0
@@ -45,7 +45,21 @@ macro_rules! from_display {
45 pub enum InvalidInput {45 pub enum InvalidInput {
46 TooShort { minimum: usize, actual: usize },46 TooShort { minimum: usize, actual: usize },
47 TooLong { maximum: usize, actual: usize },47 TooLong { maximum: usize, actual: usize },
48+ TooLarge { maximum: u64, actual: u64 },
49+ Empty,
48 NotASCII,50 NotASCII,
51+ MultiLine,
52+ ForbiddenCharacter,
53+ NotJpeg,
54+ Dimensions { expected: u32 },
55+}
56+
57+pub fn size_text(size: u64) -> String {
58+ match size {
59+ size if size >= 1 << 20 => format!("{:.1} MB", size as f64 / (1 << 20) as f64),
60+ size if size >= 1 << 10 => format!("{:.0} KB", size as f64 / (1 << 10) as f64),
61+ size => format!("{size} B"),
62+ }
49 }63 }
50 64
51 impl Display for InvalidInput {65 impl Display for InvalidInput {
@@ -57,7 +71,22 @@ impl Display for InvalidInput {
57 InvalidInput::TooLong { maximum, actual } => {71 InvalidInput::TooLong { maximum, actual } => {
58 write!(f, "too long ({actual} > {maximum})")72 write!(f, "too long ({actual} > {maximum})")
59 }73 }
74+ InvalidInput::TooLarge { maximum, actual } => {
75+ write!(
76+ f,
77+ "too large: {} (max {})",
78+ size_text(*actual),
79+ size_text(*maximum)
80+ )
81+ }
82+ InvalidInput::Empty => write!(f, "empty"),
60 InvalidInput::NotASCII => write!(f, "not ASCII"),83 InvalidInput::NotASCII => write!(f, "not ASCII"),
84+ InvalidInput::MultiLine => write!(f, "contains line break"),
85+ InvalidInput::ForbiddenCharacter => write!(f, "contains forbidden character"),
86+ InvalidInput::NotJpeg => write!(f, "not JPEG"),
87+ InvalidInput::Dimensions { expected } => {
88+ write!(f, "must be {expected}x{expected} px")
89+ }
61 }90 }
62 }91 }
63 }92 }
@@ -94,8 +123,26 @@ pub enum Error {
94 Community(InvalidInput),123 Community(InvalidInput),
95 #[error("message: {0}")]124 #[error("message: {0}")]
96 Message(InvalidInput),125 Message(InvalidInput),
126+ #[error("status: {0}")]
127+ Status(InvalidInput),
128+ #[error("avatar: {0}")]
129+ Avatar(InvalidInput),
130+ #[error("file {0}")]
131+ Attachment(InvalidInput),
132+ #[error("file name: {0}")]
133+ AttachmentName(InvalidInput),
134+ #[error("reason: {0}")]
135+ Reason(InvalidInput),
136+ #[error("forward: {0}")]
137+ Forward(InvalidInput),
138+ #[error("upload: {0}")]
139+ Upload(String),
97 #[error("certificate: {0}")]140 #[error("certificate: {0}")]
98 Certificate(String),141 Certificate(String),
142+ #[error("already a member")]
143+ AlreadyMember,
144+ #[error("already invited")]
145+ AlreadyInvited,
99 }146 }
100 147
101 from_display! { Error {148 from_display! { Error {
crates/common/src/event.rsmodified+38 -4
@@ -1,14 +1,48 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3-use crate::model::{Community, Message, User};3+use crate::model::{Community, Friends, Invitation, Member, Message, Rank, User};
4 4
5 #[derive(Debug, Clone, Encode, Decode)]5 #[derive(Debug, Clone, Encode, Decode)]
6 pub enum Event {6 pub enum Event {
7 MessageCreated(Message),7 MessageCreated(Message),
8 MessageUpdated(Message),8 MessageUpdated(Message),
9 MessageDeleted(Message),9 MessageDeleted(Message),
10- MemberJoined { community_id: String, user: User },10+ MemberJoined {
11- MemberLeft { community_id: String, user_id: String },11+ community_id: String,
12+ member: Member,
13+ },
14+ MemberLeft {
15+ community_id: String,
16+ user_id: String,
17+ },
18+ RankChanged {
19+ community_id: String,
20+ user_id: String,
21+ rank: Rank,
22+ },
12 CommunityUpdated(Community),23 CommunityUpdated(Community),
13- CommunityDeleted { community_id: String },24+ CommunityAdded(Community),
25+ Removed {
26+ community_id: String,
27+ community_name: String,
28+ banned: bool,
29+ reason: Option<String>,
30+ },
31+ FriendsUpdated(Friends),
32+ InvitationsUpdated(Vec<Invitation>),
33+ CommunityDeleted {
34+ community_id: String,
35+ },
36+ UserDeleted {
37+ user_id: String,
38+ },
39+ UserUpdated(User),
40+ VoiceJoined {
41+ community_id: String,
42+ user_id: String,
43+ },
44+ VoiceLeft {
45+ community_id: String,
46+ user_id: String,
47+ },
14 }48 }
crates/common/src/lib.rsmodified+2 -0
@@ -4,6 +4,8 @@ pub mod error;
4 pub mod event;4 pub mod event;
5 pub mod model;5 pub mod model;
6 pub mod network;6 pub mod network;
7+pub mod permission;
7 pub mod request;8 pub mod request;
8 pub mod response;9 pub mod response;
9 pub mod validate;10 pub mod validate;
11+pub mod voice;
crates/common/src/model.rsmodified+182 -1
@@ -1,16 +1,193 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
4+pub enum Role {
5+ User,
6+ Staff,
7+}
8+
9+impl Role {
10+ pub fn as_str(self) -> &'static str {
11+ match self {
12+ Role::User => "user",
13+ Role::Staff => "staff",
14+ }
15+ }
16+
17+ pub fn parse(text: &str) -> Option<Self> {
18+ match text {
19+ "user" => Some(Role::User),
20+ "staff" => Some(Role::Staff),
21+ _ => None,
22+ }
23+ }
24+}
25+
26+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
27+pub enum Rank {
28+ Member,
29+ Moderator,
30+ Admin,
31+ Owner,
32+ Staff,
33+}
34+
35+impl Rank {
36+ pub fn as_str(self) -> &'static str {
37+ match self {
38+ Rank::Member => "member",
39+ Rank::Moderator => "moderator",
40+ Rank::Admin => "admin",
41+ Rank::Owner => "owner",
42+ Rank::Staff => "staff",
43+ }
44+ }
45+
46+ pub fn parse(text: &str) -> Option<Self> {
47+ match text {
48+ "member" => Some(Rank::Member),
49+ "moderator" => Some(Rank::Moderator),
50+ "admin" => Some(Rank::Admin),
51+ "owner" => Some(Rank::Owner),
52+ "staff" => Some(Rank::Staff),
53+ _ => None,
54+ }
55+ }
56+}
57+
3 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]58 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
4 pub struct User {59 pub struct User {
5 pub id: String,60 pub id: String,
6 pub username: String,61 pub username: String,
62+ pub role: Role,
63+ pub status: String,
64+ pub avatar_id: Option<String>,
65+}
66+
67+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
68+pub struct Member {
69+ pub user: User,
70+ pub rank: Rank,
71+}
72+
73+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
74+pub enum CommunityKind {
75+ Group,
76+ Direct { peer: User },
7 }77 }
8 78
9 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]79 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
10 pub struct Community {80 pub struct Community {
11 pub id: String,81 pub id: String,
12 pub name: String,82 pub name: String,
13- pub owner_id: String,83+ pub kind: CommunityKind,
84+ pub avatar_id: Option<String>,
85+}
86+
87+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
88+pub struct Ban {
89+ pub user: User,
90+ pub reason: Option<String>,
91+}
92+
93+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
94+pub enum LogAction {
95+ Created,
96+ Renamed { name: String },
97+ AvatarChanged,
98+ AvatarRemoved,
99+ Invited,
100+ Joined,
101+ Left,
102+ Kicked { reason: Option<String> },
103+ Banned { reason: Option<String> },
104+ Unbanned,
105+ RankChanged { rank: Rank },
106+ MessageDeleted,
107+}
108+
109+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
110+pub struct LogEntry {
111+ pub id: String,
112+ pub actor: Option<User>,
113+ pub target: Option<User>,
114+ pub action: LogAction,
115+}
116+
117+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
118+pub struct Invitation {
119+ pub community: Community,
120+ pub inviter: User,
121+}
122+
123+#[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)]
124+pub struct Friends {
125+ pub friends: Vec<User>,
126+ pub incoming: Vec<User>,
127+ pub outgoing: Vec<User>,
128+}
129+
130+#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
131+pub enum AttachmentKind {
132+ Image,
133+ Video,
134+ Audio,
135+ File,
136+}
137+
138+impl AttachmentKind {
139+ pub fn as_str(self) -> &'static str {
140+ match self {
141+ AttachmentKind::Image => "image",
142+ AttachmentKind::Video => "video",
143+ AttachmentKind::Audio => "audio",
144+ AttachmentKind::File => "file",
145+ }
146+ }
147+
148+ pub fn parse(text: &str) -> Option<Self> {
149+ match text {
150+ "image" => Some(AttachmentKind::Image),
151+ "video" => Some(AttachmentKind::Video),
152+ "audio" => Some(AttachmentKind::Audio),
153+ "file" => Some(AttachmentKind::File),
154+ _ => None,
155+ }
156+ }
157+}
158+
159+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
160+pub struct Attachment {
161+ pub id: String,
162+ pub name: String,
163+ pub size: u64,
164+ pub kind: AttachmentKind,
165+ pub width: Option<u32>,
166+ pub height: Option<u32>,
167+}
168+
169+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
170+pub struct Quote {
171+ pub message_id: String,
172+ pub user_id: String,
173+ pub body: String,
174+ pub attachments: usize,
175+}
176+
177+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
178+pub struct SnippetMessage {
179+ pub id: String,
180+ pub user_id: String,
181+ pub username: String,
182+ pub avatar_id: Option<String>,
183+ pub body: String,
184+ pub attachments: Vec<Attachment>,
185+}
186+
187+#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
188+pub struct Snippet {
189+ pub origin: Option<String>,
190+ pub messages: Vec<SnippetMessage>,
14 }191 }
15 192
16 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]193 #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
@@ -19,4 +196,8 @@ pub struct Message {
19 pub user_id: String,196 pub user_id: String,
20 pub community_id: String,197 pub community_id: String,
21 pub body: String,198 pub body: String,
199+ pub attachments: Vec<Attachment>,
200+ pub reply: Option<Quote>,
201+ pub snippet: Option<Snippet>,
202+ pub edited: bool,
22 }203 }
crates/common/src/network.rsmodified+144 -10
@@ -1,19 +1,154 @@
1+use bitcode::{DecodeOwned, Encode};
1 use quinn::{RecvStream, SendStream};2 use quinn::{RecvStream, SendStream};
2 3
3 use crate::{4 use crate::{
4- constant::{MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT},5+ constant::{
6+ MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_ATTACHMENTS_PER_MESSAGE, MAXIMUM_AVATAR_BYTES,
7+ MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, MESSAGE_PAGE_LIMIT,
8+ },
5 error::Error,9 error::Error,
6 event::Event,10 event::Event,
7- request::Request,11+ request::{DownloadRequest, Request, UploadHeader},
8 response::Response,12 response::Response,
9 };13 };
10 14
11-pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2;15+const ATTACHMENT_MAX_ENCODED_LENGTH: usize = MAXIMUM_ATTACHMENT_NAME_LENGTH * 4 + 128;
12-pub const EVENT_MAX_ENCODED_LENGTH: usize = MAXIMUM_MESSAGE_LENGTH * 2;16+pub const UPLOAD_HEADER_MAX_LENGTH: usize = 1024;
17+pub const DOWNLOAD_REQUEST_MAX_READ_LENGTH: usize = 1024;
18+
19+const MESSAGE_MAX_ENCODED_LENGTH: usize =
20+ MAXIMUM_MESSAGE_LENGTH * 2 + MAXIMUM_ATTACHMENTS_PER_MESSAGE * ATTACHMENT_MAX_ENCODED_LENGTH;
21+pub const REQUEST_MAX_READ_LENGTH: usize = MAXIMUM_AVATAR_BYTES + MESSAGE_MAX_ENCODED_LENGTH;
22+pub const EVENT_MAX_ENCODED_LENGTH: usize =
23+ MESSAGE_MAX_ENCODED_LENGTH * (MAXIMUM_FORWARD_MESSAGES + 2);
13 pub const RESPONSE_MAX_READ_LENGTH: usize = EVENT_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT;24 pub const RESPONSE_MAX_READ_LENGTH: usize = EVENT_MAX_ENCODED_LENGTH * MESSAGE_PAGE_LIMIT;
14 25
26+#[repr(u8)]
27+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28+pub enum StreamKind {
29+ Request = 0,
30+ Upload = 1,
31+ Download = 2,
32+}
33+
34+impl StreamKind {
35+ pub fn parse(byte: u8) -> Option<Self> {
36+ match byte {
37+ 0 => Some(StreamKind::Request),
38+ 1 => Some(StreamKind::Upload),
39+ 2 => Some(StreamKind::Download),
40+ _ => None,
41+ }
42+ }
43+}
44+
45+#[repr(u8)]
46+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47+pub enum DownloadStatus {
48+ Ok = 0,
49+ Error = 1,
50+}
51+
52+impl DownloadStatus {
53+ pub fn parse(byte: u8) -> Option<Self> {
54+ match byte {
55+ 0 => Some(DownloadStatus::Ok),
56+ 1 => Some(DownloadStatus::Error),
57+ _ => None,
58+ }
59+ }
60+}
61+
62+pub async fn send_stream_kind(kind: StreamKind, send_stream: &mut SendStream) -> Result<(), Error> {
63+ send_stream.write_all(&[kind as u8]).await?;
64+ Ok(())
65+}
66+
67+pub async fn receive_stream_kind(receive_stream: &mut RecvStream) -> Result<StreamKind, Error> {
68+ let mut byte = [0u8; 1];
69+ receive_stream.read_exact(&mut byte).await?;
70+
71+ StreamKind::parse(byte[0]).ok_or_else(|| Error::Decode(format!("stream kind {}", byte[0])))
72+}
73+
74+pub async fn send_download_status(
75+ status: DownloadStatus,
76+ send_stream: &mut SendStream,
77+) -> Result<(), Error> {
78+ send_stream.write_all(&[status as u8]).await?;
79+ Ok(())
80+}
81+
82+pub async fn receive_download_status(
83+ receive_stream: &mut RecvStream,
84+) -> Result<DownloadStatus, Error> {
85+ let mut byte = [0u8; 1];
86+ receive_stream.read_exact(&mut byte).await?;
87+
88+ DownloadStatus::parse(byte[0]).ok_or_else(|| Error::Decode(format!("status {}", byte[0])))
89+}
90+
91+pub async fn send_upload_header(
92+ header: &UploadHeader,
93+ send_stream: &mut SendStream,
94+) -> Result<(), Error> {
95+ let payload = bitcode::encode(header);
96+ send_stream
97+ .write_all(&(payload.len() as u32).to_le_bytes())
98+ .await?;
99+ send_stream.write_all(&payload).await?;
100+ Ok(())
101+}
102+
103+pub async fn receive_upload_header(receive_stream: &mut RecvStream) -> Result<UploadHeader, Error> {
104+ let mut length_bytes = [0u8; 4];
105+ receive_stream.read_exact(&mut length_bytes).await?;
106+
107+ let length = u32::from_le_bytes(length_bytes) as usize;
108+ if length > UPLOAD_HEADER_MAX_LENGTH {
109+ return Err(Error::ReadBoundExceed {
110+ actual: length,
111+ maximum: UPLOAD_HEADER_MAX_LENGTH,
112+ });
113+ }
114+
115+ let mut payload = vec![0u8; length];
116+ receive_stream.read_exact(&mut payload).await?;
117+ Ok(bitcode::decode(&payload)?)
118+}
119+
120+pub async fn send_download_request(
121+ request: &DownloadRequest,
122+ send_stream: &mut SendStream,
123+) -> Result<(), Error> {
124+ send_stream.write_all(&bitcode::encode(request)).await?;
125+ Ok(())
126+}
127+
128+pub async fn receive_download_request(
129+ receive_stream: &mut RecvStream,
130+) -> Result<DownloadRequest, Error> {
131+ let bytes = receive_stream
132+ .read_to_end(DOWNLOAD_REQUEST_MAX_READ_LENGTH)
133+ .await?;
134+ Ok(bitcode::decode(&bytes)?)
135+}
136+
137+pub async fn send_encoded<T: Encode>(value: &T, send_stream: &mut SendStream) -> Result<(), Error> {
138+ send_stream.write_all(&bitcode::encode(value)).await?;
139+ Ok(())
140+}
141+
142+pub async fn receive_decoded<T: DecodeOwned>(
143+ receive_stream: &mut RecvStream,
144+ limit: usize,
145+) -> Result<T, Error> {
146+ let bytes = receive_stream.read_to_end(limit).await?;
147+ Ok(bitcode::decode(&bytes)?)
148+}
149+
15 pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> {150 pub async fn send_response(response: &Response, mut send_stream: SendStream) -> Result<(), Error> {
16- send_stream.write_all(&bitcode::encode(response)).await?;151+ send_encoded(response, &mut send_stream).await?;
17 send_stream.finish()?;152 send_stream.finish()?;
18 Ok(())153 Ok(())
19 }154 }
@@ -22,8 +157,7 @@ pub async fn receive_request(
22 mut receive_stream: RecvStream,157 mut receive_stream: RecvStream,
23 limit: usize,158 limit: usize,
24 ) -> Result<Request, Error> {159 ) -> Result<Request, Error> {
25- let bytes = receive_stream.read_to_end(limit).await?;160+ receive_decoded(&mut receive_stream, limit).await
26- Ok(bitcode::decode(&bytes)?)
27 }161 }
28 162
29 pub async fn send_request(163 pub async fn send_request(
@@ -31,11 +165,11 @@ pub async fn send_request(
31 mut send_stream: SendStream,165 mut send_stream: SendStream,
32 mut receive_stream: RecvStream,166 mut receive_stream: RecvStream,
33 ) -> Result<Response, Error> {167 ) -> Result<Response, Error> {
34- send_stream.write_all(&bitcode::encode(request)).await?;168+ send_stream_kind(StreamKind::Request, &mut send_stream).await?;
169+ send_encoded(request, &mut send_stream).await?;
35 send_stream.finish()?;170 send_stream.finish()?;
36 171
37- let bytes = receive_stream.read_to_end(RESPONSE_MAX_READ_LENGTH).await?;172+ receive_decoded(&mut receive_stream, RESPONSE_MAX_READ_LENGTH).await
38- Ok(bitcode::decode(&bytes)?)
39 }173 }
40 174
41 pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> {175 pub async fn send_event(event: &Event, send_stream: &mut SendStream) -> Result<(), Error> {
crates/common/src/permission.rsadded+97 -0
@@ -0,0 +1,97 @@
1+use crate::model::{Rank, Role};
2+
3+pub fn effective_rank(role: Role, rank: Option<Rank>) -> Option<Rank> {
4+ match role {
5+ Role::Staff => Some(Rank::Staff),
6+ Role::User => rank,
7+ }
8+}
9+
10+pub fn can_read(actor: Option<Rank>) -> bool {
11+ actor.is_some()
12+}
13+
14+pub fn can_join_voice(actor: Option<Rank>) -> bool {
15+ actor.is_some()
16+}
17+
18+pub fn can_post(actor: Option<Rank>) -> bool {
19+ actor.is_some()
20+}
21+
22+pub fn can_join(role: Role, banned: bool) -> bool {
23+ !banned || role == Role::Staff
24+}
25+
26+pub fn can_edit_message(is_author: bool) -> bool {
27+ is_author
28+}
29+
30+pub fn can_delete_message(actor: Option<Rank>, author: Option<Rank>, is_author: bool) -> bool {
31+ is_author || (actor >= Some(Rank::Moderator) && actor > author)
32+}
33+
34+pub fn can_moderate(actor: Option<Rank>, target: Option<Rank>) -> bool {
35+ actor >= Some(Rank::Moderator) && actor > target && target != Some(Rank::Owner)
36+}
37+
38+pub fn can_unban(actor: Option<Rank>) -> bool {
39+ actor >= Some(Rank::Moderator)
40+}
41+
42+pub fn can_read_logs(actor: Option<Rank>) -> bool {
43+ actor >= Some(Rank::Moderator)
44+}
45+
46+pub fn can_set_rank(actor: Option<Rank>, target: Option<Rank>, new: Rank) -> bool {
47+ actor >= Some(Rank::Admin)
48+ && actor > target
49+ && Some(new) < actor
50+ && new != Rank::Owner
51+ && new != Rank::Staff
52+ && target.is_some()
53+ && target != Some(Rank::Owner)
54+}
55+
56+pub fn can_rename_community(actor: Option<Rank>) -> bool {
57+ actor >= Some(Rank::Admin)
58+}
59+
60+pub fn can_delete_community(actor: Option<Rank>) -> bool {
61+ actor >= Some(Rank::Owner)
62+}
63+
64+pub fn can_leave(actor: Option<Rank>) -> bool {
65+ actor.is_some() && actor != Some(Rank::Owner)
66+}
67+
68+pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool {
69+ is_self || (actor == Role::Staff && target != Role::Staff)
70+}
71+
72+#[cfg(test)]
73+mod tests {
74+ use super::*;
75+
76+ #[test]
77+ fn ordering_edges() {
78+ assert!(can_moderate(Some(Rank::Moderator), Some(Rank::Member)));
79+ assert!(!can_moderate(Some(Rank::Moderator), Some(Rank::Moderator)));
80+ assert!(!can_set_rank(
81+ Some(Rank::Admin),
82+ Some(Rank::Admin),
83+ Rank::Member
84+ ));
85+ assert!(!can_set_rank(
86+ Some(Rank::Admin),
87+ Some(Rank::Member),
88+ Rank::Admin
89+ ));
90+ assert!(!can_delete_message(
91+ Some(Rank::Moderator),
92+ Some(Rank::Moderator),
93+ false
94+ ));
95+ assert!(!can_leave(Some(Rank::Owner)));
96+ }
97+}
crates/common/src/request.rsmodified+150 -18
@@ -1,25 +1,157 @@
1 use bitcode::{Decode, Encode};1 use bitcode::{Decode, Encode};
2 2
3+use crate::model::Rank;
4+
5+#[derive(Debug, Clone, Encode, Decode)]
6+pub struct UploadHeader {
7+ pub community_id: String,
8+ pub name: String,
9+ pub size: u64,
10+}
11+
12+#[derive(Debug, Clone, Encode, Decode)]
13+pub struct DownloadRequest {
14+ pub attachment_id: String,
15+ pub thumbnail: bool,
16+}
17+
3 #[derive(Debug, Clone, Encode, Decode)]18 #[derive(Debug, Clone, Encode, Decode)]
4 pub enum Request {19 pub enum Request {
5- Register { username: String, password: String },20+ Register {
6- Login { username: String, password: String },21+ username: String,
7- Resume { token: String },22+ password: String,
23+ },
24+ Login {
25+ username: String,
26+ password: String,
27+ },
28+ Resume {
29+ token: String,
30+ },
8 Logout,31 Logout,
9- ReadUser { user_id: String },32+ ReadUser {
10- UpdateUser { username: String },33+ user_id: String,
11- DeleteUser,34+ },
12- CreateCommunity { name: String },35+ UpdateUser {
13- ReadCommunity { community_id: String },36+ username: String,
14- UpdateCommunity { community_id: String, name: String },37+ },
15- DeleteCommunity { community_id: String },38+ UpdateStatus {
16- SearchCommunity { name: String },39+ status: String,
17- JoinCommunity { community_id: String },40+ },
18- LeaveCommunity { community_id: String },41+ UpdateAvatar {
42+ image: Vec<u8>,
43+ },
44+ RemoveAvatar,
45+ ReadAvatar {
46+ avatar_id: String,
47+ },
48+ DeleteUser {
49+ user_id: String,
50+ },
51+ CreateCommunity {
52+ name: String,
53+ },
54+ ReadCommunity {
55+ community_id: String,
56+ },
57+ UpdateCommunity {
58+ community_id: String,
59+ name: String,
60+ },
61+ UpdateCommunityAvatar {
62+ community_id: String,
63+ image: Option<Vec<u8>>,
64+ },
65+ DeleteCommunity {
66+ community_id: String,
67+ },
68+ LeaveCommunity {
69+ community_id: String,
70+ },
19 Communities,71 Communities,
20- Members { community_id: String },72+ Members {
21- CreateMessage { community_id: String, body: String },73+ community_id: String,
22- UpdateMessage { message_id: String, body: String },74+ },
23- DeleteMessage { message_id: String },75+ Kick {
24- ReadMessages { community_id: String, before: Option<String> },76+ community_id: String,
77+ user_id: String,
78+ reason: Option<String>,
79+ },
80+ Ban {
81+ community_id: String,
82+ user_id: String,
83+ reason: Option<String>,
84+ },
85+ Unban {
86+ community_id: String,
87+ user_id: String,
88+ },
89+ Bans {
90+ community_id: String,
91+ },
92+ SetRank {
93+ community_id: String,
94+ user_id: String,
95+ rank: Rank,
96+ },
97+ CreateMessage {
98+ community_id: String,
99+ body: String,
100+ attachments: Vec<String>,
101+ reply_to: Option<String>,
102+ },
103+ ForwardMessages {
104+ message_ids: Vec<String>,
105+ community_id: String,
106+ snippet: bool,
107+ },
108+ UpdateMessage {
109+ message_id: String,
110+ body: String,
111+ },
112+ DeleteMessage {
113+ message_id: String,
114+ },
115+ ReadMessages {
116+ community_id: String,
117+ before: Option<String>,
118+ },
119+ JoinVoice {
120+ community_id: String,
121+ },
122+ LeaveVoice,
123+ VoiceParticipants {
124+ community_id: String,
125+ },
126+ FindUser {
127+ username: String,
128+ },
129+ OpenDirect {
130+ user_id: String,
131+ },
132+ Friends,
133+ AddFriend {
134+ user_id: String,
135+ },
136+ AcceptFriend {
137+ user_id: String,
138+ },
139+ RemoveFriend {
140+ user_id: String,
141+ },
142+ Invite {
143+ community_id: String,
144+ user_id: String,
145+ },
146+ Invitations,
147+ AcceptInvitation {
148+ community_id: String,
149+ },
150+ DeclineInvitation {
151+ community_id: String,
152+ },
153+ Detach,
154+ Logs {
155+ community_id: String,
156+ },
25 }157 }
crates/common/src/response.rsmodified+9 -2
@@ -2,18 +2,25 @@ use bitcode::{Decode, Encode};
2 2
3 use crate::{3 use crate::{
4 error::Error,4 error::Error,
5- model::{Community, Message, User},5+ model::{Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, User},
6 };6 };
7 7
8 #[derive(Debug, Clone, Encode, Decode)]8 #[derive(Debug, Clone, Encode, Decode)]
9 pub enum Response {9 pub enum Response {
10 Session { user: User, token: String },10 Session { user: User, token: String },
11 User(User),11 User(User),
12+ Avatar(Vec<u8>),
12 Community(Community),13 Community(Community),
13 Communities(Vec<Community>),14 Communities(Vec<Community>),
14- Members(Vec<User>),15+ Members(Vec<Member>),
16+ Bans(Vec<Ban>),
15 Message(Message),17 Message(Message),
16 Messages(Vec<Message>),18 Messages(Vec<Message>),
19+ Attachment(Attachment),
20+ Voice(Vec<String>),
21+ Friends(Friends),
22+ Invitations(Vec<Invitation>),
17 Done,23 Done,
18 Error(Error),24 Error(Error),
25+ Logs(Vec<LogEntry>),
19 }26 }
crates/common/src/validate.rsmodified+74 -23
@@ -1,12 +1,26 @@
1 use crate::{1 use crate::{
2 constant::{2 constant::{
3- MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_MESSAGE_LENGTH, MAXIMUM_PASSWORD_LENGTH,3+ MAXIMUM_ATTACHMENT_BYTES, MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_AVATAR_BYTES,
4+ MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH,
5+ MAXIMUM_PASSWORD_LENGTH, MAXIMUM_REASON_LENGTH, MAXIMUM_STATUS_LENGTH,
4 MAXIMUM_USERNAME_LENGTH, MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH,6 MAXIMUM_USERNAME_LENGTH, MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH,
5 MINIMUM_PASSWORD_LENGTH, MINIMUM_USERNAME_LENGTH,7 MINIMUM_PASSWORD_LENGTH, MINIMUM_USERNAME_LENGTH,
6 },8 },
7 error::{Error, InvalidInput},9 error::{Error, InvalidInput},
8 };10 };
9 11
12+fn check_length(actual: usize, minimum: usize, maximum: usize) -> Result<(), InvalidInput> {
13+ if actual < minimum {
14+ return Err(InvalidInput::TooShort { minimum, actual });
15+ }
16+
17+ if actual > maximum {
18+ return Err(InvalidInput::TooLong { maximum, actual });
19+ }
20+
21+ Ok(())
22+}
23+
10 fn check(24 fn check(
11 input: &str,25 input: &str,
12 minimum: usize,26 minimum: usize,
@@ -17,21 +31,7 @@ fn check(
17 return Err(InvalidInput::NotASCII);31 return Err(InvalidInput::NotASCII);
18 }32 }
19 33
20- if input.len() < minimum {34+ check_length(input.len(), minimum, maximum)
21- return Err(InvalidInput::TooShort {
22- minimum,
23- actual: input.len(),
24- });
25- }
26-
27- if input.len() > maximum {
28- return Err(InvalidInput::TooLong {
29- maximum,
30- actual: input.len(),
31- });
32- }
33-
34- Ok(())
35 }35 }
36 36
37 pub fn validate_username(username: &str) -> Result<(), Error> {37 pub fn validate_username(username: &str) -> Result<(), Error> {
@@ -65,11 +65,62 @@ pub fn validate_community_name(name: &str) -> Result<(), Error> {
65 }65 }
66 66
67 pub fn validate_message_body(body: &str) -> Result<(), Error> {67 pub fn validate_message_body(body: &str) -> Result<(), Error> {
68- check(68+ check(body, MINIMUM_MESSAGE_LENGTH, MAXIMUM_MESSAGE_LENGTH, false).map_err(Error::Message)
69- body,69+}
70- MINIMUM_MESSAGE_LENGTH,70+
71- MAXIMUM_MESSAGE_LENGTH,71+pub fn validate_new_message(body: &str, attachments: usize) -> Result<(), Error> {
72- false,72+ if attachments == 0 {
73- )73+ return validate_message_body(body);
74- .map_err(Error::Message)74+ }
75+
76+ check(body, 0, MAXIMUM_MESSAGE_LENGTH, false).map_err(Error::Message)
77+}
78+
79+pub fn validate_attachment_name(name: &str) -> Result<(), Error> {
80+ check_length(name.chars().count(), 1, MAXIMUM_ATTACHMENT_NAME_LENGTH)
81+ .map_err(Error::AttachmentName)?;
82+
83+ if name.contains(['/', '\\']) || name.chars().any(char::is_control) {
84+ return Err(Error::AttachmentName(InvalidInput::ForbiddenCharacter));
85+ }
86+
87+ Ok(())
88+}
89+
90+fn check_size(actual: u64, maximum: u64) -> Result<(), InvalidInput> {
91+ match actual {
92+ 0 => Err(InvalidInput::Empty),
93+ actual if actual > maximum => Err(InvalidInput::TooLarge { maximum, actual }),
94+ _ => Ok(()),
95+ }
96+}
97+
98+pub fn validate_attachment_size(size: u64) -> Result<(), Error> {
99+ check_size(size, MAXIMUM_ATTACHMENT_BYTES).map_err(Error::Attachment)
100+}
101+
102+pub fn validate_reason(reason: Option<&str>) -> Result<(), Error> {
103+ let Some(reason) = reason else {
104+ return Ok(());
105+ };
106+ if reason.contains(['\n', '\r']) {
107+ return Err(Error::Reason(InvalidInput::MultiLine));
108+ }
109+ check_length(reason.chars().count(), 1, MAXIMUM_REASON_LENGTH).map_err(Error::Reason)
110+}
111+
112+pub fn validate_forward(count: usize) -> Result<(), Error> {
113+ check_length(count, 1, MAXIMUM_FORWARD_MESSAGES).map_err(Error::Forward)
114+}
115+
116+pub fn validate_status(status: &str) -> Result<(), Error> {
117+ if status.contains(['\n', '\r']) {
118+ return Err(Error::Status(InvalidInput::MultiLine));
119+ }
120+
121+ check_length(status.chars().count(), 0, MAXIMUM_STATUS_LENGTH).map_err(Error::Status)
122+}
123+
124+pub fn validate_avatar_size(bytes: &[u8]) -> Result<(), Error> {
125+ check_size(bytes.len() as u64, MAXIMUM_AVATAR_BYTES as u64).map_err(Error::Avatar)
75 }126 }
crates/common/src/voice.rsadded+54 -0
@@ -0,0 +1,54 @@
1+use uuid::Uuid;
2+
3+use crate::constant::VOICE_MAX_PAYLOAD;
4+
5+pub const SEQUENCE_LENGTH: usize = 4;
6+const USER_ID_LENGTH: usize = 16;
7+
8+pub fn encode_packet(sequence: u32, payload: &[u8]) -> Vec<u8> {
9+ let mut bytes = sequence.to_be_bytes().to_vec();
10+ bytes.extend_from_slice(payload);
11+ bytes
12+}
13+
14+pub fn decode_packet(bytes: &[u8]) -> Option<(u32, &[u8])> {
15+ if bytes.len() < SEQUENCE_LENGTH || bytes.len() - SEQUENCE_LENGTH > VOICE_MAX_PAYLOAD {
16+ return None;
17+ }
18+ let sequence = u32::from_be_bytes(bytes[..SEQUENCE_LENGTH].try_into().ok()?);
19+
20+ Some((sequence, &bytes[SEQUENCE_LENGTH..]))
21+}
22+
23+pub fn encode_relay(user_id: &str, packet: &[u8]) -> Option<Vec<u8>> {
24+ let user_id = Uuid::parse_str(user_id).ok()?;
25+ let mut bytes = user_id.as_bytes().to_vec();
26+ bytes.extend_from_slice(packet);
27+
28+ Some(bytes)
29+}
30+
31+pub fn decode_relay(bytes: &[u8]) -> Option<(String, u32, &[u8])> {
32+ let user_id = Uuid::from_slice(bytes.get(..USER_ID_LENGTH)?).ok()?;
33+ let (sequence, payload) = decode_packet(&bytes[USER_ID_LENGTH..])?;
34+
35+ Some((user_id.to_string(), sequence, payload))
36+}
37+
38+#[cfg(test)]
39+mod tests {
40+ use super::*;
41+
42+ #[test]
43+ fn relay_round_trip() {
44+ let user_id = Uuid::now_v7().to_string();
45+ let packet = encode_packet(7, &[1, 2, 3]);
46+ let relay = encode_relay(&user_id, &packet).unwrap();
47+
48+ let (decoded_id, sequence, payload) = decode_relay(&relay).unwrap();
49+
50+ assert_eq!(decoded_id, user_id);
51+ assert_eq!(sequence, 7);
52+ assert_eq!(payload, &[1, 2, 3]);
53+ }
54+}
crates/server/Cargo.tomlmodified+3 -1
@@ -11,9 +11,11 @@ rcgen = "0.14.10"
11 bitcode.workspace = true11 bitcode.workspace = true
12 rustls.workspace = true12 rustls.workspace = true
13 turso = "0.9.0-pre.6"13 turso = "0.9.0-pre.6"
14-ulid = "3.0.0"14+uuid = { version = "1.29.3", features = ["v7"] }
15+bytes = "1.12.2"
15 argon2 = "0.6.0"16 argon2 = "0.6.0"
16 getrandom = "0.4.3"17 getrandom = "0.4.3"
18+image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] }
17 thiserror = "2.0.21"19 thiserror = "2.0.21"
18 tracing = "0.1.44"20 tracing = "0.1.44"
19 tracing-subscriber = "0.3.23"21 tracing-subscriber = "0.3.23"
crates/server/src/attachment.rsadded+560 -0
@@ -0,0 +1,560 @@
1+use std::{
2+ collections::HashSet,
3+ io::{BufReader, Cursor},
4+ path::{Path, PathBuf},
5+ time::{Duration, SystemTime},
6+};
7+
8+use common::{
9+ constant::{
10+ ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, MAXIMUM_ATTACHMENTS_PER_MESSAGE,
11+ THUMBNAIL_SIZE,
12+ },
13+ error::Error as CommonError,
14+ model::{Attachment, AttachmentKind, User},
15+ network::{
16+ DownloadStatus, receive_download_request, receive_upload_header, send_download_status,
17+ send_encoded, send_response,
18+ },
19+ permission,
20+ request::{DownloadRequest, UploadHeader},
21+ response::Response,
22+ validate::{validate_attachment_name, validate_attachment_size},
23+};
24+use image::{ImageFormat, ImageReader, Limits};
25+use quinn::{RecvStream, SendStream, VarInt};
26+use tokio::{
27+ fs::File,
28+ io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
29+};
30+use tracing::error;
31+use turso::{Connection, Row};
32+use uuid::{Timestamp, Uuid};
33+
34+use crate::{
35+ database::{self, DB, new_id},
36+ error::Error,
37+ request::{actor_rank, ensure},
38+};
39+
40+const COLLECT_INTERVAL: Duration = Duration::from_secs(600);
41+const STALE_AGE: Duration = Duration::from_secs(3600);
42+const MAXIMUM_IMAGE_SIDE: u32 = 16384;
43+const MAXIMUM_DECODE_BYTES: u64 = 256 * 1024 * 1024;
44+
45+pub struct Stored {
46+ pub attachment: Attachment,
47+ pub uploader_id: String,
48+ pub community_id: String,
49+ pub bound: bool,
50+}
51+
52+pub fn directory(database_path: &str) -> Result<PathBuf, Error> {
53+ let directory = Path::new(database_path)
54+ .parent()
55+ .unwrap_or_else(|| Path::new(""))
56+ .join("attachments");
57+ std::fs::create_dir_all(&directory)?;
58+
59+ Ok(directory)
60+}
61+
62+fn from_row(row: &Row) -> Result<Attachment, Error> {
63+ let size: i64 = row.get(2)?;
64+ let kind: String = row.get(3)?;
65+ let width: Option<i64> = row.get(4)?;
66+ let height: Option<i64> = row.get(5)?;
67+
68+ Ok(Attachment {
69+ id: row.get(0)?,
70+ name: row.get(1)?,
71+ size: size as u64,
72+ kind: AttachmentKind::parse(&kind).ok_or(CommonError::Server)?,
73+ width: width.map(|value| value as u32),
74+ height: height.map(|value| value as u32),
75+ })
76+}
77+
78+pub async fn of_message(
79+ message_id: &str,
80+ snippet_position: Option<i64>,
81+ conn: &Connection,
82+) -> Result<Vec<Attachment>, Error> {
83+ let mut rows = conn
84+ .query(
85+ "SELECT id, name, size, kind, width, height FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id",
86+ (message_id, snippet_position),
87+ )
88+ .await?;
89+
90+ let mut attachments = Vec::new();
91+ while let Some(row) = rows.next().await? {
92+ attachments.push(from_row(&row)?);
93+ }
94+
95+ Ok(attachments)
96+}
97+
98+pub async fn bind(
99+ message_id: &str,
100+ user_id: &str,
101+ community_id: &str,
102+ attachment_ids: &[String],
103+ conn: &Connection,
104+) -> Result<(), Error> {
105+ if attachment_ids.len() > MAXIMUM_ATTACHMENTS_PER_MESSAGE {
106+ return Err(CommonError::NotFound.into());
107+ }
108+
109+ for attachment_id in attachment_ids {
110+ let bound = conn
111+ .execute(
112+ "UPDATE attachment SET message_id = ?1 WHERE id = ?2 AND uploader_id = ?3 AND community_id = ?4 AND message_id IS NULL",
113+ (message_id, attachment_id.as_str(), user_id, community_id),
114+ )
115+ .await?;
116+ if bound != 1 {
117+ return Err(CommonError::NotFound.into());
118+ }
119+ }
120+
121+ Ok(())
122+}
123+
124+fn link_or_copy(source: &Path, target: &Path) -> std::io::Result<()> {
125+ std::fs::hard_link(source, target).or_else(|_| std::fs::copy(source, target).map(drop))
126+}
127+
128+async fn duplicate(source: PathBuf, target: PathBuf) -> Result<(), Error> {
129+ tokio::task::spawn_blocking(move || link_or_copy(&source, &target))
130+ .await
131+ .map_err(|_| CommonError::Server)?
132+ .map_err(|_| CommonError::Server)?;
133+
134+ Ok(())
135+}
136+
137+pub async fn copy(
138+ attachment: &Attachment,
139+ message_id: &str,
140+ user_id: &str,
141+ community_id: &str,
142+ snippet_position: Option<i64>,
143+ directory: &Path,
144+ conn: &Connection,
145+) -> Result<(), Error> {
146+ let id = new_id();
147+ conn.execute(
148+ "INSERT INTO attachment (id, uploader_id, community_id, message_id, name, size, kind, width, height, snippet_position) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
149+ (
150+ id.as_str(),
151+ user_id,
152+ community_id,
153+ message_id,
154+ attachment.name.as_str(),
155+ attachment.size as i64,
156+ attachment.kind.as_str(),
157+ attachment.width.map(i64::from),
158+ attachment.height.map(i64::from),
159+ snippet_position,
160+ ),
161+ )
162+ .await?;
163+
164+ duplicate(directory.join(&attachment.id), directory.join(&id)).await?;
165+ let thumbnail = directory.join(format!("{}.thumb", attachment.id));
166+ if tokio::fs::try_exists(&thumbnail)
167+ .await
168+ .map_err(|_| CommonError::Server)?
169+ {
170+ duplicate(thumbnail, directory.join(format!("{id}.thumb"))).await?;
171+ }
172+
173+ Ok(())
174+}
175+
176+async fn read(attachment_id: &str, conn: &Connection) -> Result<Stored, Error> {
177+ let mut rows = conn
178+ .query(
179+ "SELECT id, name, size, kind, width, height, uploader_id, community_id, message_id IS NOT NULL FROM attachment WHERE id = ?1",
180+ (attachment_id,),
181+ )
182+ .await?;
183+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
184+ let bound: i64 = row.get(8)?;
185+
186+ Ok(Stored {
187+ attachment: from_row(&row)?,
188+ uploader_id: row.get(6)?,
189+ community_id: row.get(7)?,
190+ bound: bound != 0,
191+ })
192+}
193+
194+fn media_kind(head: &[u8]) -> AttachmentKind {
195+ if is_video(head) {
196+ AttachmentKind::Video
197+ } else if is_audio(head) {
198+ AttachmentKind::Audio
199+ } else {
200+ AttachmentKind::File
201+ }
202+}
203+
204+fn is_image(head: &[u8]) -> bool {
205+ matches!(
206+ image::guess_format(head),
207+ Ok(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP)
208+ )
209+}
210+
211+fn is_video(head: &[u8]) -> bool {
212+ head.get(4..8) == Some(b"ftyp") || head.starts_with(&[0x1A, 0x45, 0xDF, 0xA3])
213+}
214+
215+fn is_audio(head: &[u8]) -> bool {
216+ head.starts_with(b"OggS")
217+ || head.starts_with(b"fLaC")
218+ || head.starts_with(b"ID3")
219+ || head.starts_with(&[0xFF, 0xFB])
220+ || head.starts_with(&[0xFF, 0xF3])
221+ || head.starts_with(&[0xFF, 0xF2])
222+ || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WAVE"))
223+}
224+
225+fn decode_thumbnail(source: &Path, thumbnail: &Path) -> Option<(u32, u32)> {
226+ let mut reader = ImageReader::new(BufReader::new(std::fs::File::open(source).ok()?))
227+ .with_guessed_format()
228+ .ok()?;
229+ let mut limits = Limits::default();
230+ limits.max_image_width = Some(MAXIMUM_IMAGE_SIDE);
231+ limits.max_image_height = Some(MAXIMUM_IMAGE_SIDE);
232+ limits.max_alloc = Some(MAXIMUM_DECODE_BYTES);
233+ reader.limits(limits);
234+ let image = reader.decode().ok()?;
235+ let (width, height) = (image.width(), image.height());
236+
237+ let fitted = if width > THUMBNAIL_SIZE || height > THUMBNAIL_SIZE {
238+ image.thumbnail(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
239+ } else {
240+ image
241+ };
242+ let mut bytes = Cursor::new(Vec::new());
243+ fitted
244+ .to_rgb8()
245+ .write_to(&mut bytes, ImageFormat::Jpeg)
246+ .ok()?;
247+ std::fs::write(thumbnail, bytes.into_inner()).ok()?;
248+
249+ Some((width, height))
250+}
251+
252+async fn receive_body<R: AsyncRead + Unpin>(
253+ reader: &mut R,
254+ part: &Path,
255+ size: u64,
256+) -> Result<Vec<u8>, Error> {
257+ let mismatch = || CommonError::Upload("size mismatch".to_string());
258+ let mut file = File::create(part).await?;
259+
260+ let mut head = vec![0u8; (ATTACHMENT_HEAD_BYTES as u64).min(size) as usize];
261+ reader.read_exact(&mut head).await?;
262+ file.write_all(&head).await?;
263+
264+ let mut received = head.len() as u64;
265+ let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
266+ loop {
267+ let read = reader.read(&mut buffer).await?;
268+ if read == 0 {
269+ break;
270+ }
271+
272+ received += read as u64;
273+ if received > size {
274+ return Err(mismatch().into());
275+ }
276+ file.write_all(&buffer[..read]).await?;
277+ }
278+
279+ if received != size {
280+ return Err(mismatch().into());
281+ }
282+ file.flush().await?;
283+
284+ Ok(head)
285+}
286+
287+pub async fn store<R: AsyncRead + Unpin>(
288+ user: &User,
289+ header: &UploadHeader,
290+ reader: &mut R,
291+ db: &DB,
292+ directory: &Path,
293+) -> Result<Attachment, Error> {
294+ let conn = database::connect(db).await?;
295+ let rank = actor_rank(user, &header.community_id, &conn).await?;
296+ ensure(permission::can_post(rank))?;
297+ validate_attachment_name(&header.name)?;
298+ validate_attachment_size(header.size)?;
299+
300+ let id = new_id();
301+ let part = directory.join(format!("{id}.part"));
302+ let path = directory.join(&id);
303+ let head = match receive_body(reader, &part, header.size).await {
304+ Ok(head) => head,
305+ Err(error) => {
306+ let _ = tokio::fs::remove_file(&part).await;
307+ return Err(error);
308+ }
309+ };
310+ tokio::fs::rename(&part, &path).await?;
311+
312+ let described = if is_image(&head) {
313+ let source = path.clone();
314+ let thumbnail = directory.join(format!("{id}.thumb"));
315+ tokio::task::spawn_blocking(move || decode_thumbnail(&source, &thumbnail))
316+ .await
317+ .ok()
318+ .flatten()
319+ } else {
320+ None
321+ };
322+ let (kind, width, height) = match described {
323+ Some((width, height)) => (AttachmentKind::Image, Some(width), Some(height)),
324+ None => (media_kind(&head), None, None),
325+ };
326+
327+ let mut rows = conn
328+ .query(
329+ "INSERT INTO attachment (id, uploader_id, community_id, name, size, kind, width, height) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) RETURNING id, name, size, kind, width, height",
330+ (
331+ id.as_str(),
332+ user.id.as_str(),
333+ header.community_id.as_str(),
334+ header.name.as_str(),
335+ header.size as i64,
336+ kind.as_str(),
337+ width.map(i64::from),
338+ height.map(i64::from),
339+ ),
340+ )
341+ .await?;
342+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
343+
344+ from_row(&row)
345+}
346+
347+pub async fn upload(
348+ user: Option<&User>,
349+ mut receive_stream: RecvStream,
350+ send_stream: SendStream,
351+ db: &DB,
352+ directory: &Path,
353+) -> Result<(), Error> {
354+ let header = receive_upload_header(&mut receive_stream).await?;
355+ let stored = match user {
356+ Some(user) => store(user, &header, &mut receive_stream, db, directory).await,
357+ None => Err(CommonError::Unauthenticated.into()),
358+ };
359+
360+ let response = match stored {
361+ Ok(attachment) => Response::Attachment(attachment),
362+ Err(error) => {
363+ let _ = receive_stream.stop(VarInt::from_u32(0));
364+ Response::Error(error.into())
365+ }
366+ };
367+ send_response(&response, send_stream).await?;
368+
369+ Ok(())
370+}
371+
372+async fn locate(
373+ user: Option<&User>,
374+ request: &DownloadRequest,
375+ db: &DB,
376+ directory: &Path,
377+) -> Result<(PathBuf, u64), Error> {
378+ let user = user.ok_or(CommonError::Unauthenticated)?;
379+ let conn = database::connect(db).await?;
380+ let stored = read(&request.attachment_id, &conn).await?;
381+
382+ let rank = actor_rank(user, &stored.community_id, &conn).await?;
383+ ensure(permission::can_read(rank))?;
384+ ensure(stored.bound || stored.uploader_id == user.id)?;
385+
386+ let path = if request.thumbnail {
387+ directory.join(format!("{}.thumb", stored.attachment.id))
388+ } else {
389+ directory.join(&stored.attachment.id)
390+ };
391+ let length = tokio::fs::metadata(&path)
392+ .await
393+ .map_err(|_| CommonError::NotFound)?
394+ .len();
395+
396+ Ok((path, length))
397+}
398+
399+async fn stream_file(path: &Path, send_stream: &mut SendStream) -> Result<(), Error> {
400+ let mut file = File::open(path).await?;
401+ let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES];
402+ loop {
403+ let read = file.read(&mut buffer).await?;
404+ if read == 0 {
405+ return Ok(());
406+ }
407+
408+ send_stream.write_all(&buffer[..read]).await?;
409+ }
410+}
411+
412+pub async fn download(
413+ user: Option<&User>,
414+ mut receive_stream: RecvStream,
415+ mut send_stream: SendStream,
416+ db: &DB,
417+ directory: &Path,
418+) -> Result<(), Error> {
419+ let request = receive_download_request(&mut receive_stream).await?;
420+
421+ match locate(user, &request, db, directory).await {
422+ Ok((path, length)) => {
423+ send_download_status(DownloadStatus::Ok, &mut send_stream).await?;
424+ send_stream.write_all(&length.to_le_bytes()).await?;
425+ stream_file(&path, &mut send_stream).await?;
426+ }
427+ Err(error) => {
428+ let error: CommonError = error.into();
429+ send_download_status(DownloadStatus::Error, &mut send_stream).await?;
430+ send_encoded(&error, &mut send_stream).await?;
431+ }
432+ }
433+ send_stream.finish()?;
434+
435+ Ok(())
436+}
437+
438+pub async fn collect(db: DB, directory: PathBuf) {
439+ let mut interval = tokio::time::interval(COLLECT_INTERVAL);
440+ loop {
441+ interval.tick().await;
442+ if let Err(error) = sweep(&db, &directory).await {
443+ error!("attachment sweep: {error}");
444+ }
445+ }
446+}
447+
448+async fn sweep(db: &DB, directory: &Path) -> Result<(), Error> {
449+ let conn = database::connect(db).await?;
450+ let stale_at = SystemTime::now() - STALE_AGE;
451+ let stale_secs = stale_at
452+ .duration_since(SystemTime::UNIX_EPOCH)
453+ .unwrap_or_default()
454+ .as_secs();
455+ let stale_id = Uuid::new_v7(Timestamp::from_unix_time(stale_secs, 0, 0, 0)).to_string();
456+
457+ conn.execute(
458+ "DELETE FROM attachment WHERE message_id IS NULL AND id < ?1",
459+ (stale_id.as_str(),),
460+ )
461+ .await?;
462+
463+ let mut rows = conn.query("SELECT id FROM attachment", ()).await?;
464+ let mut ids = HashSet::new();
465+ while let Some(row) = rows.next().await? {
466+ ids.insert(row.get::<String>(0)?);
467+ }
468+ drop(rows);
469+
470+ for entry in std::fs::read_dir(directory)? {
471+ let entry = entry?;
472+ let name = entry.file_name().to_string_lossy().into_owned();
473+ let id = name
474+ .strip_suffix(".thumb")
475+ .or_else(|| name.strip_suffix(".part"))
476+ .unwrap_or(&name);
477+ let stale = entry.metadata()?.modified()? < stale_at;
478+
479+ if stale && !ids.contains(id) {
480+ std::fs::remove_file(entry.path())?;
481+ }
482+ }
483+
484+ Ok(())
485+}
486+
487+#[cfg(test)]
488+mod tests {
489+ use std::{io::Cursor, path::Path, sync::Mutex};
490+
491+ use common::{
492+ model::{AttachmentKind, Rank},
493+ request::{Request, UploadHeader},
494+ };
495+ use image::{ImageFormat, RgbImage};
496+
497+ use crate::{
498+ attachment::store, community, database, message, network::State, request::handle, test,
499+ user, user_community, voice::Voice,
500+ };
501+
502+ #[tokio::test]
503+ async fn upload_then_read_in_message() {
504+ let db = test::get_database().await;
505+ let conn = database::connect(&db).await.unwrap();
506+ let user = user::create("Tahinli", "hash", &conn).await.unwrap();
507+ let community = community::create("Tahinli", &conn).await.unwrap();
508+ user_community::join(&user.id, &community.id, Rank::Member, &conn)
509+ .await
510+ .unwrap();
511+
512+ let mut png = Cursor::new(Vec::new());
513+ RgbImage::new(2, 3)
514+ .write_to(&mut png, ImageFormat::Png)
515+ .unwrap();
516+ let png = png.into_inner();
517+ let directory = Path::new(concat!(
518+ env!("CARGO_MANIFEST_DIR"),
519+ "/../../target/attachment-tests"
520+ ));
521+ std::fs::create_dir_all(directory).unwrap();
522+ let header = UploadHeader {
523+ community_id: community.id.clone(),
524+ name: "pixel.png".to_string(),
525+ size: png.len() as u64,
526+ };
527+ let attachment = store(&user, &header, &mut png.as_slice(), &db, directory)
528+ .await
529+ .unwrap();
530+
531+ let state = Mutex::new(State::Authenticated {
532+ user: user.clone(),
533+ token: "token".to_string(),
534+ });
535+ handle(
536+ Request::CreateMessage {
537+ community_id: community.id.clone(),
538+ body: String::new(),
539+ attachments: vec![attachment.id.clone()],
540+ reply_to: None,
541+ },
542+ &state,
543+ &db,
544+ &Voice::default(),
545+ None,
546+ &test::directory(),
547+ )
548+ .await;
549+
550+ let messages = message::read_page(&community.id, None, &conn)
551+ .await
552+ .unwrap();
553+ assert_eq!(vec![attachment.clone()], messages[0].attachments);
554+ assert_eq!(AttachmentKind::Image, attachment.kind);
555+ assert_eq!((Some(2), Some(3)), (attachment.width, attachment.height));
556+
557+ std::fs::remove_file(directory.join(&attachment.id)).unwrap();
558+ std::fs::remove_file(directory.join(format!("{}.thumb", attachment.id))).unwrap();
559+ }
560+}
crates/server/src/authentication.rsmodified+1 -1
@@ -84,7 +84,7 @@ pub async fn login(
84 pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> {84 pub async fn resume(token: &str, conn: &Connection) -> Result<User, Error> {
85 let mut rows = conn85 let mut rows = conn
86 .query(86 .query(
87- "SELECT user.id, user.username FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1",87+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM session JOIN user ON user.id = session.user_id WHERE session.token = ?1",
88 (token,),88 (token,),
89 )89 )
90 .await?;90 .await?;
crates/server/src/certificate.rsmodified+2 -1
@@ -108,7 +108,8 @@ pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfi
108 .with_cert_resolver(reloader.clone());108 .with_cert_resolver(reloader.clone());
109 tls.max_early_data_size = u32::MAX;109 tls.max_early_data_size = u32::MAX;
110 110
111- let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;111+ let crypto =
112+ quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;
112 113
113 tokio::spawn(watch(114 tokio::spawn(watch(
114 reloader,115 reloader,
crates/server/src/community.rsmodified+198 -97
@@ -1,98 +1,223 @@
1-use common::{error::Error as CommonError, model::Community, validate::validate_community_name};1+use common::{
2+ error::Error as CommonError,
3+ model::{Community, CommunityKind, User},
4+ validate::validate_community_name,
5+};
2 use turso::{Connection, Row};6 use turso::{Connection, Row};
3 7
4-use crate::{database::new_id, error::Error};8+use crate::{database::new_id, error::Error, user};
5 9
6-fn from_row(row: &Row) -> Result<Community, Error> {10+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7- Ok(Community {11+enum Kind {
8- id: row.get(0)?,12+ Group,
9- name: row.get(1)?,13+ Direct,
10- owner_id: row.get(2)?,
11- })
12 }14 }
13 15
14-pub async fn create(name: &str, owner_id: &str, conn: &Connection) -> Result<Community, Error> {16+impl Kind {
15- validate_community_name(name)?;17+ fn as_str(self) -> &'static str {
18+ match self {
19+ Kind::Group => "group",
20+ Kind::Direct => "direct",
21+ }
22+ }
16 23
17- let mut rows = conn24+ fn parse(text: &str) -> Option<Self> {
18- .query(25+ match text {
19- "INSERT INTO community (id, name, owner_id) VALUES (?1, ?2, ?3) RETURNING id, name, owner_id",26+ "group" => Some(Kind::Group),
20- (new_id(), name, owner_id),27+ "direct" => Some(Kind::Direct),
21- )28+ _ => None,
22- .await?;29+ }
23- let row = rows.next().await?.ok_or(CommonError::NotFound)?;30+ }
31+}
32+
33+type Raw = (String, String, Kind, Option<String>);
34+
35+fn raw_of(row: &Row) -> Result<Raw, Error> {
36+ let text: String = row.get(2)?;
37+ let kind = Kind::parse(&text).ok_or(CommonError::Server)?;
24 38
25- from_row(&row)39+ Ok((row.get(0)?, row.get(1)?, kind, row.get(3)?))
26 }40 }
27 41
28-pub async fn read(community_id: &str, conn: &Connection) -> Result<Community, Error> {42+async fn peer(community_id: &str, viewer_id: &str, conn: &Connection) -> Result<User, Error> {
29 let mut rows = conn43 let mut rows = conn
30 .query(44 .query(
31- "SELECT id, name, owner_id FROM community WHERE id = ?1",45+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM direct JOIN user ON user.id = CASE WHEN direct.user_a = ?2 THEN direct.user_b ELSE direct.user_a END WHERE direct.community_id = ?1",
32- (community_id,),46+ (community_id, viewer_id),
33 )47 )
34 .await?;48 .await?;
35 let row = rows.next().await?.ok_or(CommonError::NotFound)?;49 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
36 50
37- from_row(&row)51+ user::from_row(&row)
38 }52 }
39 53
40-pub async fn read_by_name(name: &str, conn: &Connection) -> Result<Vec<Community>, Error> {54+async fn build(raw: Raw, viewer_id: &str, conn: &Connection) -> Result<Community, Error> {
41- let mut rows = conn55+ let (id, name, kind, avatar_id) = raw;
42- .query(56+ let kind = match kind {
43- "SELECT id, name, owner_id FROM community WHERE name = ?1 ORDER BY id",57+ Kind::Group => CommunityKind::Group,
44- (name,),58+ Kind::Direct => CommunityKind::Direct {
45- )59+ peer: peer(&id, viewer_id, conn).await?,
46- .await?;60+ },
61+ };
47 62
48- let mut communities = Vec::new();63+ Ok(Community {
49- while let Some(row) = rows.next().await? {64+ id,
50- communities.push(from_row(&row)?);65+ name,
51- }66+ kind,
67+ avatar_id,
68+ })
69+}
52 70
53- Ok(communities)71+pub async fn create(name: &str, conn: &Connection) -> Result<Community, Error> {
72+ validate_community_name(name)?;
73+
74+ let id = new_id();
75+ conn.execute(
76+ "INSERT INTO community (id, name, kind) VALUES (?1, ?2, ?3)",
77+ (id.as_str(), name, Kind::Group.as_str()),
78+ )
79+ .await?;
80+
81+ Ok(Community {
82+ id,
83+ name: name.to_string(),
84+ kind: CommunityKind::Group,
85+ avatar_id: None,
86+ })
87+}
88+
89+pub async fn create_direct(conn: &Connection) -> Result<String, Error> {
90+ let id = new_id();
91+ conn.execute(
92+ "INSERT INTO community (id, name, kind) VALUES (?1, '', ?2)",
93+ (id.as_str(), Kind::Direct.as_str()),
94+ )
95+ .await?;
96+
97+ Ok(id)
98+}
99+
100+pub async fn read(
101+ community_id: &str,
102+ viewer_id: &str,
103+ conn: &Connection,
104+) -> Result<Community, Error> {
105+ let raw = {
106+ let mut rows = conn
107+ .query(
108+ "SELECT id, name, kind, avatar_id FROM community WHERE id = ?1",
109+ (community_id,),
110+ )
111+ .await?;
112+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
113+
114+ raw_of(&row)?
115+ };
116+
117+ build(raw, viewer_id, conn).await
54 }118 }
55 119
56 pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Community>, Error> {120 pub async fn communities_of(user_id: &str, conn: &Connection) -> Result<Vec<Community>, Error> {
57- let mut rows = conn121+ let raws = {
58- .query(122+ let mut rows = conn
59- "SELECT community.id, community.name, community.owner_id FROM community JOIN user_community ON user_community.community_id = community.id WHERE user_community.user_id = ?1 ORDER BY community.id",123+ .query(
60- (user_id,),124+ "SELECT community.id, community.name, community.kind, community.avatar_id FROM community JOIN user_community ON user_community.community_id = community.id WHERE user_community.user_id = ?1 ORDER BY community.id",
61- )125+ (user_id,),
62- .await?;126+ )
127+ .await?;
128+
129+ let mut raws = Vec::new();
130+ while let Some(row) = rows.next().await? {
131+ raws.push(raw_of(&row)?);
132+ }
133+
134+ raws
135+ };
63 136
64 let mut communities = Vec::new();137 let mut communities = Vec::new();
65- while let Some(row) = rows.next().await? {138+ for raw in raws {
66- communities.push(from_row(&row)?);139+ communities.push(build(raw, user_id, conn).await?);
67 }140 }
68 141
69 Ok(communities)142 Ok(communities)
70 }143 }
71 144
72-pub async fn update(community_id: &str, name: &str, conn: &Connection) -> Result<Community, Error> {145+pub async fn update(
146+ community_id: &str,
147+ name: &str,
148+ viewer_id: &str,
149+ conn: &Connection,
150+) -> Result<Community, Error> {
73 validate_community_name(name)?;151 validate_community_name(name)?;
74 152
75- let mut rows = conn153+ conn.execute(
76- .query(154+ "UPDATE community SET name = ?2 WHERE id = ?1",
77- "UPDATE community SET name = ?2 WHERE id = ?1 RETURNING id, name, owner_id",155+ (community_id, name),
78- (community_id, name),156+ )
157+ .await?;
158+
159+ read(community_id, viewer_id, conn).await
160+}
161+
162+pub async fn set_avatar(
163+ community_id: &str,
164+ image: Option<&[u8]>,
165+ viewer_id: &str,
166+ conn: &mut Connection,
167+) -> Result<Community, Error> {
168+ if let Some(bytes) = image {
169+ user::check_avatar(bytes)?;
170+ }
171+ let avatar_id = image.map(|_| new_id());
172+
173+ let tx = conn.transaction().await?;
174+ tx.execute(
175+ "DELETE FROM community_avatar WHERE community_id = ?1",
176+ (community_id,),
177+ )
178+ .await?;
179+ if let (Some(avatar_id), Some(bytes)) = (&avatar_id, image) {
180+ tx.execute(
181+ "INSERT INTO community_avatar (id, community_id, data) VALUES (?1, ?2, ?3)",
182+ (avatar_id.as_str(), community_id, bytes),
79 )183 )
80 .await?;184 .await?;
81- let row = rows.next().await?.ok_or(CommonError::NotFound)?;185+ }
186+ tx.execute(
187+ "UPDATE community SET avatar_id = ?2 WHERE id = ?1",
188+ (community_id, avatar_id.as_deref()),
189+ )
190+ .await?;
191+ let community = read(community_id, viewer_id, &tx).await?;
192+ tx.commit().await?;
193+
194+ Ok(community)
195+}
82 196
83- from_row(&row)197+pub async fn delete(
198+ community_id: &str,
199+ viewer_id: &str,
200+ conn: &Connection,
201+) -> Result<Community, Error> {
202+ let deleted = read(community_id, viewer_id, conn).await?;
203+ conn.execute("DELETE FROM community WHERE id = ?1", (community_id,))
204+ .await?;
205+
206+ Ok(deleted)
84 }207 }
85 208
86-pub async fn delete(community_id: &str, conn: &Connection) -> Result<Community, Error> {209+async fn kind(community_id: &str, conn: &Connection) -> Result<Kind, Error> {
87 let mut rows = conn210 let mut rows = conn
88- .query(211+ .query("SELECT kind FROM community WHERE id = ?1", (community_id,))
89- "DELETE FROM community WHERE id = ?1 RETURNING id, name, owner_id",
90- (community_id,),
91- )
92 .await?;212 .await?;
93 let row = rows.next().await?.ok_or(CommonError::NotFound)?;213 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
214+ let text: String = row.get(0)?;
94 215
95- from_row(&row)216+ Ok(Kind::parse(&text).ok_or(CommonError::Server)?)
217+}
218+
219+pub async fn is_direct(community_id: &str, conn: &Connection) -> Result<bool, Error> {
220+ Ok(kind(community_id, conn).await? == Kind::Direct)
96 }221 }
97 222
98 #[cfg(test)]223 #[cfg(test)]
@@ -105,64 +230,40 @@ mod tests {
105 async fn create() {230 async fn create() {
106 let db = test::get_database().await;231 let db = test::get_database().await;
107 let conn = database::connect(&db).await.unwrap();232 let conn = database::connect(&db).await.unwrap();
108- let owner = user::create("Tahinli", "hash", &conn).await.unwrap();
109 233
110- let community = community::create("Tahinli", &owner.id, &conn)234+ let community = community::create("Tahinli", &conn).await.unwrap();
111- .await
112- .unwrap();
113 235
114 assert_eq!("Tahinli", community.name);236 assert_eq!("Tahinli", community.name);
115- assert_eq!(owner.id, community.owner_id);
116 }237 }
117 238
118 #[tokio::test]239 #[tokio::test]
119 async fn read() {240 async fn read() {
120 let db = test::get_database().await;241 let db = test::get_database().await;
121 let conn = database::connect(&db).await.unwrap();242 let conn = database::connect(&db).await.unwrap();
122- let owner = user::create("Tahinli", "hash", &conn).await.unwrap();243+ let viewer = user::create("Tahinli", "hash", &conn).await.unwrap();
123 244
124- let created_community = community::create("Tahinli", &owner.id, &conn)245+ let created_community = community::create("Tahinli", &conn).await.unwrap();
246+ let searched_community = community::read(&created_community.id, &viewer.id, &conn)
125 .await247 .await
126 .unwrap();248 .unwrap();
127- let searched_community = community::read(&created_community.id, &conn).await.unwrap();
128 249
129 assert_eq!(created_community, searched_community);250 assert_eq!(created_community, searched_community);
130 }251 }
131 252
132- #[tokio::test]
133- async fn read_by_name() {
134- let db = test::get_database().await;
135- let conn = database::connect(&db).await.unwrap();
136- let owner = user::create("Tahinli", "hash", &conn).await.unwrap();
137-
138- let community_1 = community::create("Tahinli", &owner.id, &conn)
139- .await
140- .unwrap();
141- let community_2 = community::create("Tahinli", &owner.id, &conn)
142- .await
143- .unwrap();
144- let _community_3 = community::create("Not Tahinli", &owner.id, &conn)
145- .await
146- .unwrap();
147-
148- let searched_communities = community::read_by_name("Tahinli", &conn).await.unwrap();
149-
150- assert_eq!(vec![community_1, community_2], searched_communities);
151- }
152-
153 #[tokio::test]253 #[tokio::test]
154 async fn update() {254 async fn update() {
155 let db = test::get_database().await;255 let db = test::get_database().await;
156 let conn = database::connect(&db).await.unwrap();256 let conn = database::connect(&db).await.unwrap();
157- let owner = user::create("Tahinli", "hash", &conn).await.unwrap();257+ let viewer = user::create("Tahinli", "hash", &conn).await.unwrap();
158-258+
159- let created_community = community::create("Tahinli", &owner.id, &conn)259+ let created_community = community::create("Tahinli", &conn).await.unwrap();
260+ let updated_community =
261+ community::update(&created_community.id, "Not Tahinli", &viewer.id, &conn)
262+ .await
263+ .unwrap();
264+ let searched_community = community::read(&created_community.id, &viewer.id, &conn)
160 .await265 .await
161 .unwrap();266 .unwrap();
162- let updated_community = community::update(&created_community.id, "Not Tahinli", &conn)
163- .await
164- .unwrap();
165- let searched_community = community::read(&created_community.id, &conn).await.unwrap();
166 267
167 assert_eq!(created_community.id, searched_community.id);268 assert_eq!(created_community.id, searched_community.id);
168 assert_eq!(updated_community, searched_community);269 assert_eq!(updated_community, searched_community);
@@ -173,8 +274,10 @@ mod tests {
173 async fn update_on_missing_community() {274 async fn update_on_missing_community() {
174 let db = test::get_database().await;275 let db = test::get_database().await;
175 let conn = database::connect(&db).await.unwrap();276 let conn = database::connect(&db).await.unwrap();
277+ let viewer = user::create("Tahinli", "hash", &conn).await.unwrap();
176 278
177- let updated_community = community::update("missing", "Not Tahinli", &conn).await;279+ let updated_community =
280+ community::update("missing", "Not Tahinli", &viewer.id, &conn).await;
178 281
179 assert!(matches!(282 assert!(matches!(
180 updated_community,283 updated_community,
@@ -186,12 +289,10 @@ mod tests {
186 async fn delete() {289 async fn delete() {
187 let db = test::get_database().await;290 let db = test::get_database().await;
188 let conn = database::connect(&db).await.unwrap();291 let conn = database::connect(&db).await.unwrap();
189- let owner = user::create("Tahinli", "hash", &conn).await.unwrap();292+ let viewer = user::create("Tahinli", "hash", &conn).await.unwrap();
190 293
191- let created_community = community::create("Tahinli", &owner.id, &conn)294+ let created_community = community::create("Tahinli", &conn).await.unwrap();
192- .await295+ let deleted_community = community::delete(&created_community.id, &viewer.id, &conn)
193- .unwrap();
194- let deleted_community = community::delete(&created_community.id, &conn)
195 .await296 .await
196 .unwrap();297 .unwrap();
197 298
crates/server/src/database.rsmodified+106 -18
@@ -1,24 +1,28 @@
1-use std::{1+use std::time::Duration;
2- sync::{LazyLock, Mutex},
3- time::Duration,
4-};
5 2
6 use turso::Connection;3 use turso::Connection;
7-use ulid::Generator;
8 4
9 use crate::error::Error;5 use crate::error::Error;
10 6
11 pub type DB = turso::Database;7 pub type DB = turso::Database;
12 8
13-static ULID: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
14-
15 const BUSY_TIMEOUT: Duration = Duration::from_secs(5);9 const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
16 10
17-const MIGRATIONS: &[&str] = &["11+const MIGRATIONS: &[&str] = &[
12+ "
18 CREATE TABLE user (13 CREATE TABLE user (
19 id TEXT PRIMARY KEY,14 id TEXT PRIMARY KEY,
20 username TEXT NOT NULL UNIQUE,15 username TEXT NOT NULL UNIQUE,
21- password_hash TEXT NOT NULL16+ password_hash TEXT NOT NULL,
17+ role TEXT NOT NULL DEFAULT 'user',
18+ status TEXT NOT NULL DEFAULT '',
19+ avatar_id TEXT
20+ );
21+
22+ CREATE TABLE avatar (
23+ id TEXT PRIMARY KEY,
24+ user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
25+ data BLOB NOT NULL
22 );26 );
23 27
24 CREATE TABLE session (28 CREATE TABLE session (
@@ -28,8 +32,7 @@ const MIGRATIONS: &[&str] = &["
28 32
29 CREATE TABLE community (33 CREATE TABLE community (
30 id TEXT PRIMARY KEY,34 id TEXT PRIMARY KEY,
31- name TEXT NOT NULL,35+ name TEXT NOT NULL
32- owner_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE
33 );36 );
34 37
35 CREATE TABLE message (38 CREATE TABLE message (
@@ -42,11 +45,101 @@ const MIGRATIONS: &[&str] = &["
42 CREATE INDEX message_community_id_id ON message (community_id, id);45 CREATE INDEX message_community_id_id ON message (community_id, id);
43 46
44 CREATE TABLE user_community (47 CREATE TABLE user_community (
48+ user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
49+ community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,
50+ rank TEXT NOT NULL DEFAULT 'member',
51+ PRIMARY KEY (user_id, community_id)
52+ );
53+
54+ CREATE TABLE ban (
45 user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,55 user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
46 community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,56 community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,
47 PRIMARY KEY (user_id, community_id)57 PRIMARY KEY (user_id, community_id)
48 );58 );
49-"];59+
60+ CREATE TABLE attachment (
61+ id TEXT PRIMARY KEY,
62+ uploader_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
63+ community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,
64+ message_id TEXT REFERENCES message (id) ON DELETE CASCADE,
65+ name TEXT NOT NULL,
66+ size INTEGER NOT NULL,
67+ kind TEXT NOT NULL,
68+ width INTEGER,
69+ height INTEGER
70+ );
71+
72+ CREATE INDEX attachment_message_id ON attachment (message_id);
73+",
74+ "
75+ ALTER TABLE community ADD COLUMN kind TEXT NOT NULL DEFAULT 'group';
76+ ALTER TABLE message ADD COLUMN reply_to TEXT;
77+ ALTER TABLE message ADD COLUMN edited INTEGER NOT NULL DEFAULT 0;
78+ ALTER TABLE attachment ADD COLUMN snippet_position INTEGER;
79+ ALTER TABLE ban ADD COLUMN reason TEXT;
80+ ALTER TABLE community ADD COLUMN avatar_id TEXT;
81+
82+ CREATE TABLE community_avatar (
83+ id TEXT PRIMARY KEY,
84+ community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,
85+ data BLOB NOT NULL
86+ );
87+
88+ CREATE TABLE direct (
89+ user_a TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
90+ user_b TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
91+ community_id TEXT NOT NULL UNIQUE REFERENCES community (id) ON DELETE CASCADE,
92+ PRIMARY KEY (user_a, user_b)
93+ );
94+
95+ CREATE TABLE snippet (
96+ message_id TEXT PRIMARY KEY REFERENCES message (id) ON DELETE CASCADE,
97+ origin TEXT
98+ );
99+
100+ CREATE TABLE snippet_message (
101+ message_id TEXT NOT NULL REFERENCES message (id) ON DELETE CASCADE,
102+ position INTEGER NOT NULL,
103+ original_id TEXT NOT NULL,
104+ user_id TEXT NOT NULL,
105+ username TEXT NOT NULL,
106+ avatar_id TEXT,
107+ body TEXT NOT NULL,
108+ PRIMARY KEY (message_id, position)
109+ );
110+
111+ CREATE TABLE friend_request (
112+ from_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
113+ to_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
114+ PRIMARY KEY (from_id, to_id)
115+ );
116+
117+ CREATE TABLE friend (
118+ user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
119+ friend_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
120+ PRIMARY KEY (user_id, friend_id)
121+ );
122+
123+ CREATE TABLE invitation (
124+ community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,
125+ user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
126+ inviter_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE,
127+ PRIMARY KEY (community_id, user_id)
128+ );
129+",
130+ "
131+ CREATE TABLE community_log (
132+ id TEXT PRIMARY KEY,
133+ community_id TEXT NOT NULL REFERENCES community (id) ON DELETE CASCADE,
134+ actor_id TEXT REFERENCES user (id) ON DELETE SET NULL,
135+ target_id TEXT REFERENCES user (id) ON DELETE SET NULL,
136+ action TEXT NOT NULL,
137+ detail TEXT
138+ );
139+
140+ CREATE INDEX community_log_community_id_id ON community_log (community_id, id);
141+",
142+];
50 143
51 pub async fn open(path: &str) -> Result<DB, Error> {144 pub async fn open(path: &str) -> Result<DB, Error> {
52 let db = turso::Builder::new_local(path).build().await?;145 let db = turso::Builder::new_local(path).build().await?;
@@ -89,10 +182,5 @@ async fn user_version(conn: &Connection) -> Result<usize, Error> {
89 }182 }
90 183
91 pub fn new_id() -> String {184 pub fn new_id() -> String {
92- loop {185+ uuid::Uuid::now_v7().to_string()
93- match ULID.lock().unwrap().generate() {
94- Ok(ulid) => return ulid.to_string(),
95- Err(_) => continue,
96- }
97- }
98 }186 }
crates/server/src/direct.rsadded+51 -0
@@ -0,0 +1,51 @@
1+use common::{
2+ error::Error as CommonError,
3+ model::{Community, Rank},
4+};
5+use turso::Connection;
6+
7+use crate::{community, error::Error, user, user_community};
8+
9+async fn find(user_a: &str, user_b: &str, conn: &Connection) -> Result<Option<String>, Error> {
10+ let mut rows = conn
11+ .query(
12+ "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2",
13+ (user_a, user_b),
14+ )
15+ .await?;
16+
17+ Ok(rows.next().await?.map(|row| row.get(0)).transpose()?)
18+}
19+
20+pub async fn open(
21+ me: &str,
22+ other: &str,
23+ conn: &mut Connection,
24+) -> Result<(Community, bool), Error> {
25+ if me == other {
26+ return Err(CommonError::Forbidden.into());
27+ }
28+ user::read(other, conn).await?;
29+
30+ let (user_a, user_b) = if me < other { (me, other) } else { (other, me) };
31+ let tx = conn.transaction().await?;
32+ if let Some(community_id) = find(user_a, user_b, &tx).await? {
33+ let community = community::read(&community_id, me, &tx).await?;
34+ tx.commit().await?;
35+
36+ return Ok((community, false));
37+ }
38+
39+ let community_id = community::create_direct(&tx).await?;
40+ user_community::join(me, &community_id, Rank::Member, &tx).await?;
41+ user_community::join(other, &community_id, Rank::Member, &tx).await?;
42+ tx.execute(
43+ "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)",
44+ (user_a, user_b, community_id.as_str()),
45+ )
46+ .await?;
47+ let community = community::read(&community_id, me, &tx).await?;
48+ tx.commit().await?;
49+
50+ Ok((community, true))
51+}
crates/server/src/friend.rsadded+146 -0
@@ -0,0 +1,146 @@
1+use common::{
2+ error::Error as CommonError,
3+ model::{Friends, User},
4+};
5+use turso::Connection;
6+
7+use crate::{error::Error, user};
8+
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?;
11+
12+ let mut users = Vec::new();
13+ while let Some(row) = rows.next().await? {
14+ users.push(user::from_row(&row)?);
15+ }
16+
17+ Ok(users)
18+}
19+
20+async fn pair_exists(
21+ sql: &str,
22+ first: &str,
23+ second: &str,
24+ conn: &Connection,
25+) -> Result<bool, Error> {
26+ let mut rows = conn.query(sql, (first, second)).await?;
27+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
28+ let count: i64 = row.get(0)?;
29+
30+ Ok(count > 0)
31+}
32+
33+async fn is_friend(me: &str, other: &str, conn: &Connection) -> Result<bool, Error> {
34+ pair_exists(
35+ "SELECT COUNT(*) FROM friend WHERE user_id = ?1 AND friend_id = ?2",
36+ me,
37+ other,
38+ conn,
39+ )
40+ .await
41+}
42+
43+async fn is_requested(from: &str, to: &str, conn: &Connection) -> Result<bool, Error> {
44+ pair_exists(
45+ "SELECT COUNT(*) FROM friend_request WHERE from_id = ?1 AND to_id = ?2",
46+ from,
47+ to,
48+ conn,
49+ )
50+ .await
51+}
52+
53+async fn befriend(me: &str, other: &str, conn: &Connection) -> Result<(), Error> {
54+ conn.execute(
55+ "DELETE FROM friend_request WHERE from_id = ?1 AND to_id = ?2",
56+ (other, me),
57+ )
58+ .await?;
59+ conn.execute(
60+ "INSERT INTO friend (user_id, friend_id) VALUES (?1, ?2)",
61+ (me, other),
62+ )
63+ .await?;
64+ conn.execute(
65+ "INSERT INTO friend (user_id, friend_id) VALUES (?1, ?2)",
66+ (other, me),
67+ )
68+ .await?;
69+
70+ Ok(())
71+}
72+
73+pub async fn state(user_id: &str, conn: &Connection) -> Result<Friends, Error> {
74+ Ok(Friends {
75+ friends: users(
76+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM user JOIN friend ON friend.friend_id = user.id WHERE friend.user_id = ?1 ORDER BY user.id",
77+ user_id,
78+ conn,
79+ )
80+ .await?,
81+ incoming: users(
82+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM user JOIN friend_request ON friend_request.from_id = user.id WHERE friend_request.to_id = ?1 ORDER BY user.id",
83+ user_id,
84+ conn,
85+ )
86+ .await?,
87+ outgoing: users(
88+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id FROM user JOIN friend_request ON friend_request.to_id = user.id WHERE friend_request.from_id = ?1 ORDER BY user.id",
89+ user_id,
90+ conn,
91+ )
92+ .await?,
93+ })
94+}
95+
96+pub async fn add(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
97+ if me == other {
98+ return Err(CommonError::Forbidden.into());
99+ }
100+ user::read(other, conn).await?;
101+
102+ let tx = conn.transaction().await?;
103+ if is_friend(me, other, &tx).await? || is_requested(me, other, &tx).await? {
104+ return Err(CommonError::Taken.into());
105+ }
106+ if is_requested(other, me, &tx).await? {
107+ befriend(me, other, &tx).await?;
108+ } else {
109+ tx.execute(
110+ "INSERT INTO friend_request (from_id, to_id) VALUES (?1, ?2)",
111+ (me, other),
112+ )
113+ .await?;
114+ }
115+ tx.commit().await?;
116+
117+ Ok(())
118+}
119+
120+pub async fn accept(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
121+ let tx = conn.transaction().await?;
122+ if !is_requested(other, me, &tx).await? {
123+ return Err(CommonError::NotFound.into());
124+ }
125+ befriend(me, other, &tx).await?;
126+ tx.commit().await?;
127+
128+ Ok(())
129+}
130+
131+pub async fn remove(me: &str, other: &str, conn: &mut Connection) -> Result<(), Error> {
132+ let tx = conn.transaction().await?;
133+ tx.execute(
134+ "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)",
135+ (me, other),
136+ )
137+ .await?;
138+ tx.execute(
139+ "DELETE FROM friend_request WHERE (from_id = ?1 AND to_id = ?2) OR (from_id = ?2 AND to_id = ?1)",
140+ (me, other),
141+ )
142+ .await?;
143+ tx.commit().await?;
144+
145+ Ok(())
146+}
crates/server/src/invitation.rsadded+73 -0
@@ -0,0 +1,73 @@
1+use common::{error::Error as CommonError, model::Invitation};
2+use turso::Connection;
3+
4+use crate::{community, error::Error, user};
5+
6+pub async fn of(user_id: &str, conn: &Connection) -> Result<Vec<Invitation>, Error> {
7+ let pairs = {
8+ let mut rows = conn
9+ .query(
10+ "SELECT community_id, inviter_id FROM invitation WHERE user_id = ?1 ORDER BY community_id",
11+ (user_id,),
12+ )
13+ .await?;
14+
15+ let mut pairs: Vec<(String, String)> = Vec::new();
16+ while let Some(row) = rows.next().await? {
17+ pairs.push((row.get(0)?, row.get(1)?));
18+ }
19+
20+ pairs
21+ };
22+
23+ let mut invitations = Vec::new();
24+ for (community_id, inviter_id) in pairs {
25+ invitations.push(Invitation {
26+ community: community::read(&community_id, user_id, conn).await?,
27+ inviter: user::read(&inviter_id, conn).await?,
28+ });
29+ }
30+
31+ Ok(invitations)
32+}
33+
34+pub async fn exists(community_id: &str, user_id: &str, conn: &Connection) -> Result<bool, Error> {
35+ let mut rows = conn
36+ .query(
37+ "SELECT COUNT(*) FROM invitation WHERE community_id = ?1 AND user_id = ?2",
38+ (community_id, user_id),
39+ )
40+ .await?;
41+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
42+ let count: i64 = row.get(0)?;
43+
44+ Ok(count > 0)
45+}
46+
47+pub async fn insert(
48+ community_id: &str,
49+ user_id: &str,
50+ inviter_id: &str,
51+ conn: &Connection,
52+) -> Result<(), Error> {
53+ conn.execute(
54+ "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)",
55+ (community_id, user_id, inviter_id),
56+ )
57+ .await?;
58+
59+ Ok(())
60+}
61+
62+pub async fn take(community_id: &str, user_id: &str, conn: &Connection) -> Result<(), Error> {
63+ if !exists(community_id, user_id, conn).await? {
64+ return Err(CommonError::NotFound.into());
65+ }
66+ conn.execute(
67+ "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2",
68+ (community_id, user_id),
69+ )
70+ .await?;
71+
72+ Ok(())
73+}
crates/server/src/lib.rsmodified+26 -4
@@ -1,18 +1,24 @@
1+pub mod attachment;
1 pub mod authentication;2 pub mod authentication;
2 pub mod certificate;3 pub mod certificate;
3 pub mod community;4 pub mod community;
4 pub mod database;5 pub mod database;
6+pub mod direct;
5 pub mod error;7 pub mod error;
8+pub mod friend;
9+pub mod invitation;
10+pub mod log;
6 pub mod message;11 pub mod message;
7 pub mod network;12 pub mod network;
8 pub mod request;13 pub mod request;
9 pub mod user;14 pub mod user;
10 pub mod user_community;15 pub mod user_community;
16+pub mod voice;
11 17
12 #[cfg(test)]18 #[cfg(test)]
13 mod test;19 mod test;
14 20
15-use common::config::Config;21+use common::{config::Config, model::Role};
16 22
17 use crate::error::Error;23 use crate::error::Error;
18 24
@@ -41,14 +47,30 @@ impl ServerConfig {
41 }47 }
42 }48 }
43 49
50+fn load_config() -> Result<ServerConfig, Error> {
51+ let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?;
52+
53+ ServerConfig::parse(&content)
54+}
55+
44 pub async fn showtime() -> Result<(), Error> {56 pub async fn showtime() -> Result<(), Error> {
45 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();57 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
46 58
47- let content = std::fs::read_to_string(SERVER_CONFIG_FILE_PATH)?;59+ let config = load_config()?;
48- let config = ServerConfig::parse(&content)?;
49 60
50 let database = database::open(&config.database_path).await?;61 let database = database::open(&config.database_path).await?;
51 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;62 let certificate = certificate::load(&config.certificate_path, &config.key_path)?;
63+ let attachments = attachment::directory(&config.database_path)?;
64+ tokio::spawn(attachment::collect(database.clone(), attachments.clone()));
65+
66+ network::serve(&config.server_address, certificate, database, attachments).await
67+}
68+
69+pub async fn set_role(username: &str, role: Role) -> Result<(), Error> {
70+ let config = load_config()?;
71+ let database = database::open(&config.database_path).await?;
72+ let conn = database::connect(&database).await?;
73+ user::set_role(username, role, &conn).await?;
52 74
53- network::serve(&config.server_address, certificate, database).await75+ Ok(())
54 }76 }
crates/server/src/log.rsadded+102 -0
@@ -0,0 +1,102 @@
1+use common::{
2+ error::Error as CommonError,
3+ model::{LogAction, LogEntry, Rank, Role, User},
4+};
5+use turso::{Connection, Row};
6+
7+use crate::{database::new_id, error::Error};
8+
9+fn parts(action: &LogAction) -> (&'static str, Option<String>) {
10+ match action {
11+ LogAction::Created => ("created", None),
12+ LogAction::Renamed { name } => ("renamed", Some(name.clone())),
13+ LogAction::AvatarChanged => ("avatar_changed", None),
14+ LogAction::AvatarRemoved => ("avatar_removed", None),
15+ LogAction::Invited => ("invited", None),
16+ LogAction::Joined => ("joined", None),
17+ LogAction::Left => ("left", None),
18+ LogAction::Kicked { reason } => ("kicked", reason.clone()),
19+ LogAction::Banned { reason } => ("banned", reason.clone()),
20+ LogAction::Unbanned => ("unbanned", None),
21+ LogAction::RankChanged { rank } => ("rank_changed", Some(rank.as_str().to_string())),
22+ LogAction::MessageDeleted => ("message_deleted", None),
23+ }
24+}
25+
26+fn action_of(text: &str, detail: Option<String>) -> Option<LogAction> {
27+ match text {
28+ "created" => Some(LogAction::Created),
29+ "renamed" => Some(LogAction::Renamed { name: detail? }),
30+ "avatar_changed" => Some(LogAction::AvatarChanged),
31+ "avatar_removed" => Some(LogAction::AvatarRemoved),
32+ "invited" => Some(LogAction::Invited),
33+ "joined" => Some(LogAction::Joined),
34+ "left" => Some(LogAction::Left),
35+ "kicked" => Some(LogAction::Kicked { reason: detail }),
36+ "banned" => Some(LogAction::Banned { reason: detail }),
37+ "unbanned" => Some(LogAction::Unbanned),
38+ "rank_changed" => Some(LogAction::RankChanged {
39+ rank: Rank::parse(&detail?)?,
40+ }),
41+ "message_deleted" => Some(LogAction::MessageDeleted),
42+ _ => None,
43+ }
44+}
45+
46+fn user_at(row: &Row, start: usize) -> Result<Option<User>, Error> {
47+ let Some(id) = row.get::<Option<String>>(start)? else {
48+ return Ok(None);
49+ };
50+ let role: String = row.get(start + 2)?;
51+
52+ Ok(Some(User {
53+ id,
54+ username: row.get(start + 1)?,
55+ role: Role::parse(&role).ok_or(CommonError::Server)?,
56+ status: row.get(start + 3)?,
57+ avatar_id: row.get(start + 4)?,
58+ }))
59+}
60+
61+pub async fn record(
62+ community_id: &str,
63+ actor_id: Option<&str>,
64+ target_id: Option<&str>,
65+ action: &LogAction,
66+ conn: &Connection,
67+) -> Result<(), Error> {
68+ let id = new_id();
69+ let (action, detail) = parts(action);
70+ conn.execute(
71+ "INSERT INTO community_log (id, community_id, actor_id, target_id, action, detail) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
72+ (id.as_str(), community_id, actor_id, target_id, action, detail.as_deref()),
73+ )
74+ .await?;
75+
76+ Ok(())
77+}
78+
79+pub async fn list(community_id: &str, conn: &Connection) -> Result<Vec<LogEntry>, Error> {
80+ let mut rows = conn
81+ .query(
82+ "SELECT l.id, l.action, l.detail, a.id, a.username, a.role, a.status, a.avatar_id, t.id, t.username, t.role, t.status, t.avatar_id FROM community_log l LEFT JOIN user a ON a.id = l.actor_id LEFT JOIN user t ON t.id = l.target_id WHERE l.community_id = ?1 ORDER BY l.id DESC LIMIT 500",
83+ (community_id,),
84+ )
85+ .await?;
86+
87+ let mut entries = Vec::new();
88+ while let Some(row) = rows.next().await? {
89+ let text: String = row.get(1)?;
90+ let Some(action) = action_of(&text, row.get(2)?) else {
91+ continue;
92+ };
93+ entries.push(LogEntry {
94+ id: row.get(0)?,
95+ actor: user_at(&row, 3)?,
96+ target: user_at(&row, 8)?,
97+ action,
98+ });
99+ }
100+
101+ Ok(entries)
102+}
crates/server/src/main.rsmodified+19 -3
@@ -1,8 +1,24 @@
1-use server::showtime;1+use common::model::Role;
2+use server::{set_role, showtime};
2 3
3 #[tokio::main]4 #[tokio::main]
4 async fn main() -> Result<(), server::error::Error> {5 async fn main() -> Result<(), server::error::Error> {
5- tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();6+ tracing_subscriber::fmt()
7+ .with_max_level(tracing::Level::INFO)
8+ .init();
6 9
7- showtime().await10+ let args: Vec<String> = std::env::args().skip(1).collect();
11+ match args
12+ .iter()
13+ .map(String::as_str)
14+ .collect::<Vec<_>>()
15+ .as_slice()
16+ {
17+ ["staff", username] => set_role(username, Role::Staff).await?,
18+ ["unstaff", username] => set_role(username, Role::User).await?,
19+ _ => return showtime().await,
20+ }
21+
22+ println!("ok");
23+ Ok(())
8 }24 }
crates/server/src/message.rsmodified+337 -39
@@ -1,49 +1,160 @@
1+use std::path::Path;
2+
1 use common::{3 use common::{
2- constant::MESSAGE_PAGE_LIMIT, error::Error as CommonError, model::Message,4+ constant::{MAXIMUM_FORWARD_MESSAGES, MAXIMUM_QUOTE_LENGTH, MESSAGE_PAGE_LIMIT},
3- validate::validate_message_body,5+ error::{Error as CommonError, InvalidInput},
6+ model::{Message, Quote, Snippet, SnippetMessage, User},
7+ validate::{validate_message_body, validate_new_message},
4 };8 };
5 use turso::{Connection, Row};9 use turso::{Connection, Row};
6 10
7-use crate::{database::new_id, error::Error};11+use crate::{attachment, database::new_id, error::Error, user};
12+
13+const SELECT: &str = "SELECT m.id, m.user_id, m.community_id, m.body, m.edited, r.id, r.user_id, r.body, (SELECT COUNT(*) FROM attachment a WHERE a.message_id = r.id AND a.snippet_position IS NULL) FROM message m LEFT JOIN message r ON r.id = m.reply_to";
8 14
9 fn from_row(row: &Row) -> Result<Message, Error> {15 fn from_row(row: &Row) -> Result<Message, Error> {
16+ let edited: i64 = row.get(4)?;
17+ let reply = match row.get::<Option<String>>(5)? {
18+ Some(message_id) => {
19+ let body: String = row.get(7)?;
20+ let attachments: i64 = row.get(8)?;
21+ Some(Quote {
22+ message_id,
23+ user_id: row.get(6)?,
24+ body: body.chars().take(MAXIMUM_QUOTE_LENGTH).collect(),
25+ attachments: attachments as usize,
26+ })
27+ }
28+ None => None,
29+ };
30+
10 Ok(Message {31 Ok(Message {
11 id: row.get(0)?,32 id: row.get(0)?,
12 user_id: row.get(1)?,33 user_id: row.get(1)?,
13 community_id: row.get(2)?,34 community_id: row.get(2)?,
14 body: row.get(3)?,35 body: row.get(3)?,
36+ attachments: Vec::new(),
37+ reply,
38+ snippet: None,
39+ edited: edited != 0,
15 })40 })
16 }41 }
17 42
18-pub async fn create(43+async fn snippet_of(message_id: &str, conn: &Connection) -> Result<Option<Snippet>, Error> {
44+ let mut rows = conn
45+ .query(
46+ "SELECT origin FROM snippet WHERE message_id = ?1",
47+ (message_id,),
48+ )
49+ .await?;
50+ let Some(row) = rows.next().await? else {
51+ return Ok(None);
52+ };
53+ let origin: Option<String> = row.get(0)?;
54+ drop(rows);
55+
56+ let mut rows = conn
57+ .query(
58+ "SELECT position, original_id, user_id, username, avatar_id, body FROM snippet_message WHERE message_id = ?1 ORDER BY position",
59+ (message_id,),
60+ )
61+ .await?;
62+ let mut entries = Vec::new();
63+ while let Some(row) = rows.next().await? {
64+ let position: i64 = row.get(0)?;
65+ entries.push((
66+ position,
67+ SnippetMessage {
68+ id: row.get(1)?,
69+ user_id: row.get(2)?,
70+ username: row.get(3)?,
71+ avatar_id: row.get(4)?,
72+ body: row.get(5)?,
73+ attachments: Vec::new(),
74+ },
75+ ));
76+ }
77+ drop(rows);
78+
79+ let mut messages = Vec::new();
80+ for (position, mut entry) in entries {
81+ entry.attachments = attachment::of_message(message_id, Some(position), conn).await?;
82+ messages.push(entry);
83+ }
84+
85+ Ok(Some(Snippet { origin, messages }))
86+}
87+
88+async fn hydrate(mut message: Message, conn: &Connection) -> Result<Message, Error> {
89+ message.attachments = attachment::of_message(&message.id, None, conn).await?;
90+ message.snippet = snippet_of(&message.id, conn).await?;
91+
92+ Ok(message)
93+}
94+
95+async fn insert(
19 user_id: &str,96 user_id: &str,
20 community_id: &str,97 community_id: &str,
21 body: &str,98 body: &str,
99+ reply_to: Option<&str>,
22 conn: &Connection,100 conn: &Connection,
23-) -> Result<Message, Error> {101+) -> Result<String, Error> {
24- validate_message_body(body)?;102+ let message_id = new_id();
103+ conn.execute(
104+ "INSERT INTO message (id, user_id, community_id, body, reply_to) VALUES (?1, ?2, ?3, ?4, ?5)",
105+ (message_id.as_str(), user_id, community_id, body, reply_to),
106+ )
107+ .await?;
108+
109+ Ok(message_id)
110+}
25 111
112+async fn ensure_in_community(
113+ message_id: &str,
114+ community_id: &str,
115+ conn: &Connection,
116+) -> Result<(), Error> {
26 let mut rows = conn117 let mut rows = conn
27 .query(118 .query(
28- "INSERT INTO message (id, user_id, community_id, body) VALUES (?1, ?2, ?3, ?4) RETURNING id, user_id, community_id, body",119+ "SELECT id FROM message WHERE id = ?1 AND community_id = ?2",
29- (new_id(), user_id, community_id, body),120+ (message_id, community_id),
30 )121 )
31 .await?;122 .await?;
32- let row = rows.next().await?.ok_or(CommonError::NotFound)?;123+ if rows.next().await?.is_none() {
124+ return Err(CommonError::NotFound.into());
125+ }
33 126
34- from_row(&row)127+ Ok(())
128+}
129+
130+pub async fn create(
131+ user_id: &str,
132+ community_id: &str,
133+ body: &str,
134+ attachments: &[String],
135+ reply_to: Option<&str>,
136+ conn: &Connection,
137+) -> Result<Message, Error> {
138+ validate_new_message(body, attachments.len())?;
139+ if let Some(reply_to) = reply_to {
140+ ensure_in_community(reply_to, community_id, conn).await?;
141+ }
142+
143+ let message_id = insert(user_id, community_id, body, reply_to, conn).await?;
144+ attachment::bind(&message_id, user_id, community_id, attachments, conn).await?;
145+
146+ read(&message_id, conn).await
35 }147 }
36 148
37 pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, Error> {149 pub async fn read(message_id: &str, conn: &Connection) -> Result<Message, Error> {
38 let mut rows = conn150 let mut rows = conn
39- .query(151+ .query(&format!("{SELECT} WHERE m.id = ?1"), (message_id,))
40- "SELECT id, user_id, community_id, body FROM message WHERE id = ?1",
41- (message_id,),
42- )
43 .await?;152 .await?;
44 let row = rows.next().await?.ok_or(CommonError::NotFound)?;153 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
154+ let message = from_row(&row)?;
155+ drop(rows);
45 156
46- from_row(&row)157+ hydrate(message, conn).await
47 }158 }
48 159
49 pub async fn read_page(160 pub async fn read_page(
@@ -53,7 +164,9 @@ pub async fn read_page(
53 ) -> Result<Vec<Message>, Error> {164 ) -> Result<Vec<Message>, Error> {
54 let mut rows = conn165 let mut rows = conn
55 .query(166 .query(
56- "SELECT id, user_id, community_id, body FROM message WHERE community_id = ?1 AND (?2 IS NULL OR id < ?2) ORDER BY id DESC LIMIT ?3",167+ &format!(
168+ "{SELECT} WHERE m.community_id = ?1 AND (?2 IS NULL OR m.id < ?2) ORDER BY m.id DESC LIMIT ?3"
169+ ),
57 (community_id, before, MESSAGE_PAGE_LIMIT as i64),170 (community_id, before, MESSAGE_PAGE_LIMIT as i64),
58 )171 )
59 .await?;172 .await?;
@@ -62,35 +175,194 @@ pub async fn read_page(
62 while let Some(row) = rows.next().await? {175 while let Some(row) = rows.next().await? {
63 messages.push(from_row(&row)?);176 messages.push(from_row(&row)?);
64 }177 }
178+ drop(rows);
65 messages.reverse();179 messages.reverse();
66 180
67- Ok(messages)181+ let mut page = Vec::new();
182+ for message in messages {
183+ page.push(hydrate(message, conn).await?);
184+ }
185+
186+ Ok(page)
68 }187 }
69 188
70 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {189 pub async fn update(message_id: &str, body: &str, conn: &Connection) -> Result<Message, Error> {
71 validate_message_body(body)?;190 validate_message_body(body)?;
72 191
73- let mut rows = conn192+ let updated = conn
74- .query(193+ .execute(
75- "UPDATE message SET body = ?2 WHERE id = ?1 RETURNING id, user_id, community_id, body",194+ "UPDATE message SET body = ?2, edited = 1 WHERE id = ?1",
76 (message_id, body),195 (message_id, body),
77 )196 )
78 .await?;197 .await?;
79- let row = rows.next().await?.ok_or(CommonError::NotFound)?;198+ if updated == 0 {
199+ return Err(CommonError::NotFound.into());
200+ }
80 201
81- from_row(&row)202+ read(message_id, conn).await
82 }203 }
83 204
84 pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Error> {205 pub async fn delete(message_id: &str, conn: &Connection) -> Result<Message, Error> {
206+ let message = read(message_id, conn).await?;
207+ conn.execute("DELETE FROM message WHERE id = ?1", (message_id,))
208+ .await?;
209+
210+ Ok(message)
211+}
212+
213+async fn origin(sources: &[Message], conn: &Connection) -> Result<Option<String>, Error> {
214+ let community_id = &sources[0].community_id;
215+ if sources
216+ .iter()
217+ .any(|source| &source.community_id != community_id)
218+ {
219+ return Ok(None);
220+ }
221+
85 let mut rows = conn222 let mut rows = conn
86 .query(223 .query(
87- "DELETE FROM message WHERE id = ?1 RETURNING id, user_id, community_id, body",224+ "SELECT name, kind FROM community WHERE id = ?1",
88- (message_id,),225+ (community_id.as_str(),),
89 )226 )
90 .await?;227 .await?;
91 let row = rows.next().await?.ok_or(CommonError::NotFound)?;228 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
229+ let name: String = row.get(0)?;
230+ let kind: String = row.get(1)?;
92 231
93- from_row(&row)232+ Ok((kind != "direct").then_some(name))
233+}
234+
235+async fn entry(source: &Message, conn: &Connection) -> Result<SnippetMessage, Error> {
236+ let author: User = user::read(&source.user_id, conn).await?;
237+
238+ Ok(SnippetMessage {
239+ id: source.id.clone(),
240+ user_id: author.id,
241+ username: author.username,
242+ avatar_id: author.avatar_id,
243+ body: source.body.clone(),
244+ attachments: source.attachments.clone(),
245+ })
246+}
247+
248+async fn write_snippet(
249+ message_id: &str,
250+ user_id: &str,
251+ community_id: &str,
252+ origin: Option<&str>,
253+ entries: &[SnippetMessage],
254+ directory: &Path,
255+ conn: &Connection,
256+) -> Result<(), Error> {
257+ conn.execute(
258+ "INSERT INTO snippet (message_id, origin) VALUES (?1, ?2)",
259+ (message_id, origin),
260+ )
261+ .await?;
262+
263+ for (position, entry) in entries.iter().enumerate() {
264+ let position = position as i64;
265+ conn.execute(
266+ "INSERT INTO snippet_message (message_id, position, original_id, user_id, username, avatar_id, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
267+ (
268+ message_id,
269+ position,
270+ entry.id.as_str(),
271+ entry.user_id.as_str(),
272+ entry.username.as_str(),
273+ entry.avatar_id.as_deref(),
274+ entry.body.as_str(),
275+ ),
276+ )
277+ .await?;
278+ for attachment in &entry.attachments {
279+ attachment::copy(
280+ attachment,
281+ message_id,
282+ user_id,
283+ community_id,
284+ Some(position),
285+ directory,
286+ conn,
287+ )
288+ .await?;
289+ }
290+ }
291+
292+ Ok(())
293+}
294+
295+pub async fn forward(
296+ user: &User,
297+ community_id: &str,
298+ sources: &[Message],
299+ snippet: bool,
300+ directory: &Path,
301+ conn: &Connection,
302+) -> Result<Vec<Message>, Error> {
303+ if !snippet {
304+ let mut created = Vec::new();
305+ for source in sources {
306+ let message_id = insert(&user.id, community_id, &source.body, None, conn).await?;
307+ for attachment in &source.attachments {
308+ attachment::copy(
309+ attachment,
310+ &message_id,
311+ &user.id,
312+ community_id,
313+ None,
314+ directory,
315+ conn,
316+ )
317+ .await?;
318+ }
319+ if let Some(inner) = &source.snippet {
320+ write_snippet(
321+ &message_id,
322+ &user.id,
323+ community_id,
324+ inner.origin.as_deref(),
325+ &inner.messages,
326+ directory,
327+ conn,
328+ )
329+ .await?;
330+ }
331+ created.push(read(&message_id, conn).await?);
332+ }
333+
334+ return Ok(created);
335+ }
336+
337+ let mut entries = Vec::new();
338+ for source in sources {
339+ match &source.snippet {
340+ Some(inner) => entries.extend(inner.messages.iter().cloned()),
341+ None => entries.push(entry(source, conn).await?),
342+ }
343+ }
344+ if entries.len() > MAXIMUM_FORWARD_MESSAGES {
345+ return Err(CommonError::Forward(InvalidInput::TooLong {
346+ maximum: MAXIMUM_FORWARD_MESSAGES,
347+ actual: entries.len(),
348+ })
349+ .into());
350+ }
351+
352+ let origin = origin(sources, conn).await?;
353+ let message_id = insert(&user.id, community_id, "", None, conn).await?;
354+ write_snippet(
355+ &message_id,
356+ &user.id,
357+ community_id,
358+ origin.as_deref(),
359+ &entries,
360+ directory,
361+ conn,
362+ )
363+ .await?;
364+
365+ Ok(vec![read(&message_id, conn).await?])
94 }366 }
95 367
96 #[cfg(test)]368 #[cfg(test)]
@@ -104,9 +376,9 @@ mod tests {
104 let db = test::get_database().await;376 let db = test::get_database().await;
105 let conn = database::connect(&db).await.unwrap();377 let conn = database::connect(&db).await.unwrap();
106 let user = user::create("Tahinli", "hash", &conn).await.unwrap();378 let user = user::create("Tahinli", "hash", &conn).await.unwrap();
107- let community = community::create("Tahinli", &user.id, &conn).await.unwrap();379+ let community = community::create("Tahinli", &conn).await.unwrap();
108 380
109- let message = message::create(&user.id, &community.id, "Tahinli", &conn)381+ let message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn)
110 .await382 .await
111 .unwrap();383 .unwrap();
112 384
@@ -120,8 +392,8 @@ mod tests {
120 let db = test::get_database().await;392 let db = test::get_database().await;
121 let conn = database::connect(&db).await.unwrap();393 let conn = database::connect(&db).await.unwrap();
122 let user = user::create("Tahinli", "hash", &conn).await.unwrap();394 let user = user::create("Tahinli", "hash", &conn).await.unwrap();
123- let community = community::create("Tahinli", &user.id, &conn).await.unwrap();395+ let community = community::create("Tahinli", &conn).await.unwrap();
124- let created_message = message::create(&user.id, &community.id, "Tahinli", &conn)396+ let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn)
125 .await397 .await
126 .unwrap();398 .unwrap();
127 399
@@ -136,17 +408,15 @@ mod tests {
136 let conn = database::connect(&db).await.unwrap();408 let conn = database::connect(&db).await.unwrap();
137 let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap();409 let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap();
138 let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap();410 let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap();
139- let community = community::create("Tahinli", &user_1.id, &conn)411+ let community = community::create("Tahinli", &conn).await.unwrap();
140- .await
141- .unwrap();
142 412
143- let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &conn)413+ let message_1 = message::create(&user_1.id, &community.id, "Tahinli", &[], None, &conn)
144 .await414 .await
145 .unwrap();415 .unwrap();
146- let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &conn)416+ let message_2 = message::create(&user_2.id, &community.id, "Tahinli", &[], None, &conn)
147 .await417 .await
148 .unwrap();418 .unwrap();
149- let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &conn)419+ let message_3 = message::create(&user_2.id, &community.id, "Tahinli", &[], None, &conn)
150 .await420 .await
151 .unwrap();421 .unwrap();
152 422
@@ -169,8 +439,8 @@ mod tests {
169 let db = test::get_database().await;439 let db = test::get_database().await;
170 let conn = database::connect(&db).await.unwrap();440 let conn = database::connect(&db).await.unwrap();
171 let user = user::create("Tahinli", "hash", &conn).await.unwrap();441 let user = user::create("Tahinli", "hash", &conn).await.unwrap();
172- let community = community::create("Tahinli", &user.id, &conn).await.unwrap();442+ let community = community::create("Tahinli", &conn).await.unwrap();
173- let created_message = message::create(&user.id, &community.id, "Tahinli", &conn)443+ let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn)
174 .await444 .await
175 .unwrap();445 .unwrap();
176 446
@@ -203,8 +473,8 @@ mod tests {
203 let db = test::get_database().await;473 let db = test::get_database().await;
204 let conn = database::connect(&db).await.unwrap();474 let conn = database::connect(&db).await.unwrap();
205 let user = user::create("Tahinli", "hash", &conn).await.unwrap();475 let user = user::create("Tahinli", "hash", &conn).await.unwrap();
206- let community = community::create("Tahinli", &user.id, &conn).await.unwrap();476+ let community = community::create("Tahinli", &conn).await.unwrap();
207- let created_message = message::create(&user.id, &community.id, "Tahinli", &conn)477+ let created_message = message::create(&user.id, &community.id, "Tahinli", &[], None, &conn)
208 .await478 .await
209 .unwrap();479 .unwrap();
210 480
@@ -212,4 +482,32 @@ mod tests {
212 482
213 assert_eq!(created_message, deleted_message);483 assert_eq!(created_message, deleted_message);
214 }484 }
485+
486+ #[tokio::test]
487+ async fn forward_two_as_snippet() {
488+ let db = test::get_database().await;
489+ let conn = database::connect(&db).await.unwrap();
490+ let user = user::create("Tahinli", "hash", &conn).await.unwrap();
491+ let community = community::create("Tahinli", &conn).await.unwrap();
492+ let first = message::create(&user.id, &community.id, "First", &[], None, &conn)
493+ .await
494+ .unwrap();
495+ let second = message::create(&user.id, &community.id, "Second", &[], None, &conn)
496+ .await
497+ .unwrap();
498+
499+ let created = message::forward(
500+ &user,
501+ &community.id,
502+ &[first, second],
503+ true,
504+ &test::directory(),
505+ &conn,
506+ )
507+ .await
508+ .unwrap();
509+
510+ assert_eq!(1, created.len());
511+ assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len());
512+ }
215 }513 }
crates/server/src/network.rsmodified+108 -17
@@ -1,18 +1,27 @@
1-use std::sync::{Arc, Mutex};1+use std::{
2+ path::PathBuf,
3+ sync::{Arc, Mutex},
4+};
2 5
3 use common::{6 use common::{
4 event::Event as Push,7 event::Event as Push,
5 model::User,8 model::User,
6- network::{REQUEST_MAX_READ_LENGTH, receive_request, send_event, send_response},9+ network::{
10+ REQUEST_MAX_READ_LENGTH, StreamKind, receive_request, receive_stream_kind, send_event,
11+ send_response,
12+ },
13+ voice::decode_packet,
7 };14 };
8 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};15 use quinn::{Connection, Endpoint, Incoming, RecvStream, SendStream};
9 use tokio::{sync::mpsc, task::JoinHandle};16 use tokio::{sync::mpsc, task::JoinHandle};
10 use tracing::{info, warn};17 use tracing::{info, warn};
11 18
12 use crate::{19 use crate::{
13- database::DB,20+ attachment,
21+ database::{self, DB},
14 error::Error,22 error::Error,
15 request::{self, Broadcast},23 request::{self, Broadcast},
24+ voice::Voice,
16 };25 };
17 26
18 const CHANNEL_LENGTH: usize = 2048;27 const CHANNEL_LENGTH: usize = 2048;
@@ -37,7 +46,7 @@ enum Event {
37 SignedOut {46 SignedOut {
38 connection_id: usize,47 connection_id: usize,
39 },48 },
40- Broadcast(Broadcast),49+ Broadcast(Box<Broadcast>),
41 }50 }
42 51
43 struct Session {52 struct Session {
@@ -52,26 +61,36 @@ pub async fn serve(
52 server_address: &str,61 server_address: &str,
53 server_config: quinn::ServerConfig,62 server_config: quinn::ServerConfig,
54 db: DB,63 db: DB,
64+ directory: PathBuf,
55 ) -> Result<(), Error> {65 ) -> Result<(), Error> {
56 let endpoint = Endpoint::server(server_config, server_address.parse()?)?;66 let endpoint = Endpoint::server(server_config, server_address.parse()?)?;
57 info!("listening on {server_address}");67 info!("listening on {server_address}");
58 68
59 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH);69 let (event_sender, event_receiver) = mpsc::channel(CHANNEL_LENGTH);
60 tokio::spawn(the_actor(event_receiver));70 tokio::spawn(the_actor(event_receiver));
71+ let voice = Voice::default();
61 72
62 while let Some(incoming) = endpoint.accept().await {73 while let Some(incoming) = endpoint.accept().await {
63 tokio::spawn(handle_connection(74 tokio::spawn(handle_connection(
64 incoming,75 incoming,
65 event_sender.clone(),76 event_sender.clone(),
66 db.clone(),77 db.clone(),
78+ voice.clone(),
79+ directory.clone(),
67 ));80 ));
68 }81 }
69 82
70 Ok(())83 Ok(())
71 }84 }
72 85
73-async fn handle_connection(incoming: Incoming, event_sender: mpsc::Sender<Event>, db: DB) {86+async fn handle_connection(
74- if let Err(error) = serve_connection(incoming, event_sender, db).await {87+ incoming: Incoming,
88+ event_sender: mpsc::Sender<Event>,
89+ db: DB,
90+ voice: Voice,
91+ directory: PathBuf,
92+) {
93+ if let Err(error) = serve_connection(incoming, event_sender, db, voice, directory).await {
75 warn!("connection: {error}");94 warn!("connection: {error}");
76 }95 }
77 }96 }
@@ -80,6 +99,8 @@ async fn serve_connection(
80 incoming: Incoming,99 incoming: Incoming,
81 event_sender: mpsc::Sender<Event>,100 event_sender: mpsc::Sender<Event>,
82 db: DB,101 db: DB,
102+ voice: Voice,
103+ directory: PathBuf,
83 ) -> Result<(), Error> {104 ) -> Result<(), Error> {
84 let connection = incoming.await?;105 let connection = incoming.await?;
85 let send_stream = connection.open_uni().await?;106 let send_stream = connection.open_uni().await?;
@@ -93,35 +114,96 @@ async fn serve_connection(
93 114
94 let state = Arc::new(Mutex::new(State::Anonymous));115 let state = Arc::new(Mutex::new(State::Anonymous));
95 116
96- while let Ok((send_stream, receive_stream)) = connection.accept_bi().await {117+ tokio::spawn(relay_datagrams(
97- tokio::spawn(answer(118+ connection.clone(),
98- connection.stable_id(),119+ Arc::clone(&state),
120+ voice.clone(),
121+ ));
122+
123+ while let Ok(streams) = connection.accept_bi().await {
124+ tokio::spawn(route(
125+ connection.clone(),
99 Arc::clone(&state),126 Arc::clone(&state),
100- send_stream,127+ streams,
101- receive_stream,
102 event_sender.clone(),128 event_sender.clone(),
103 db.clone(),129 db.clone(),
130+ voice.clone(),
131+ directory.clone(),
104 ));132 ));
105 }133 }
106 134
135+ if signed_user_id(&state).is_some() {
136+ let conn = database::connect(&db).await?;
137+ let broadcasts = request::leave_connection_voice(&voice, Some(&connection), &conn).await?;
138+ for broadcast in broadcasts {
139+ let _ = event_sender
140+ .send(Event::Broadcast(Box::new(broadcast)))
141+ .await;
142+ }
143+ }
144+
107 Ok(())145 Ok(())
108 }146 }
109 147
148+async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, voice: Voice) {
149+ while let Ok(bytes) = connection.read_datagram().await {
150+ if signed_user_id(&state).is_some() && decode_packet(&bytes).is_some() {
151+ voice.relay(connection.stable_id(), &bytes);
152+ }
153+ }
154+}
155+
156+async fn route(
157+ connection: Connection,
158+ state: Arc<Mutex<State>>,
159+ (send_stream, mut receive_stream): (SendStream, RecvStream),
160+ event_sender: mpsc::Sender<Event>,
161+ db: DB,
162+ voice: Voice,
163+ directory: PathBuf,
164+) -> Result<(), Error> {
165+ match receive_stream_kind(&mut receive_stream).await? {
166+ StreamKind::Request => {
167+ answer(
168+ connection,
169+ state,
170+ (send_stream, receive_stream),
171+ event_sender,
172+ db,
173+ voice,
174+ directory,
175+ )
176+ .await
177+ }
178+ StreamKind::Upload => {
179+ let user = signed_user(&state);
180+ attachment::upload(user.as_ref(), receive_stream, send_stream, &db, &directory).await
181+ }
182+ StreamKind::Download => {
183+ let user = signed_user(&state);
184+ attachment::download(user.as_ref(), receive_stream, send_stream, &db, &directory).await
185+ }
186+ }
187+}
188+
110 async fn answer(189 async fn answer(
111- connection_id: usize,190+ connection: Connection,
112 state: Arc<Mutex<State>>,191 state: Arc<Mutex<State>>,
113- send_stream: SendStream,192+ (send_stream, receive_stream): (SendStream, RecvStream),
114- receive_stream: RecvStream,
115 event_sender: mpsc::Sender<Event>,193 event_sender: mpsc::Sender<Event>,
116 db: DB,194 db: DB,
195+ voice: Voice,
196+ directory: PathBuf,
117 ) -> Result<(), Error> {197 ) -> Result<(), Error> {
118 let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?;198 let request = receive_request(receive_stream, REQUEST_MAX_READ_LENGTH).await?;
119 199
120 let before = signed_user_id(&state);200 let before = signed_user_id(&state);
121- let (response, broadcast) = request::handle(request, &state, &db).await;201+ let (response, broadcasts) =
202+ request::handle(request, &state, &db, &voice, Some(&connection), &directory).await;
122 let after = signed_user_id(&state);203 let after = signed_user_id(&state);
123 204
124 if before != after {205 if before != after {
206+ let connection_id = connection.stable_id();
125 let event = match after {207 let event = match after {
126 Some(user_id) => Event::SignedIn {208 Some(user_id) => Event::SignedIn {
127 connection_id,209 connection_id,
@@ -132,8 +214,10 @@ async fn answer(
132 let _ = event_sender.send(event).await;214 let _ = event_sender.send(event).await;
133 }215 }
134 216
135- if let Some(broadcast) = broadcast {217+ for broadcast in broadcasts {
136- let _ = event_sender.send(Event::Broadcast(broadcast)).await;218+ let _ = event_sender
219+ .send(Event::Broadcast(Box::new(broadcast)))
220+ .await;
137 }221 }
138 222
139 send_response(&response, send_stream).await?;223 send_response(&response, send_stream).await?;
@@ -141,6 +225,13 @@ async fn answer(
141 Ok(())225 Ok(())
142 }226 }
143 227
228+fn signed_user(state: &Mutex<State>) -> Option<User> {
229+ match &*state.lock().unwrap() {
230+ State::Anonymous => None,
231+ State::Authenticated { user, .. } => Some(user.clone()),
232+ }
233+}
234+
144 fn signed_user_id(state: &Mutex<State>) -> Option<String> {235 fn signed_user_id(state: &Mutex<State>) -> Option<String> {
145 match &*state.lock().unwrap() {236 match &*state.lock().unwrap() {
146 State::Anonymous => None,237 State::Anonymous => None,
crates/server/src/request.rsmodified+891 -81
@@ -1,20 +1,25 @@
1-use std::sync::Mutex;1+use std::{collections::BTreeSet, path::Path, sync::Mutex};
2 2
3 use common::{3 use common::{
4 error::Error as CommonError,4 error::Error as CommonError,
5 event::Event,5 event::Event,
6- model::{Community, Message, User},6+ model::{CommunityKind, LogAction, Member, Rank, User},
7+ permission,
7 request::Request,8 request::Request,
8 response::Response,9 response::Response,
10+ validate::{validate_forward, validate_reason},
9 };11 };
12+use turso::Connection;
10 13
11 use crate::{14 use crate::{
12 authentication, community,15 authentication, community,
13 database::{self, DB},16 database::{self, DB},
17+ direct,
14 error::Error,18 error::Error,
15- message,19+ friend, invitation, log, message,
16 network::State,20 network::State,
17 user, user_community,21 user, user_community,
22+ voice::Voice,
18 };23 };
19 24
20 pub struct Broadcast {25 pub struct Broadcast {
@@ -22,40 +27,67 @@ pub struct Broadcast {
22 pub user_ids: Vec<String>,27 pub user_ids: Vec<String>,
23 }28 }
24 29
25-type Outcome = (Response, Option<Broadcast>);30+type Outcome = (Response, Vec<Broadcast>);
26 31
27-pub async fn handle(request: Request, state: &Mutex<State>, db: &DB) -> Outcome {32+pub async fn handle(
28- match dispatch(request, state, db).await {33+ request: Request,
34+ state: &Mutex<State>,
35+ db: &DB,
36+ voice: &Voice,
37+ connection: Option<&quinn::Connection>,
38+ directory: &Path,
39+) -> Outcome {
40+ match dispatch(request, state, db, voice, connection, directory).await {
29 Ok(outcome) => outcome,41 Ok(outcome) => outcome,
30- Err(error) => (Response::Error(error.into()), None),42+ Err(error) => (Response::Error(error.into()), Vec::new()),
31 }43 }
32 }44 }
33 45
34-async fn dispatch(request: Request, state: &Mutex<State>, db: &DB) -> Result<Outcome, Error> {46+async fn dispatch(
47+ request: Request,
48+ state: &Mutex<State>,
49+ db: &DB,
50+ voice: &Voice,
51+ connection: Option<&quinn::Connection>,
52+ directory: &Path,
53+) -> Result<Outcome, Error> {
35 let mut conn = database::connect(db).await?;54 let mut conn = database::connect(db).await?;
36 55
37 let outcome = match request {56 let outcome = match request {
38 Request::Register { username, password } => {57 Request::Register { username, password } => {
39 let (user, token) = authentication::register(&username, &password, &mut conn).await?;58 let (user, token) = authentication::register(&username, &password, &mut conn).await?;
40- sign_in(state, user, token)59+ let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
60+ sign_in(state, user, token, broadcasts)
41 }61 }
42 Request::Login { username, password } => {62 Request::Login { username, password } => {
43 let (user, token) = authentication::login(&username, &password, &conn).await?;63 let (user, token) = authentication::login(&username, &password, &conn).await?;
44- sign_in(state, user, token)64+ let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
65+ sign_in(state, user, token, broadcasts)
45 }66 }
46 Request::Resume { token } => {67 Request::Resume { token } => {
47 let user = authentication::resume(&token, &conn).await?;68 let user = authentication::resume(&token, &conn).await?;
48- sign_in(state, user, token)69+ let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
70+ sign_in(state, user, token, broadcasts)
71+ }
72+ Request::Detach => {
73+ authenticated(state)?;
74+ let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
75+ set_state(state, State::Anonymous);
76+ (Response::Done, broadcasts)
49 }77 }
50 Request::Logout => {78 Request::Logout => {
51 let (_, token) = authenticated(state)?;79 let (_, token) = authenticated(state)?;
52 authentication::logout(&token, &conn).await?;80 authentication::logout(&token, &conn).await?;
81+ let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
53 set_state(state, State::Anonymous);82 set_state(state, State::Anonymous);
54- (Response::Done, None)83+ (Response::Done, broadcasts)
55 }84 }
56 Request::ReadUser { user_id } => {85 Request::ReadUser { user_id } => {
57 authenticated(state)?;86 authenticated(state)?;
58- (Response::User(user::read(&user_id, &conn).await?), None)87+ (
88+ Response::User(user::read(&user_id, &conn).await?),
89+ Vec::new(),
90+ )
59 }91 }
60 Request::UpdateUser { username } => {92 Request::UpdateUser { username } => {
61 let (me, token) = authenticated(state)?;93 let (me, token) = authenticated(state)?;
@@ -67,116 +99,353 @@ async fn dispatch(request: Request, state: &Mutex<State>, db: &DB) -> Result<Out
67 token,99 token,
68 },100 },
69 );101 );
70- (Response::User(user), None)102+ let broadcasts = user_updated(&user, &conn).await?;
103+ (Response::User(user), broadcasts)
71 }104 }
72- Request::DeleteUser => {105+ Request::UpdateStatus { status } => {
106+ let (me, token) = authenticated(state)?;
107+ let user = user::update_status(&me.id, &status, &conn).await?;
108+ set_state(
109+ state,
110+ State::Authenticated {
111+ user: user.clone(),
112+ token,
113+ },
114+ );
115+ let broadcasts = user_updated(&user, &conn).await?;
116+ (Response::User(user), broadcasts)
117+ }
118+ Request::UpdateAvatar { image } => {
119+ let (me, token) = authenticated(state)?;
120+ let user = user::set_avatar(&me.id, &image, &mut conn).await?;
121+ set_state(
122+ state,
123+ State::Authenticated {
124+ user: user.clone(),
125+ token,
126+ },
127+ );
128+ let broadcasts = user_updated(&user, &conn).await?;
129+ (Response::User(user), broadcasts)
130+ }
131+ Request::RemoveAvatar => {
132+ let (me, token) = authenticated(state)?;
133+ let user = user::remove_avatar(&me.id, &mut conn).await?;
134+ set_state(
135+ state,
136+ State::Authenticated {
137+ user: user.clone(),
138+ token,
139+ },
140+ );
141+ let broadcasts = user_updated(&user, &conn).await?;
142+ (Response::User(user), broadcasts)
143+ }
144+ Request::ReadAvatar { avatar_id } => {
145+ authenticated(state)?;
146+ (
147+ Response::Avatar(user::avatar(&avatar_id, &conn).await?),
148+ Vec::new(),
149+ )
150+ }
151+ Request::DeleteUser { user_id } => {
73 let (me, _) = authenticated(state)?;152 let (me, _) = authenticated(state)?;
74- let user = user::delete(&me.id, &conn).await?;153+ let target = user::read(&user_id, &conn).await?;
75- set_state(state, State::Anonymous);154+ ensure(permission::can_delete_user(
76- (Response::User(user), None)155+ me.role,
156+ me.id == user_id,
157+ target.role,
158+ ))?;
159+ let tx = conn.transaction().await?;
160+ let mut broadcasts = Vec::new();
161+ for community_id in user_community::owned(&user_id, &tx).await? {
162+ let members = user_community::members(&community_id, &tx).await?;
163+ voice.remove_room(&community_id);
164+ community::delete(&community_id, &user_id, &tx).await?;
165+ let event = Event::CommunityDeleted { community_id };
166+ broadcasts.extend(broadcast(event, &members));
167+ }
168+ for community in community::communities_of(&user_id, &tx).await? {
169+ let members = user_community::members(&community.id, &tx).await?;
170+ if matches!(community.kind, CommunityKind::Direct { .. }) {
171+ community::delete(&community.id, &user_id, &tx).await?;
172+ }
173+ let event = Event::UserDeleted {
174+ user_id: user_id.clone(),
175+ };
176+ broadcasts.extend(broadcast(event, &members));
177+ }
178+ broadcasts.extend(leave_voice(voice, &user_id, &tx).await?);
179+ let deleted = user::delete(&user_id, &tx).await?;
180+ tx.commit().await?;
181+ if me.id == user_id {
182+ set_state(state, State::Anonymous);
183+ }
184+ (Response::User(deleted), broadcasts)
77 }185 }
78 Request::CreateCommunity { name } => {186 Request::CreateCommunity { name } => {
79 let (me, _) = authenticated(state)?;187 let (me, _) = authenticated(state)?;
80 let tx = conn.transaction().await?;188 let tx = conn.transaction().await?;
81- let community = community::create(&name, &me.id, &tx).await?;189+ let community = community::create(&name, &tx).await?;
82- user_community::join(&me.id, &community.id, &tx).await?;190+ user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?;
191+ log::record(&community.id, Some(&me.id), None, &LogAction::Created, &tx).await?;
83 tx.commit().await?;192 tx.commit().await?;
84- (Response::Community(community), None)193+ (Response::Community(community), Vec::new())
85 }194 }
86 Request::ReadCommunity { community_id } => {195 Request::ReadCommunity { community_id } => {
87- authenticated(state)?;196+ let (me, _) = authenticated(state)?;
88 (197 (
89- Response::Community(community::read(&community_id, &conn).await?),198+ Response::Community(community::read(&community_id, &me.id, &conn).await?),
90- None,199+ Vec::new(),
91 )200 )
92 }201 }
93 Request::UpdateCommunity { community_id, name } => {202 Request::UpdateCommunity { community_id, name } => {
94 let (me, _) = authenticated(state)?;203 let (me, _) = authenticated(state)?;
95- let existing = community::read(&community_id, &conn).await?;204+ ensure(!community::is_direct(&community_id, &conn).await?)?;
96- ensure_owner(&existing, &me)?;205+ ensure(permission::can_rename_community(
97- let updated = community::update(&community_id, &name, &conn).await?;206+ actor_rank(&me, &community_id, &conn).await?,
207+ ))?;
208+ let updated = community::update(&community_id, &name, &me.id, &conn).await?;
209+ let action = LogAction::Renamed {
210+ name: updated.name.clone(),
211+ };
212+ log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
213+ let members = user_community::members(&community_id, &conn).await?;
214+ let event = Event::CommunityUpdated(updated.clone());
215+ (Response::Community(updated), broadcast(event, &members))
216+ }
217+ Request::UpdateCommunityAvatar {
218+ community_id,
219+ image,
220+ } => {
221+ let (me, _) = authenticated(state)?;
222+ ensure(!community::is_direct(&community_id, &conn).await?)?;
223+ ensure(permission::can_rename_community(
224+ actor_rank(&me, &community_id, &conn).await?,
225+ ))?;
226+ let updated =
227+ community::set_avatar(&community_id, image.as_deref(), &me.id, &mut conn).await?;
228+ let action = if image.is_some() {
229+ LogAction::AvatarChanged
230+ } else {
231+ LogAction::AvatarRemoved
232+ };
233+ log::record(&community_id, Some(&me.id), None, &action, &conn).await?;
98 let members = user_community::members(&community_id, &conn).await?;234 let members = user_community::members(&community_id, &conn).await?;
99 let event = Event::CommunityUpdated(updated.clone());235 let event = Event::CommunityUpdated(updated.clone());
100 (Response::Community(updated), broadcast(event, &members))236 (Response::Community(updated), broadcast(event, &members))
101 }237 }
102 Request::DeleteCommunity { community_id } => {238 Request::DeleteCommunity { community_id } => {
103 let (me, _) = authenticated(state)?;239 let (me, _) = authenticated(state)?;
104- let existing = community::read(&community_id, &conn).await?;240+ ensure(!community::is_direct(&community_id, &conn).await?)?;
105- ensure_owner(&existing, &me)?;241+ ensure(permission::can_delete_community(
242+ actor_rank(&me, &community_id, &conn).await?,
243+ ))?;
106 let tx = conn.transaction().await?;244 let tx = conn.transaction().await?;
107 let members = user_community::members(&community_id, &tx).await?;245 let members = user_community::members(&community_id, &tx).await?;
108- let deleted = community::delete(&community_id, &tx).await?;246+ let deleted = community::delete(&community_id, &me.id, &tx).await?;
109 tx.commit().await?;247 tx.commit().await?;
248+ voice.remove_room(&community_id);
110 let event = Event::CommunityDeleted {249 let event = Event::CommunityDeleted {
111 community_id: deleted.id.clone(),250 community_id: deleted.id.clone(),
112 };251 };
113 (Response::Community(deleted), broadcast(event, &members))252 (Response::Community(deleted), broadcast(event, &members))
114 }253 }
115- Request::SearchCommunity { name } => {
116- authenticated(state)?;
117- (
118- Response::Communities(community::read_by_name(&name, &conn).await?),
119- None,
120- )
121- }
122- Request::JoinCommunity { community_id } => {
123- let (me, _) = authenticated(state)?;
124- let existing = community::read(&community_id, &conn).await?;
125- let tx = conn.transaction().await?;
126- if user_community::is_member(&me.id, &community_id, &tx).await? {
127- return Err(CommonError::Taken.into());
128- }
129- user_community::join(&me.id, &community_id, &tx).await?;
130- let members = user_community::members(&community_id, &tx).await?;
131- tx.commit().await?;
132- let event = Event::MemberJoined {
133- community_id,
134- user: me,
135- };
136- (Response::Community(existing), broadcast(event, &members))
137- }
138 Request::LeaveCommunity { community_id } => {254 Request::LeaveCommunity { community_id } => {
139 let (me, _) = authenticated(state)?;255 let (me, _) = authenticated(state)?;
256+ ensure(!community::is_direct(&community_id, &conn).await?)?;
257+ ensure(permission::can_leave(
258+ actor_rank(&me, &community_id, &conn).await?,
259+ ))?;
140 let tx = conn.transaction().await?;260 let tx = conn.transaction().await?;
141 user_community::leave(&me.id, &community_id, &tx).await?;261 user_community::leave(&me.id, &community_id, &tx).await?;
262+ log::record(&community_id, Some(&me.id), None, &LogAction::Left, &tx).await?;
142 let members = user_community::members(&community_id, &tx).await?;263 let members = user_community::members(&community_id, &tx).await?;
143 if members.is_empty() {264 if members.is_empty() {
144- community::delete(&community_id, &tx).await?;265+ community::delete(&community_id, &me.id, &tx).await?;
145 }266 }
146 tx.commit().await?;267 tx.commit().await?;
268+ let mut broadcasts = voice_leave(voice, &community_id, &me.id, &members);
147 let event = Event::MemberLeft {269 let event = Event::MemberLeft {
148 community_id,270 community_id,
149 user_id: me.id,271 user_id: me.id,
150 };272 };
151- (Response::Done, broadcast(event, &members))273+ broadcasts.extend(broadcast(event, &members));
274+ (Response::Done, broadcasts)
152 }275 }
153 Request::Communities => {276 Request::Communities => {
154 let (me, _) = authenticated(state)?;277 let (me, _) = authenticated(state)?;
155 (278 (
156 Response::Communities(community::communities_of(&me.id, &conn).await?),279 Response::Communities(community::communities_of(&me.id, &conn).await?),
157- None,280+ Vec::new(),
158 )281 )
159 }282 }
160 Request::Members { community_id } => {283 Request::Members { community_id } => {
161 let (me, _) = authenticated(state)?;284 let (me, _) = authenticated(state)?;
162- user_community::ensure_member(&me.id, &community_id, &conn).await?;285+ ensure(permission::can_read(
286+ actor_rank(&me, &community_id, &conn).await?,
287+ ))?;
163 (288 (
164 Response::Members(user_community::members(&community_id, &conn).await?),289 Response::Members(user_community::members(&community_id, &conn).await?),
165- None,290+ Vec::new(),
166 )291 )
167 }292 }
168- Request::CreateMessage { community_id, body } => {293+ Request::Kick {
294+ community_id,
295+ user_id,
296+ reason,
297+ } => {
169 let (me, _) = authenticated(state)?;298 let (me, _) = authenticated(state)?;
170- user_community::ensure_member(&me.id, &community_id, &conn).await?;299+ remove_member(
171- let created = message::create(&me.id, &community_id, &body, &conn).await?;300+ &me,
301+ Removal {
302+ community_id,
303+ user_id,
304+ reason,
305+ banned: false,
306+ },
307+ voice,
308+ &mut conn,
309+ )
310+ .await?
311+ }
312+ Request::Ban {
313+ community_id,
314+ user_id,
315+ reason,
316+ } => {
317+ let (me, _) = authenticated(state)?;
318+ remove_member(
319+ &me,
320+ Removal {
321+ community_id,
322+ user_id,
323+ reason,
324+ banned: true,
325+ },
326+ voice,
327+ &mut conn,
328+ )
329+ .await?
330+ }
331+ Request::Unban {
332+ community_id,
333+ user_id,
334+ } => {
335+ let (me, _) = authenticated(state)?;
336+ ensure(permission::can_unban(
337+ actor_rank(&me, &community_id, &conn).await?,
338+ ))?;
339+ user_community::unban(&user_id, &community_id, &conn).await?;
340+ log::record(
341+ &community_id,
342+ Some(&me.id),
343+ Some(&user_id),
344+ &LogAction::Unbanned,
345+ &conn,
346+ )
347+ .await?;
348+ (Response::Done, Vec::new())
349+ }
350+ Request::Bans { community_id } => {
351+ let (me, _) = authenticated(state)?;
352+ ensure(permission::can_unban(
353+ actor_rank(&me, &community_id, &conn).await?,
354+ ))?;
355+ (
356+ Response::Bans(user_community::bans(&community_id, &conn).await?),
357+ Vec::new(),
358+ )
359+ }
360+ Request::SetRank {
361+ community_id,
362+ user_id,
363+ rank,
364+ } => {
365+ let (me, _) = authenticated(state)?;
366+ ensure(!community::is_direct(&community_id, &conn).await?)?;
367+ let target = user::read(&user_id, &conn).await?;
368+ ensure(permission::can_set_rank(
369+ actor_rank(&me, &community_id, &conn).await?,
370+ actor_rank(&target, &community_id, &conn).await?,
371+ rank,
372+ ))?;
373+ user_community::set_rank(&user_id, &community_id, rank, &conn).await?;
374+ log::record(
375+ &community_id,
376+ Some(&me.id),
377+ Some(&user_id),
378+ &LogAction::RankChanged { rank },
379+ &conn,
380+ )
381+ .await?;
382+ let members = user_community::members(&community_id, &conn).await?;
383+ let event = Event::RankChanged {
384+ community_id,
385+ user_id,
386+ rank,
387+ };
388+ (Response::Done, broadcast(event, &members))
389+ }
390+ Request::CreateMessage {
391+ community_id,
392+ body,
393+ attachments,
394+ reply_to,
395+ } => {
396+ let (me, _) = authenticated(state)?;
397+ ensure(permission::can_post(
398+ actor_rank(&me, &community_id, &conn).await?,
399+ ))?;
400+ let tx = conn.transaction().await?;
401+ let created = message::create(
402+ &me.id,
403+ &community_id,
404+ &body,
405+ &attachments,
406+ reply_to.as_deref(),
407+ &tx,
408+ )
409+ .await?;
410+ tx.commit().await?;
172 let members = user_community::members(&community_id, &conn).await?;411 let members = user_community::members(&community_id, &conn).await?;
173 let event = Event::MessageCreated(created.clone());412 let event = Event::MessageCreated(created.clone());
174 (Response::Message(created), broadcast(event, &members))413 (Response::Message(created), broadcast(event, &members))
175 }414 }
415+ Request::ForwardMessages {
416+ message_ids,
417+ community_id,
418+ snippet,
419+ } => {
420+ let (me, _) = authenticated(state)?;
421+ validate_forward(message_ids.len())?;
422+ ensure(permission::can_post(
423+ actor_rank(&me, &community_id, &conn).await?,
424+ ))?;
425+ let tx = conn.transaction().await?;
426+ let mut sources = Vec::new();
427+ for message_id in &message_ids {
428+ let source = message::read(message_id, &tx).await?;
429+ ensure(permission::can_read(
430+ actor_rank(&me, &source.community_id, &tx).await?,
431+ ))?;
432+ sources.push(source);
433+ }
434+ let created =
435+ message::forward(&me, &community_id, &sources, snippet, directory, &tx).await?;
436+ tx.commit().await?;
437+ let members = user_community::members(&community_id, &conn).await?;
438+ let mut broadcasts = Vec::new();
439+ for message in &created {
440+ let event = Event::MessageCreated(message.clone());
441+ broadcasts.extend(broadcast(event, &members));
442+ }
443+ (Response::Messages(created), broadcasts)
444+ }
176 Request::UpdateMessage { message_id, body } => {445 Request::UpdateMessage { message_id, body } => {
177 let (me, _) = authenticated(state)?;446 let (me, _) = authenticated(state)?;
178 let existing = message::read(&message_id, &conn).await?;447 let existing = message::read(&message_id, &conn).await?;
179- ensure_author(&existing, &me)?;448+ ensure(permission::can_edit_message(existing.user_id == me.id))?;
180 let updated = message::update(&message_id, &body, &conn).await?;449 let updated = message::update(&message_id, &body, &conn).await?;
181 let members = user_community::members(&updated.community_id, &conn).await?;450 let members = user_community::members(&updated.community_id, &conn).await?;
182 let event = Event::MessageUpdated(updated.clone());451 let event = Event::MessageUpdated(updated.clone());
@@ -185,8 +454,23 @@ async fn dispatch(request: Request, state: &Mutex<State>, db: &DB) -> Result<Out
185 Request::DeleteMessage { message_id } => {454 Request::DeleteMessage { message_id } => {
186 let (me, _) = authenticated(state)?;455 let (me, _) = authenticated(state)?;
187 let existing = message::read(&message_id, &conn).await?;456 let existing = message::read(&message_id, &conn).await?;
188- ensure_author(&existing, &me)?;457+ let author = user::read(&existing.user_id, &conn).await?;
458+ ensure(permission::can_delete_message(
459+ actor_rank(&me, &existing.community_id, &conn).await?,
460+ actor_rank(&author, &existing.community_id, &conn).await?,
461+ existing.user_id == me.id,
462+ ))?;
189 let deleted = message::delete(&message_id, &conn).await?;463 let deleted = message::delete(&message_id, &conn).await?;
464+ if existing.user_id != me.id {
465+ log::record(
466+ &deleted.community_id,
467+ Some(&me.id),
468+ Some(&existing.user_id),
469+ &LogAction::MessageDeleted,
470+ &conn,
471+ )
472+ .await?;
473+ }
190 let members = user_community::members(&deleted.community_id, &conn).await?;474 let members = user_community::members(&deleted.community_id, &conn).await?;
191 let event = Event::MessageDeleted(deleted.clone());475 let event = Event::MessageDeleted(deleted.clone());
192 (Response::Message(deleted), broadcast(event, &members))476 (Response::Message(deleted), broadcast(event, &members))
@@ -196,16 +480,342 @@ async fn dispatch(request: Request, state: &Mutex<State>, db: &DB) -> Result<Out
196 before,480 before,
197 } => {481 } => {
198 let (me, _) = authenticated(state)?;482 let (me, _) = authenticated(state)?;
199- user_community::ensure_member(&me.id, &community_id, &conn).await?;483+ ensure(permission::can_read(
484+ actor_rank(&me, &community_id, &conn).await?,
485+ ))?;
200 let messages = message::read_page(&community_id, before.as_deref(), &conn).await?;486 let messages = message::read_page(&community_id, before.as_deref(), &conn).await?;
201- (Response::Messages(messages), None)487+ (Response::Messages(messages), Vec::new())
488+ }
489+ Request::JoinVoice { community_id } => {
490+ let (me, _) = authenticated(state)?;
491+ ensure(permission::can_join_voice(
492+ actor_rank(&me, &community_id, &conn).await?,
493+ ))?;
494+ let Some(connection) = connection else {
495+ return Err(CommonError::Server.into());
496+ };
497+ let members = user_community::members(&community_id, &conn).await?;
498+ let previous = voice.join(&community_id, &me.id, connection.clone());
499+ let mut broadcasts = Vec::new();
500+ if let Some(previous_id) = previous {
501+ let previous_members = user_community::members(&previous_id, &conn).await?;
502+ let event = Event::VoiceLeft {
503+ community_id: previous_id,
504+ user_id: me.id.clone(),
505+ };
506+ broadcasts.extend(broadcast(event, &previous_members));
507+ }
508+ let event = Event::VoiceJoined {
509+ community_id: community_id.clone(),
510+ user_id: me.id.clone(),
511+ };
512+ broadcasts.extend(broadcast(event, &members));
513+ (
514+ Response::Voice(voice.participants(&community_id)),
515+ broadcasts,
516+ )
517+ }
518+ Request::LeaveVoice => {
519+ authenticated(state)?;
520+ (
521+ Response::Done,
522+ leave_connection_voice(voice, connection, &conn).await?,
523+ )
524+ }
525+ Request::VoiceParticipants { community_id } => {
526+ let (me, _) = authenticated(state)?;
527+ ensure(permission::can_read(
528+ actor_rank(&me, &community_id, &conn).await?,
529+ ))?;
530+ (
531+ Response::Voice(voice.participants(&community_id)),
532+ Vec::new(),
533+ )
534+ }
535+ Request::FindUser { username } => {
536+ authenticated(state)?;
537+ let found = user::by_username(&username, &conn)
538+ .await?
539+ .ok_or(CommonError::NotFound)?;
540+ (Response::User(found), Vec::new())
541+ }
542+ Request::OpenDirect { user_id } => {
543+ let (me, _) = authenticated(state)?;
544+ let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?;
545+ let broadcasts = if created {
546+ let peer_view = community::read(&community.id, &user_id, &conn).await?;
547+ vec![Broadcast {
548+ event: Event::CommunityAdded(peer_view),
549+ user_ids: vec![user_id],
550+ }]
551+ } else {
552+ Vec::new()
553+ };
554+ (Response::Community(community), broadcasts)
555+ }
556+ Request::Friends => {
557+ let (me, _) = authenticated(state)?;
558+ (
559+ Response::Friends(friend::state(&me.id, &conn).await?),
560+ Vec::new(),
561+ )
562+ }
563+ Request::AddFriend { user_id } => {
564+ let (me, _) = authenticated(state)?;
565+ friend::add(&me.id, &user_id, &mut conn).await?;
566+ let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
567+ (Response::Done, broadcasts)
568+ }
569+ Request::AcceptFriend { user_id } => {
570+ let (me, _) = authenticated(state)?;
571+ friend::accept(&me.id, &user_id, &mut conn).await?;
572+ let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
573+ (Response::Done, broadcasts)
574+ }
575+ Request::RemoveFriend { user_id } => {
576+ let (me, _) = authenticated(state)?;
577+ friend::remove(&me.id, &user_id, &mut conn).await?;
578+ let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
579+ (Response::Done, broadcasts)
580+ }
581+ Request::Invite {
582+ community_id,
583+ user_id,
584+ } => {
585+ let (me, _) = authenticated(state)?;
586+ ensure(!community::is_direct(&community_id, &conn).await?)?;
587+ ensure(permission::can_read(
588+ actor_rank(&me, &community_id, &conn).await?,
589+ ))?;
590+ let target = user::read(&user_id, &conn).await?;
591+ if user_community::rank(&user_id, &community_id, &conn)
592+ .await?
593+ .is_some()
594+ {
595+ return Err(CommonError::AlreadyMember.into());
596+ }
597+ let banned = user_community::is_banned(&user_id, &community_id, &conn).await?;
598+ ensure(permission::can_join(target.role, banned))?;
599+ if invitation::exists(&community_id, &user_id, &conn).await? {
600+ return Err(CommonError::AlreadyInvited.into());
601+ }
602+ invitation::insert(&community_id, &user_id, &me.id, &conn).await?;
603+ log::record(
604+ &community_id,
605+ Some(&me.id),
606+ Some(&user_id),
607+ &LogAction::Invited,
608+ &conn,
609+ )
610+ .await?;
611+ let broadcast = invitations_updated(&user_id, &conn).await?;
612+ (Response::Done, vec![broadcast])
613+ }
614+ Request::Invitations => {
615+ let (me, _) = authenticated(state)?;
616+ (
617+ Response::Invitations(invitation::of(&me.id, &conn).await?),
618+ Vec::new(),
619+ )
620+ }
621+ Request::AcceptInvitation { community_id } => {
622+ let (me, _) = authenticated(state)?;
623+ let tx = conn.transaction().await?;
624+ invitation::take(&community_id, &me.id, &tx).await?;
625+ let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;
626+ ensure(permission::can_join(me.role, banned))?;
627+ user_community::join(&me.id, &community_id, Rank::Member, &tx).await?;
628+ log::record(&community_id, Some(&me.id), None, &LogAction::Joined, &tx).await?;
629+ let community = community::read(&community_id, &me.id, &tx).await?;
630+ let members = user_community::members(&community_id, &tx).await?;
631+ tx.commit().await?;
632+ let event = Event::MemberJoined {
633+ community_id,
634+ member: Member {
635+ user: me.clone(),
636+ rank: Rank::Member,
637+ },
638+ };
639+ let mut broadcasts = broadcast(event, &members);
640+ broadcasts.push(invitations_updated(&me.id, &conn).await?);
641+ (Response::Community(community), broadcasts)
642+ }
643+ Request::DeclineInvitation { community_id } => {
644+ let (me, _) = authenticated(state)?;
645+ invitation::take(&community_id, &me.id, &conn).await?;
646+ (
647+ Response::Done,
648+ vec![invitations_updated(&me.id, &conn).await?],
649+ )
650+ }
651+ Request::Logs { community_id } => {
652+ let (me, _) = authenticated(state)?;
653+ ensure(permission::can_read_logs(
654+ actor_rank(&me, &community_id, &conn).await?,
655+ ))?;
656+ (
657+ Response::Logs(log::list(&community_id, &conn).await?),
658+ Vec::new(),
659+ )
202 }660 }
203 };661 };
204 662
205 Ok(outcome)663 Ok(outcome)
206 }664 }
207 665
208-fn sign_in(state: &Mutex<State>, user: User, token: String) -> Outcome {666+struct Removal {
667+ community_id: String,
668+ user_id: String,
669+ reason: Option<String>,
670+ banned: bool,
671+}
672+
673+async fn remove_member(
674+ me: &User,
675+ removal: Removal,
676+ voice: &Voice,
677+ conn: &mut Connection,
678+) -> Result<Outcome, Error> {
679+ let Removal {
680+ community_id,
681+ user_id,
682+ reason,
683+ banned,
684+ } = removal;
685+ validate_reason(reason.as_deref())?;
686+ ensure(!community::is_direct(&community_id, conn).await?)?;
687+ let target = user::read(&user_id, conn).await?;
688+ ensure(permission::can_moderate(
689+ actor_rank(me, &community_id, conn).await?,
690+ actor_rank(&target, &community_id, conn).await?,
691+ ))?;
692+ let community = community::read(&community_id, &me.id, conn).await?;
693+ let tx = conn.transaction().await?;
694+ let members = user_community::members(&community_id, &tx).await?;
695+ user_community::leave(&user_id, &community_id, &tx).await?;
696+ let action = if banned {
697+ user_community::ban(&user_id, &community_id, reason.as_deref(), &tx).await?;
698+ LogAction::Banned {
699+ reason: reason.clone(),
700+ }
701+ } else {
702+ LogAction::Kicked {
703+ reason: reason.clone(),
704+ }
705+ };
706+ log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?;
707+ tx.commit().await?;
708+ let mut broadcasts = voice_leave(voice, &community_id, &user_id, &members);
709+ broadcasts.push(Broadcast {
710+ event: Event::Removed {
711+ community_id: community_id.clone(),
712+ community_name: community.name,
713+ banned,
714+ reason,
715+ },
716+ user_ids: vec![user_id.clone()],
717+ });
718+ let event = Event::MemberLeft {
719+ community_id,
720+ user_id,
721+ };
722+ broadcasts.extend(broadcast(event, &members));
723+
724+ Ok((Response::Done, broadcasts))
725+}
726+
727+async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
728+ let mut user_ids = BTreeSet::new();
729+ for community in community::communities_of(&user.id, conn).await? {
730+ for member in user_community::members(&community.id, conn).await? {
731+ user_ids.insert(member.user.id);
732+ }
733+ }
734+ for friend in friend::state(&user.id, conn).await?.friends {
735+ user_ids.insert(friend.id);
736+ }
737+
738+ Ok(vec![Broadcast {
739+ event: Event::UserUpdated(user.clone()),
740+ user_ids: user_ids.into_iter().collect(),
741+ }])
742+}
743+
744+async fn friends_updated(user_ids: &[&str], conn: &Connection) -> Result<Vec<Broadcast>, Error> {
745+ let mut broadcasts = Vec::new();
746+ for user_id in user_ids {
747+ broadcasts.push(Broadcast {
748+ event: Event::FriendsUpdated(friend::state(user_id, conn).await?),
749+ user_ids: vec![user_id.to_string()],
750+ });
751+ }
752+
753+ Ok(broadcasts)
754+}
755+
756+async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadcast, Error> {
757+ Ok(Broadcast {
758+ event: Event::InvitationsUpdated(invitation::of(user_id, conn).await?),
759+ user_ids: vec![user_id.to_string()],
760+ })
761+}
762+
763+pub async fn leave_voice(
764+ voice: &Voice,
765+ user_id: &str,
766+ conn: &Connection,
767+) -> Result<Vec<Broadcast>, Error> {
768+ let Some(community_id) = voice.leave(user_id) else {
769+ return Ok(Vec::new());
770+ };
771+ let members = user_community::members(&community_id, conn).await?;
772+ let event = Event::VoiceLeft {
773+ community_id,
774+ user_id: user_id.to_string(),
775+ };
776+
777+ Ok(broadcast(event, &members))
778+}
779+
780+pub async fn leave_connection_voice(
781+ voice: &Voice,
782+ connection: Option<&quinn::Connection>,
783+ conn: &Connection,
784+) -> Result<Vec<Broadcast>, Error> {
785+ let Some((community_id, user_id)) =
786+ connection.and_then(|connection| voice.leave_connection(connection.stable_id()))
787+ else {
788+ return Ok(Vec::new());
789+ };
790+ let members = user_community::members(&community_id, conn).await?;
791+
792+ Ok(broadcast(
793+ Event::VoiceLeft {
794+ community_id,
795+ user_id,
796+ },
797+ &members,
798+ ))
799+}
800+
801+fn voice_leave(
802+ voice: &Voice,
803+ community_id: &str,
804+ user_id: &str,
805+ members: &[Member],
806+) -> Vec<Broadcast> {
807+ if !voice.leave_room(community_id, user_id) {
808+ return Vec::new();
809+ }
810+ let event = Event::VoiceLeft {
811+ community_id: community_id.to_string(),
812+ user_id: user_id.to_string(),
813+ };
814+
815+ broadcast(event, members)
816+}
817+
818+fn sign_in(state: &Mutex<State>, user: User, token: String, broadcasts: Vec<Broadcast>) -> Outcome {
209 set_state(819 set_state(
210 state,820 state,
211 State::Authenticated {821 State::Authenticated {
@@ -214,7 +824,7 @@ fn sign_in(state: &Mutex<State>, user: User, token: String) -> Outcome {
214 },824 },
215 );825 );
216 826
217- (Response::Session { user, token }, None)827+ (Response::Session { user, token }, broadcasts)
218 }828 }
219 829
220 fn set_state(state: &Mutex<State>, new_state: State) {830 fn set_state(state: &Mutex<State>, new_state: State) {
@@ -228,27 +838,32 @@ fn authenticated(state: &Mutex<State>) -> Result<(User, String), Error> {
228 }838 }
229 }839 }
230 840
231-fn ensure_owner(community: &Community, me: &User) -> Result<(), Error> {841+pub async fn actor_rank(
232- if community.owner_id != me.id {842+ me: &User,
233- return Err(CommonError::Forbidden.into());843+ community_id: &str,
234- }844+ conn: &Connection,
845+) -> Result<Option<Rank>, Error> {
846+ let rank = user_community::rank(&me.id, community_id, conn).await?;
235 847
236- Ok(())848+ Ok(permission::effective_rank(me.role, rank))
237 }849 }
238 850
239-fn ensure_author(message: &Message, me: &User) -> Result<(), Error> {851+pub fn ensure(allowed: bool) -> Result<(), Error> {
240- if message.user_id != me.id {852+ if !allowed {
241 return Err(CommonError::Forbidden.into());853 return Err(CommonError::Forbidden.into());
242 }854 }
243 855
244 Ok(())856 Ok(())
245 }857 }
246 858
247-fn broadcast(event: Event, members: &[User]) -> Option<Broadcast> {859+fn broadcast(event: Event, members: &[Member]) -> Vec<Broadcast> {
248- Some(Broadcast {860+ vec![Broadcast {
249 event,861 event,
250- user_ids: members.iter().map(|user| user.id.clone()).collect(),862+ user_ids: members
251- })863+ .iter()
864+ .map(|member| member.user.id.clone())
865+ .collect(),
866+ }]
252 }867 }
253 868
254 #[cfg(test)]869 #[cfg(test)]
@@ -263,6 +878,7 @@ mod tests {
263 network::State,878 network::State,
264 request::handle,879 request::handle,
265 test,880 test,
881+ voice::Voice,
266 };882 };
267 883
268 async fn signed_in(username: &str, db: &DB) -> Mutex<State> {884 async fn signed_in(username: &str, db: &DB) -> Mutex<State> {
@@ -274,45 +890,228 @@ mod tests {
274 },890 },
275 &state,891 &state,
276 db,892 db,
893+ &Voice::default(),
894+ None,
895+ &test::directory(),
277 )896 )
278 .await;897 .await;
279 898
280 state899 state
281 }900 }
282 901
902+ async fn invite_and_accept(
903+ community_id: &str,
904+ owner: &Mutex<State>,
905+ member: &Mutex<State>,
906+ username: &str,
907+ db: &DB,
908+ ) {
909+ let voice = Voice::default();
910+ let (Response::User(member_user), _) = handle(
911+ Request::FindUser {
912+ username: username.to_string(),
913+ },
914+ owner,
915+ db,
916+ &voice,
917+ None,
918+ &test::directory(),
919+ )
920+ .await
921+ else {
922+ panic!("user not found");
923+ };
924+ handle(
925+ Request::Invite {
926+ community_id: community_id.to_string(),
927+ user_id: member_user.id,
928+ },
929+ owner,
930+ db,
931+ &voice,
932+ None,
933+ &test::directory(),
934+ )
935+ .await;
936+ handle(
937+ Request::AcceptInvitation {
938+ community_id: community_id.to_string(),
939+ },
940+ member,
941+ db,
942+ &voice,
943+ None,
944+ &test::directory(),
945+ )
946+ .await;
947+ }
948+
283 #[tokio::test]949 #[tokio::test]
284- async fn forbidden_community_update() {950+ async fn plain_member_cannot_rename() {
285 let db = test::get_database().await;951 let db = test::get_database().await;
952+ let voice = Voice::default();
286 let owner = signed_in("Owner", &db).await;953 let owner = signed_in("Owner", &db).await;
287- let other = signed_in("Other", &db).await;954+ let member = signed_in("Member", &db).await;
288 let (Response::Community(community), _) = handle(955 let (Response::Community(community), _) = handle(
289 Request::CreateCommunity {956 Request::CreateCommunity {
290 name: "The Community".to_string(),957 name: "The Community".to_string(),
291 },958 },
292 &owner,959 &owner,
293 &db,960 &db,
961+ &voice,
962+ None,
963+ &test::directory(),
294 )964 )
295 .await965 .await
296 else {966 else {
297 panic!("community not created");967 panic!("community not created");
298 };968 };
969+ invite_and_accept(&community.id, &owner, &member, "Member", &db).await;
299 970
300 let (response, _) = handle(971 let (response, _) = handle(
301 Request::UpdateCommunity {972 Request::UpdateCommunity {
302 community_id: community.id,973 community_id: community.id,
303 name: "Renamed".to_string(),974 name: "Renamed".to_string(),
304 },975 },
305- &other,976+ &member,
306 &db,977 &db,
978+ &voice,
979+ None,
980+ &test::directory(),
307 )981 )
308 .await;982 .await;
309 983
310 assert!(matches!(response, Response::Error(CommonError::Forbidden)));984 assert!(matches!(response, Response::Error(CommonError::Forbidden)));
311 }985 }
312 986
987+ #[tokio::test]
988+ async fn accepted_friend_request_befriends_both() {
989+ let db = test::get_database().await;
990+ let voice = Voice::default();
991+ let first = signed_in("First", &db).await;
992+ let second = signed_in("Second", &db).await;
993+ let (Response::User(first_user), _) = handle(
994+ Request::FindUser {
995+ username: "First".to_string(),
996+ },
997+ &second,
998+ &db,
999+ &voice,
1000+ None,
1001+ &test::directory(),
1002+ )
1003+ .await
1004+ else {
1005+ panic!("user not found");
1006+ };
1007+ let (Response::User(second_user), _) = handle(
1008+ Request::FindUser {
1009+ username: "Second".to_string(),
1010+ },
1011+ &first,
1012+ &db,
1013+ &voice,
1014+ None,
1015+ &test::directory(),
1016+ )
1017+ .await
1018+ else {
1019+ panic!("user not found");
1020+ };
1021+ handle(
1022+ Request::AddFriend {
1023+ user_id: second_user.id.clone(),
1024+ },
1025+ &first,
1026+ &db,
1027+ &voice,
1028+ None,
1029+ &test::directory(),
1030+ )
1031+ .await;
1032+ handle(
1033+ Request::AcceptFriend {
1034+ user_id: first_user.id.clone(),
1035+ },
1036+ &second,
1037+ &db,
1038+ &voice,
1039+ None,
1040+ &test::directory(),
1041+ )
1042+ .await;
1043+
1044+ let (Response::Friends(first_friends), _) = handle(
1045+ Request::Friends,
1046+ &first,
1047+ &db,
1048+ &voice,
1049+ None,
1050+ &test::directory(),
1051+ )
1052+ .await
1053+ else {
1054+ panic!("friends not read");
1055+ };
1056+ let (Response::Friends(second_friends), _) = handle(
1057+ Request::Friends,
1058+ &second,
1059+ &db,
1060+ &voice,
1061+ None,
1062+ &test::directory(),
1063+ )
1064+ .await
1065+ else {
1066+ panic!("friends not read");
1067+ };
1068+
1069+ assert_eq!(vec![second_user], first_friends.friends);
1070+ assert_eq!(vec![first_user], second_friends.friends);
1071+ }
1072+
1073+ #[tokio::test]
1074+ async fn invite_and_accept_makes_member() {
1075+ let db = test::get_database().await;
1076+ let voice = Voice::default();
1077+ let owner = signed_in("Owner", &db).await;
1078+ let member = signed_in("Member", &db).await;
1079+ let (Response::Community(community), _) = handle(
1080+ Request::CreateCommunity {
1081+ name: "The Community".to_string(),
1082+ },
1083+ &owner,
1084+ &db,
1085+ &voice,
1086+ None,
1087+ &test::directory(),
1088+ )
1089+ .await
1090+ else {
1091+ panic!("community not created");
1092+ };
1093+
1094+ invite_and_accept(&community.id, &owner, &member, "Member", &db).await;
1095+
1096+ let (Response::Communities(communities), _) = handle(
1097+ Request::Communities,
1098+ &member,
1099+ &db,
1100+ &voice,
1101+ None,
1102+ &test::directory(),
1103+ )
1104+ .await
1105+ else {
1106+ panic!("communities not read");
1107+ };
1108+ assert_eq!(vec![community], communities);
1109+ }
1110+
313 #[tokio::test]1111 #[tokio::test]
314 async fn delete_community_removes_messages() {1112 async fn delete_community_removes_messages() {
315 let db = test::get_database().await;1113 let db = test::get_database().await;
1114+ let voice = Voice::default();
316 let owner = signed_in("Owner", &db).await;1115 let owner = signed_in("Owner", &db).await;
317 let (Response::Community(community), _) = handle(1116 let (Response::Community(community), _) = handle(
318 Request::CreateCommunity {1117 Request::CreateCommunity {
@@ -320,6 +1119,9 @@ mod tests {
320 },1119 },
321 &owner,1120 &owner,
322 &db,1121 &db,
1122+ &voice,
1123+ None,
1124+ &test::directory(),
323 )1125 )
324 .await1126 .await
325 else {1127 else {
@@ -329,9 +1131,14 @@ mod tests {
329 Request::CreateMessage {1131 Request::CreateMessage {
330 community_id: community.id.clone(),1132 community_id: community.id.clone(),
331 body: "Tahinli".to_string(),1133 body: "Tahinli".to_string(),
1134+ attachments: Vec::new(),
1135+ reply_to: None,
332 },1136 },
333 &owner,1137 &owner,
334 &db,1138 &db,
1139+ &voice,
1140+ None,
1141+ &test::directory(),
335 )1142 )
336 .await;1143 .await;
337 1144
@@ -341,6 +1148,9 @@ mod tests {
341 },1148 },
342 &owner,1149 &owner,
343 &db,1150 &db,
1151+ &voice,
1152+ None,
1153+ &test::directory(),
344 )1154 )
345 .await;1155 .await;
346 1156
crates/server/src/test.rsmodified+12 -0
@@ -1,5 +1,17 @@
1+use std::path::PathBuf;
2+
1 use crate::database::{self, DB};3 use crate::database::{self, DB};
2 4
3 pub async fn get_database() -> DB {5 pub async fn get_database() -> DB {
4 database::open(":memory:").await.unwrap()6 database::open(":memory:").await.unwrap()
5 }7 }
8+
9+pub fn directory() -> PathBuf {
10+ let directory = PathBuf::from(concat!(
11+ env!("CARGO_MANIFEST_DIR"),
12+ "/../../target/attachment-tests"
13+ ));
14+ std::fs::create_dir_all(&directory).unwrap();
15+
16+ directory
17+}
crates/server/src/user.rsmodified+156 -9
@@ -1,4 +1,10 @@
1-use common::{error::Error as CommonError, model::User, validate::validate_username};1+use common::{
2+ constant::AVATAR_SIZE,
3+ error::{Error as CommonError, InvalidInput},
4+ model::{Role, User},
5+ validate::{validate_avatar_size, validate_status, validate_username},
6+};
7+use image::ImageFormat;
2 use turso::{Connection, Row};8 use turso::{Connection, Row};
3 9
4 use crate::{database::new_id, error::Error};10 use crate::{database::new_id, error::Error};
@@ -7,13 +13,22 @@ pub fn from_row(row: &Row) -> Result<User, Error> {
7 Ok(User {13 Ok(User {
8 id: row.get(0)?,14 id: row.get(0)?,
9 username: row.get(1)?,15 username: row.get(1)?,
16+ role: role_of(row)?,
17+ status: row.get(3)?,
18+ avatar_id: row.get(4)?,
10 })19 })
11 }20 }
12 21
22+fn role_of(row: &Row) -> Result<Role, Error> {
23+ let text: String = row.get(2)?;
24+
25+ Ok(Role::parse(&text).ok_or(CommonError::Server)?)
26+}
27+
13 pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {28 pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {
14 let mut rows = conn29 let mut rows = conn
15 .query(30 .query(
16- "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username",31+ "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username, role, status, avatar_id",
17 (new_id(), username, password_hash),32 (new_id(), username, password_hash),
18 )33 )
19 .await?;34 .await?;
@@ -24,7 +39,10 @@ pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> R
24 39
25 pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {40 pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
26 let mut rows = conn41 let mut rows = conn
27- .query("SELECT id, username FROM user WHERE id = ?1", (user_id,))42+ .query(
43+ "SELECT id, username, role, status, avatar_id FROM user WHERE id = ?1",
44+ (user_id,),
45+ )
28 .await?;46 .await?;
29 let row = rows.next().await?.ok_or(CommonError::NotFound)?;47 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
30 48
@@ -34,7 +52,7 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
34 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {52 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {
35 let mut rows = conn53 let mut rows = conn
36 .query(54 .query(
37- "SELECT id, username FROM user WHERE username = ?1",55+ "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1",
38 (username,),56 (username,),
39 )57 )
40 .await?;58 .await?;
@@ -48,7 +66,7 @@ pub async fn credentials(
48 ) -> Result<Option<(User, String)>, Error> {66 ) -> Result<Option<(User, String)>, Error> {
49 let mut rows = conn67 let mut rows = conn
50 .query(68 .query(
51- "SELECT id, username, password_hash FROM user WHERE username = ?1",69+ "SELECT id, username, role, status, avatar_id, password_hash FROM user WHERE username = ?1",
52 (username,),70 (username,),
53 )71 )
54 .await?;72 .await?;
@@ -56,7 +74,7 @@ pub async fn credentials(
56 return Ok(None);74 return Ok(None);
57 };75 };
58 76
59- Ok(Some((from_row(&row)?, row.get(2)?)))77+ Ok(Some((from_row(&row)?, row.get(5)?)))
60 }78 }
61 79
62 pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, Error> {80 pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<User, Error> {
@@ -71,7 +89,7 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<
71 89
72 let mut rows = conn90 let mut rows = conn
73 .query(91 .query(
74- "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username",92+ "UPDATE user SET username = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id",
75 (user_id, username),93 (user_id, username),
76 )94 )
77 .await?;95 .await?;
@@ -80,10 +98,106 @@ pub async fn update(user_id: &str, username: &str, conn: &Connection) -> Result<
80 from_row(&row)98 from_row(&row)
81 }99 }
82 100
101+pub async fn update_status(user_id: &str, status: &str, conn: &Connection) -> Result<User, Error> {
102+ validate_status(status)?;
103+
104+ let mut rows = conn
105+ .query(
106+ "UPDATE user SET status = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id",
107+ (user_id, status),
108+ )
109+ .await?;
110+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
111+
112+ from_row(&row)
113+}
114+
115+pub fn check_avatar(bytes: &[u8]) -> Result<(), Error> {
116+ validate_avatar_size(bytes)?;
117+ let image = image::load_from_memory_with_format(bytes, ImageFormat::Jpeg)
118+ .map_err(|_| CommonError::Avatar(InvalidInput::NotJpeg))?;
119+ if image.width() != AVATAR_SIZE || image.height() != AVATAR_SIZE {
120+ return Err(CommonError::Avatar(InvalidInput::Dimensions {
121+ expected: AVATAR_SIZE,
122+ })
123+ .into());
124+ }
125+
126+ Ok(())
127+}
128+
129+pub async fn set_avatar(user_id: &str, bytes: &[u8], conn: &mut Connection) -> Result<User, Error> {
130+ check_avatar(bytes)?;
131+
132+ let avatar_id = new_id();
133+ let tx = conn.transaction().await?;
134+ tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,))
135+ .await?;
136+ tx.execute(
137+ "INSERT INTO avatar (id, user_id, data) VALUES (?1, ?2, ?3)",
138+ (avatar_id.as_str(), user_id, bytes),
139+ )
140+ .await?;
141+ let user = set_avatar_id(user_id, Some(&avatar_id), &tx).await?;
142+ tx.commit().await?;
143+
144+ Ok(user)
145+}
146+
147+pub async fn remove_avatar(user_id: &str, conn: &mut Connection) -> Result<User, Error> {
148+ let tx = conn.transaction().await?;
149+ tx.execute("DELETE FROM avatar WHERE user_id = ?1", (user_id,))
150+ .await?;
151+ let user = set_avatar_id(user_id, None, &tx).await?;
152+ tx.commit().await?;
153+
154+ Ok(user)
155+}
156+
157+async fn set_avatar_id(
158+ user_id: &str,
159+ avatar_id: Option<&str>,
160+ conn: &Connection,
161+) -> Result<User, Error> {
162+ let mut rows = conn
163+ .query(
164+ "UPDATE user SET avatar_id = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id",
165+ (user_id, avatar_id),
166+ )
167+ .await?;
168+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
169+
170+ from_row(&row)
171+}
172+
173+pub async fn avatar(avatar_id: &str, conn: &Connection) -> Result<Vec<u8>, Error> {
174+ let mut rows = conn
175+ .query(
176+ "SELECT data FROM avatar WHERE id = ?1 UNION ALL SELECT data FROM community_avatar WHERE id = ?1",
177+ (avatar_id,),
178+ )
179+ .await?;
180+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
181+
182+ Ok(row.get(0)?)
183+}
184+
185+pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<User, Error> {
186+ let mut rows = conn
187+ .query(
188+ "UPDATE user SET role = ?2 WHERE username = ?1 RETURNING id, username, role, status, avatar_id",
189+ (username, role.as_str()),
190+ )
191+ .await?;
192+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
193+
194+ from_row(&row)
195+}
196+
83 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {197 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
84 let mut rows = conn198 let mut rows = conn
85 .query(199 .query(
86- "DELETE FROM user WHERE id = ?1 RETURNING id, username",200+ "DELETE FROM user WHERE id = ?1 RETURNING id, username, role, status, avatar_id",
87 (user_id,),201 (user_id,),
88 )202 )
89 .await?;203 .await?;
@@ -94,10 +208,43 @@ pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
94 208
95 #[cfg(test)]209 #[cfg(test)]
96 mod tests {210 mod tests {
97- use common::error::Error as CommonError;211+ use std::io::Cursor;
212+
213+ use common::{constant::AVATAR_SIZE, error::Error as CommonError};
214+ use image::{ImageFormat, RgbImage};
98 215
99 use crate::{database, error::Error, test, user};216 use crate::{database, error::Error, test, user};
100 217
218+ fn jpeg(size: u32) -> Vec<u8> {
219+ let mut bytes = Cursor::new(Vec::new());
220+ RgbImage::new(size, size)
221+ .write_to(&mut bytes, ImageFormat::Jpeg)
222+ .unwrap();
223+
224+ bytes.into_inner()
225+ }
226+
227+ #[tokio::test]
228+ async fn set_avatar_checks_jpeg_size() {
229+ let db = test::get_database().await;
230+ let mut conn = database::connect(&db).await.unwrap();
231+ let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();
232+
233+ let small = user::set_avatar(&created_user.id, &jpeg(AVATAR_SIZE / 2), &mut conn).await;
234+ let not_jpeg = user::set_avatar(&created_user.id, b"not a jpeg", &mut conn).await;
235+ let valid = user::set_avatar(&created_user.id, &jpeg(AVATAR_SIZE), &mut conn)
236+ .await
237+ .unwrap();
238+
239+ assert!(matches!(small, Err(Error::Common(CommonError::Avatar(_)))));
240+ assert!(matches!(
241+ not_jpeg,
242+ Err(Error::Common(CommonError::Avatar(_)))
243+ ));
244+ let avatar_id = valid.avatar_id.unwrap();
245+ assert!(!user::avatar(&avatar_id, &conn).await.unwrap().is_empty());
246+ }
247+
101 #[tokio::test]248 #[tokio::test]
102 async fn create() {249 async fn create() {
103 let db = test::get_database().await;250 let db = test::get_database().await;
crates/server/src/user_community.rsmodified+190 -74
@@ -1,12 +1,26 @@
1-use common::{error::Error as CommonError, model::User};1+use common::{
2-use turso::Connection;2+ error::Error as CommonError,
3+ model::{Ban, Member, Rank},
4+};
5+use turso::{Connection, Row};
3 6
4 use crate::{error::Error, user};7 use crate::{error::Error, user};
5 8
6-pub async fn join(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> {9+fn rank_of(row: &Row, index: usize) -> Result<Rank, Error> {
10+ let text: String = row.get(index)?;
11+
12+ Ok(Rank::parse(&text).ok_or(CommonError::Server)?)
13+}
14+
15+pub async fn join(
16+ user_id: &str,
17+ community_id: &str,
18+ rank: Rank,
19+ conn: &Connection,
20+) -> Result<(), Error> {
7 conn.execute(21 conn.execute(
8- "INSERT INTO user_community (user_id, community_id) VALUES (?1, ?2)",22+ "INSERT INTO user_community (user_id, community_id, rank) VALUES (?1, ?2, ?3)",
9- (user_id, community_id),23+ (user_id, community_id, rank.as_str()),
10 )24 )
11 .await?;25 .await?;
12 26
@@ -14,70 +28,150 @@ pub async fn join(user_id: &str, community_id: &str, conn: &Connection) -> Resul
14 }28 }
15 29
16 pub async fn leave(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> {30 pub async fn leave(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> {
17- let deleted = conn31+ conn.execute(
18- .execute(32+ "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2",
19- "DELETE FROM user_community WHERE user_id = ?1 AND community_id = ?2",33+ (user_id, community_id),
20- (user_id, community_id),34+ )
21- )35+ .await?;
22- .await?;
23-
24- if deleted == 0 {
25- return Err(CommonError::NotFound.into());
26- }
27 36
28 Ok(())37 Ok(())
29 }38 }
30 39
31-pub async fn is_member(40+pub async fn rank(
32 user_id: &str,41 user_id: &str,
33 community_id: &str,42 community_id: &str,
34 conn: &Connection,43 conn: &Connection,
35-) -> Result<bool, Error> {44+) -> Result<Option<Rank>, Error> {
36 let mut rows = conn45 let mut rows = conn
37 .query(46 .query(
38- "SELECT COUNT(*) FROM user_community WHERE user_id = ?1 AND community_id = ?2",47+ "SELECT rank FROM user_community WHERE user_id = ?1 AND community_id = ?2",
39 (user_id, community_id),48 (user_id, community_id),
40 )49 )
41 .await?;50 .await?;
42- let row = rows.next().await?.ok_or(CommonError::NotFound)?;
43- let count: i64 = row.get(0)?;
44 51
45- Ok(count > 0)52+ rows.next()
53+ .await?
54+ .as_ref()
55+ .map(|row| rank_of(row, 0))
56+ .transpose()
46 }57 }
47 58
48-pub async fn ensure_member(59+pub async fn set_rank(
49 user_id: &str,60 user_id: &str,
50 community_id: &str,61 community_id: &str,
62+ rank: Rank,
51 conn: &Connection,63 conn: &Connection,
52 ) -> Result<(), Error> {64 ) -> Result<(), Error> {
53- if !is_member(user_id, community_id, conn).await? {65+ conn.execute(
54- return Err(CommonError::Forbidden.into());66+ "UPDATE user_community SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2",
55- }67+ (user_id, community_id, rank.as_str()),
68+ )
69+ .await?;
56 70
57 Ok(())71 Ok(())
58 }72 }
59 73
60-pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<User>, Error> {74+pub async fn members(community_id: &str, conn: &Connection) -> Result<Vec<Member>, Error> {
61 let mut rows = conn75 let mut rows = conn
62 .query(76 .query(
63- "SELECT user.id, user.username FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id",77+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id, user_community.rank FROM user JOIN user_community ON user_community.user_id = user.id WHERE user_community.community_id = ?1 ORDER BY user.id",
64 (community_id,),78 (community_id,),
65 )79 )
66 .await?;80 .await?;
67 81
68 let mut members = Vec::new();82 let mut members = Vec::new();
69 while let Some(row) = rows.next().await? {83 while let Some(row) = rows.next().await? {
70- members.push(user::from_row(&row)?);84+ members.push(Member {
85+ user: user::from_row(&row)?,
86+ rank: rank_of(&row, 5)?,
87+ });
71 }88 }
72 89
73 Ok(members)90 Ok(members)
74 }91 }
75 92
93+pub async fn owned(user_id: &str, conn: &Connection) -> Result<Vec<String>, Error> {
94+ let mut rows = conn
95+ .query(
96+ "SELECT community_id FROM user_community WHERE user_id = ?1 AND rank = ?2",
97+ (user_id, Rank::Owner.as_str()),
98+ )
99+ .await?;
100+
101+ let mut community_ids = Vec::new();
102+ while let Some(row) = rows.next().await? {
103+ community_ids.push(row.get(0)?);
104+ }
105+
106+ Ok(community_ids)
107+}
108+
109+pub async fn ban(
110+ user_id: &str,
111+ community_id: &str,
112+ reason: Option<&str>,
113+ conn: &Connection,
114+) -> Result<(), Error> {
115+ conn.execute(
116+ "INSERT OR REPLACE INTO ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)",
117+ (user_id, community_id, reason),
118+ )
119+ .await?;
120+
121+ Ok(())
122+}
123+
124+pub async fn unban(user_id: &str, community_id: &str, conn: &Connection) -> Result<(), Error> {
125+ conn.execute(
126+ "DELETE FROM ban WHERE user_id = ?1 AND community_id = ?2",
127+ (user_id, community_id),
128+ )
129+ .await?;
130+
131+ Ok(())
132+}
133+
134+pub async fn is_banned(
135+ user_id: &str,
136+ community_id: &str,
137+ conn: &Connection,
138+) -> Result<bool, Error> {
139+ let mut rows = conn
140+ .query(
141+ "SELECT COUNT(*) FROM ban WHERE user_id = ?1 AND community_id = ?2",
142+ (user_id, community_id),
143+ )
144+ .await?;
145+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
146+ let count: i64 = row.get(0)?;
147+
148+ Ok(count > 0)
149+}
150+
151+pub async fn bans(community_id: &str, conn: &Connection) -> Result<Vec<Ban>, Error> {
152+ let mut rows = conn
153+ .query(
154+ "SELECT user.id, user.username, user.role, user.status, user.avatar_id, ban.reason FROM user JOIN ban ON ban.user_id = user.id WHERE ban.community_id = ?1 ORDER BY ban.rowid DESC",
155+ (community_id,),
156+ )
157+ .await?;
158+
159+ let mut bans = Vec::new();
160+ while let Some(row) = rows.next().await? {
161+ bans.push(Ban {
162+ user: user::from_row(&row)?,
163+ reason: row.get(5)?,
164+ });
165+ }
166+
167+ Ok(bans)
168+}
169+
76 #[cfg(test)]170 #[cfg(test)]
77 mod tests {171 mod tests {
78- use common::error::Error as CommonError;172+ use common::model::{Member, Rank};
79 173
80- use crate::{community, database, error::Error, test, user, user_community};174+ use crate::{community, database, test, user, user_community};
81 175
82 #[tokio::test]176 #[tokio::test]
83 async fn join() {177 async fn join() {
@@ -85,16 +179,21 @@ mod tests {
85 let conn = database::connect(&db).await.unwrap();179 let conn = database::connect(&db).await.unwrap();
86 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();180 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();
87 let member = user::create("Not Tahinli", "hash", &conn).await.unwrap();181 let member = user::create("Not Tahinli", "hash", &conn).await.unwrap();
88- let community = community::create("The Community", &owner.id, &conn)182+ let community = community::create("The Community", &conn).await.unwrap();
89- .await
90- .unwrap();
91 183
92- user_community::join(&member.id, &community.id, &conn)184+ user_community::join(&member.id, &community.id, Rank::Member, &conn)
93 .await185 .await
94 .unwrap();186 .unwrap();
95 187
96- assert!(188+ assert_eq!(
97- user_community::is_member(&member.id, &community.id, &conn)189+ Some(Rank::Member),
190+ user_community::rank(&member.id, &community.id, &conn)
191+ .await
192+ .unwrap()
193+ );
194+ assert_eq!(
195+ None,
196+ user_community::rank(&owner.id, &community.id, &conn)
98 .await197 .await
99 .unwrap()198 .unwrap()
100 );199 );
@@ -105,16 +204,14 @@ mod tests {
105 let db = test::get_database().await;204 let db = test::get_database().await;
106 let conn = database::connect(&db).await.unwrap();205 let conn = database::connect(&db).await.unwrap();
107 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();206 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();
108- let community = community::create("The Community", &owner.id, &conn)207+ let community = community::create("The Community", &conn).await.unwrap();
109- .await
110- .unwrap();
111 208
112- user_community::join(&owner.id, &community.id, &conn)209+ user_community::join(&owner.id, &community.id, Rank::Owner, &conn)
113 .await210 .await
114 .unwrap();211 .unwrap();
115 212
116 assert!(213 assert!(
117- user_community::join(&owner.id, &community.id, &conn)214+ user_community::join(&owner.id, &community.id, Rank::Member, &conn)
118 .await215 .await
119 .is_err()216 .is_err()
120 );217 );
@@ -125,10 +222,8 @@ mod tests {
125 let db = test::get_database().await;222 let db = test::get_database().await;
126 let conn = database::connect(&db).await.unwrap();223 let conn = database::connect(&db).await.unwrap();
127 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();224 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();
128- let community = community::create("The Community", &owner.id, &conn)225+ let community = community::create("The Community", &conn).await.unwrap();
129- .await226+ user_community::join(&owner.id, &community.id, Rank::Owner, &conn)
130- .unwrap();
131- user_community::join(&owner.id, &community.id, &conn)
132 .await227 .await
133 .unwrap();228 .unwrap();
134 229
@@ -136,54 +231,79 @@ mod tests {
136 .await231 .await
137 .unwrap();232 .unwrap();
138 233
139- assert!(234+ assert_eq!(
140- !user_community::is_member(&owner.id, &community.id, &conn)235+ None,
236+ user_community::rank(&owner.id, &community.id, &conn)
141 .await237 .await
142 .unwrap()238 .unwrap()
143 );239 );
144 }240 }
145 241
146 #[tokio::test]242 #[tokio::test]
147- async fn leave_again() {243+ async fn members() {
148 let db = test::get_database().await;244 let db = test::get_database().await;
149 let conn = database::connect(&db).await.unwrap();245 let conn = database::connect(&db).await.unwrap();
150- let owner = user::create("Tahinli", "hash", &conn).await.unwrap();246+ let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap();
151- let community = community::create("The Community", &owner.id, &conn)247+ let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap();
152- .await248+ let _user_3 = user::create("Third Tahinli", "hash", &conn).await.unwrap();
153- .unwrap();249+ let community = community::create("The Community", &conn).await.unwrap();
154- user_community::join(&owner.id, &community.id, &conn)250+
251+ user_community::join(&user_1.id, &community.id, Rank::Owner, &conn)
155 .await252 .await
156 .unwrap();253 .unwrap();
157- user_community::leave(&owner.id, &community.id, &conn)254+ user_community::join(&user_2.id, &community.id, Rank::Member, &conn)
158 .await255 .await
159 .unwrap();256 .unwrap();
160 257
161- let leave = user_community::leave(&owner.id, &community.id, &conn).await;258+ let members = user_community::members(&community.id, &conn).await.unwrap();
162 259
163- assert!(matches!(leave, Err(Error::Common(CommonError::NotFound))));260+ assert_eq!(
261+ vec![
262+ Member {
263+ user: user_1,
264+ rank: Rank::Owner
265+ },
266+ Member {
267+ user: user_2,
268+ rank: Rank::Member
269+ },
270+ ],
271+ members
272+ );
164 }273 }
165 274
166 #[tokio::test]275 #[tokio::test]
167- async fn members() {276+ async fn ban_and_unban() {
168 let db = test::get_database().await;277 let db = test::get_database().await;
169 let conn = database::connect(&db).await.unwrap();278 let conn = database::connect(&db).await.unwrap();
170- let user_1 = user::create("Tahinli", "hash", &conn).await.unwrap();279+ let member = user::create("Not Tahinli", "hash", &conn).await.unwrap();
171- let user_2 = user::create("Not Tahinli", "hash", &conn).await.unwrap();280+ let community = community::create("The Community", &conn).await.unwrap();
172- let _user_3 = user::create("Third Tahinli", "hash", &conn).await.unwrap();281+ user_community::join(&member.id, &community.id, Rank::Member, &conn)
173- let community = community::create("The Community", &user_1.id, &conn)
174 .await282 .await
175 .unwrap();283 .unwrap();
176 284
177- user_community::join(&user_1.id, &community.id, &conn)285+ user_community::ban(&member.id, &community.id, None, &conn)
178 .await286 .await
179 .unwrap();287 .unwrap();
180- user_community::join(&user_2.id, &community.id, &conn)288+ let banned = user_community::is_banned(&member.id, &community.id, &conn)
289+ .await
290+ .unwrap();
291+ user_community::unban(&member.id, &community.id, &conn)
181 .await292 .await
182 .unwrap();293 .unwrap();
183 294
184- let members = user_community::members(&community.id, &conn).await.unwrap();295+ assert!(banned);
185-296+ assert!(
186- assert_eq!(vec![user_1, user_2], members);297+ !user_community::is_banned(&member.id, &community.id, &conn)
298+ .await
299+ .unwrap()
300+ );
301+ assert!(
302+ user_community::bans(&community.id, &conn)
303+ .await
304+ .unwrap()
305+ .is_empty()
306+ );
187 }307 }
188 308
189 #[tokio::test]309 #[tokio::test]
@@ -191,17 +311,13 @@ mod tests {
191 let db = test::get_database().await;311 let db = test::get_database().await;
192 let conn = database::connect(&db).await.unwrap();312 let conn = database::connect(&db).await.unwrap();
193 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();313 let owner = user::create("Tahinli", "hash", &conn).await.unwrap();
194- let community_1 = community::create("The Community", &owner.id, &conn)314+ let community_1 = community::create("The Community", &conn).await.unwrap();
195- .await315+ let community_2 = community::create("The Community", &conn).await.unwrap();
196- .unwrap();
197- let community_2 = community::create("The Community", &owner.id, &conn)
198- .await
199- .unwrap();
200 316
201- user_community::join(&owner.id, &community_1.id, &conn)317+ user_community::join(&owner.id, &community_1.id, Rank::Owner, &conn)
202 .await318 .await
203 .unwrap();319 .unwrap();
204- user_community::join(&owner.id, &community_2.id, &conn)320+ user_community::join(&owner.id, &community_2.id, Rank::Owner, &conn)
205 .await321 .await
206 .unwrap();322 .unwrap();
207 323
crates/server/src/voice.rsadded+142 -0
@@ -0,0 +1,142 @@
1+use std::{
2+ collections::HashMap,
3+ sync::{Arc, Mutex},
4+};
5+
6+use bytes::Bytes;
7+use common::voice::{SEQUENCE_LENGTH, encode_relay};
8+use quinn::Connection;
9+
10+struct Participant {
11+ user_id: String,
12+ connection: Connection,
13+}
14+
15+type Rooms = HashMap<String, Vec<Participant>>;
16+
17+#[derive(Clone, Default)]
18+pub struct Voice(Arc<Mutex<Rooms>>);
19+
20+impl Voice {
21+ pub fn join(
22+ &self,
23+ community_id: &str,
24+ user_id: &str,
25+ connection: Connection,
26+ ) -> Option<String> {
27+ let mut rooms = self.0.lock().unwrap();
28+ let previous = leave_locked(&mut rooms, user_id);
29+ rooms
30+ .entry(community_id.to_string())
31+ .or_default()
32+ .push(Participant {
33+ user_id: user_id.to_string(),
34+ connection,
35+ });
36+
37+ previous
38+ }
39+
40+ pub fn leave(&self, user_id: &str) -> Option<String> {
41+ leave_locked(&mut self.0.lock().unwrap(), user_id)
42+ }
43+
44+ pub fn leave_connection(&self, connection_id: usize) -> Option<(String, String)> {
45+ let mut rooms = self.0.lock().unwrap();
46+ let user_id = find(&rooms, connection_id)?.user_id.clone();
47+ let community_id = leave_locked(&mut rooms, &user_id)?;
48+
49+ Some((community_id, user_id))
50+ }
51+
52+ pub fn leave_room(&self, community_id: &str, user_id: &str) -> bool {
53+ let mut rooms = self.0.lock().unwrap();
54+ let Some(room) = rooms.get_mut(community_id) else {
55+ return false;
56+ };
57+ let before = room.len();
58+ room.retain(|participant| participant.user_id != user_id);
59+ let left = room.len() != before;
60+ if room.is_empty() {
61+ rooms.remove(community_id);
62+ }
63+
64+ left
65+ }
66+
67+ pub fn participants(&self, community_id: &str) -> Vec<String> {
68+ self.0
69+ .lock()
70+ .unwrap()
71+ .get(community_id)
72+ .map(|room| {
73+ room.iter()
74+ .map(|participant| participant.user_id.clone())
75+ .collect()
76+ })
77+ .unwrap_or_default()
78+ }
79+
80+ pub fn remove_room(&self, community_id: &str) -> Vec<String> {
81+ self.0
82+ .lock()
83+ .unwrap()
84+ .remove(community_id)
85+ .unwrap_or_default()
86+ .into_iter()
87+ .map(|participant| participant.user_id)
88+ .collect()
89+ }
90+
91+ pub fn relay(&self, connection_id: usize, packet: &[u8]) {
92+ let rooms = self.0.lock().unwrap();
93+ let Some(room) = rooms.values().find(|room| {
94+ room.iter()
95+ .any(|participant| participant.connection.stable_id() == connection_id)
96+ }) else {
97+ return;
98+ };
99+ let Some(sender) = find(&rooms, connection_id) else {
100+ return;
101+ };
102+ let (Some(relay), Some(echo)) = (
103+ encode_relay(&sender.user_id, packet),
104+ encode_relay(&sender.user_id, &packet[..SEQUENCE_LENGTH]),
105+ ) else {
106+ return;
107+ };
108+ let _ = sender.connection.send_datagram(Bytes::from(echo));
109+ let bytes = Bytes::from(relay);
110+
111+ for participant in room
112+ .iter()
113+ .filter(|participant| participant.user_id != sender.user_id)
114+ {
115+ let _ = participant.connection.send_datagram(bytes.clone());
116+ }
117+ }
118+}
119+
120+fn find(rooms: &Rooms, connection_id: usize) -> Option<&Participant> {
121+ rooms
122+ .values()
123+ .flatten()
124+ .find(|participant| participant.connection.stable_id() == connection_id)
125+}
126+
127+fn leave_locked(rooms: &mut Rooms, user_id: &str) -> Option<String> {
128+ let community_id = rooms
129+ .iter()
130+ .find(|(_, room)| {
131+ room.iter()
132+ .any(|participant| participant.user_id == user_id)
133+ })
134+ .map(|(community_id, _)| community_id.clone())?;
135+ let room = rooms.get_mut(&community_id)?;
136+ room.retain(|participant| participant.user_id != user_id);
137+ if room.is_empty() {
138+ rooms.remove(&community_id);
139+ }
140+
141+ Some(community_id)
142+}
docs/screenshots/black.pngadded+0 -0

Binary file changed

docs/screenshots/community.pngadded+0 -0

Binary file changed

docs/screenshots/direct.pngadded+0 -0

Binary file changed