From 76613d28c65abd4336470769580056a555a3e1f9 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 07:25:35 +0300 Subject: [PATCH 01/15] Engine pieces for the home, messages and settings screens The home page lists the latest chats across servers and the profiles page raises an identity's security level, so the engine gains: - Store::recent_chats / History::recent_chats: the newest message of every chat, the most recently active first (one pass over the time index). - identity::improve_level: the hash cash search on every core, in chunks of counters, cancellable, reporting each better level reached; the key and so the unique id stay the same. - privacy.private_messages and privacy.pokes (everyone, friends, nobody): private messages and pokes of everyone else are dropped, next to what privacy.block_mode does for blocked contacts. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/voelin-core/Cargo.toml | 2 + crates/voelin-core/src/history.rs | 14 +++++++ crates/voelin-core/src/identity.rs | 65 ++++++++++++++++++++++++++++++ crates/voelin-core/src/session.rs | 40 +++++++++++++++++- crates/voelin-core/src/settings.rs | 29 +++++++++++++ crates/voelin-store/src/chat.rs | 42 +++++++++++++++++++ docs/architecture.md | 4 +- 8 files changed, 195 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fee7ebc..568c86d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9108,6 +9108,7 @@ dependencies = [ "toml", "tracing", "tsclientlib", + "tsproto", "tsproto-packets", "tsproto-types", "voelin-audio", diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 1888da0..acb58c4 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -47,6 +47,8 @@ voelin-query = { path = "../voelin-query" } voelin-store = { path = "../voelin-store" } voelin-stream = { path = "../voelin-stream" } tsclientlib = { path = "../proto/tsclientlib" } +# The hash cash level, for raising an identity's security level. +tsproto = { path = "../proto/tsproto" } tsproto-packets = { path = "../proto/tsproto-packets" } tsproto-types = { path = "../proto/tsproto-types" } diff --git a/crates/voelin-core/src/history.rs b/crates/voelin-core/src/history.rs index 0543467..7ba035e 100644 --- a/crates/voelin-core/src/history.rs +++ b/crates/voelin-core/src/history.rs @@ -365,6 +365,17 @@ impl History { Ok(rows.into_iter().map(HistoryMessage::from).collect()) } + /// The newest stored message of every chat with the server's unique id, + /// the most recently active chat first, at most `limit` chats (a list + /// of recent chats across servers). + pub async fn recent_chats( + &self, + limit: usize, + ) -> Result, String> { + let rows = self.run(false, move |s| s.recent_chats(Some(limit))).await?; + Ok(rows.into_iter().map(|m| (m.server_uid.clone(), HistoryMessage::from(m))).collect()) + } + /// Delete messages older than `before_ms` (pinned ones stay). pub(crate) fn prune(&self, before_ms: i64) { self.send(Job::Run { @@ -812,6 +823,9 @@ mod tests { ["m49", "n49"] ); assert!(page[0].id > 0); + let recent = history.recent_chats(5).await.unwrap(); + assert_eq!(recent.len(), 1, "one chat"); + assert_eq!((recent[0].0.as_str(), recent[0].1.message.ts_ms), ("srv", 49)); // Kept in memory only: negative ids, not in the file. let kept = history.write_async(true, vec![live("secret", 99)], 5000).await.unwrap(); assert!(kept[0].message.id < 0); diff --git a/crates/voelin-core/src/identity.rs b/crates/voelin-core/src/identity.rs index eea4bbf..97a6e97 100644 --- a/crates/voelin-core/src/identity.rs +++ b/crates/voelin-core/src/identity.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeMap, HashSet}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::{fs, str}; use rusqlite::{Connection, OpenFlags, OptionalExtension}; @@ -195,6 +196,51 @@ pub fn write_export(path: &Path, nickname: &str, identity: &Identity) -> Result< file.write_all(export(nickname, identity).as_bytes()).map_err(|e| IdentityError::read(path, e)) } +/// Raise `identity`'s hash cash security level to at least `target` on +/// every core: the counters after its current one are searched in parallel +/// chunks, and the identity with the first counter found that reaches +/// `target` is returned (the same key, so the same unique id). `progress` +/// hears each better level reached, from the worker threads; setting +/// `cancel` stops the search with `None`. Each level takes about twice as +/// long as the one before; there is no upper limit. +pub fn improve_level( + identity: &Identity, + target: u8, + cancel: &AtomicBool, + progress: impl Fn(u8) + Sync, +) -> Option { + const CHUNK: u64 = 1 << 14; + if identity.level() >= target { + return Some(identity.clone()); + } + let omega = identity.key().to_pub().to_ts(); + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); + let next = AtomicU64::new(identity.max_counter().max(identity.counter())); + let found = AtomicU64::new(u64::MAX); + let best = AtomicU8::new(identity.level()); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + while !cancel.load(Ordering::Relaxed) && found.load(Ordering::Relaxed) == u64::MAX { + let start = next.fetch_add(CHUNK, Ordering::Relaxed); + for counter in start..start.saturating_add(CHUNK) { + let level = tsproto::algorithms::get_hash_cash_level(&omega, counter); + if level > best.fetch_max(level, Ordering::Relaxed) { + progress(level); + } + if level >= target { + found.fetch_min(counter, Ordering::Relaxed); + break; + } + } + } + }); + } + }); + let counter = found.into_inner(); + (counter != u64::MAX).then(|| Identity::new(identity.key().clone(), counter)) +} + /// Does `path` start with the SQLite file header? fn is_sqlite(path: &Path) -> Result { let mut head = [0u8; 16]; @@ -439,6 +485,25 @@ mod tests { Identity::create() } + #[test] + fn improve_level_keeps_the_key() { + let identity = synthetic(); + let levels = std::sync::Mutex::new(Vec::new()); + let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| { + levels.lock().unwrap().push(l); + }) + .unwrap(); + assert!(better.level() >= 13); + assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid()); + assert!(better.counter() > identity.counter()); + assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13)); + // Cancelled: nothing. + assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none()); + // Already there: the same identity. + let same = improve_level(&better, 8, &AtomicBool::new(false), |_| {}).unwrap(); + assert_eq!(same.counter(), better.counter()); + } + fn temp_dir(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("voelin-identity-{name}-{}", std::process::id())); diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 87d0d52..68911b9 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -30,7 +30,8 @@ use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; use crate::settings::{ - BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, PRIVACY_BLOCK_MODE, SharedSettings, + Allowed, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, Key, PRIVACY_BLOCK_MODE, PRIVACY_POKES, + PRIVACY_PRIVATE_MESSAGES, SharedSettings, }; use crate::stream::{ LayerSpec, OwnStreamEvent, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInfo, @@ -49,6 +50,26 @@ fn max_cache_bytes(settings: &SharedSettings) -> u64 { settings.current().get(&CACHE_MAX_MB).saturating_mul(1024 * 1024) } +/// Whether a privacy setting lets someone with this relation (`None`: no +/// unique id known) reach us. +fn allows(setting: Allowed, relation: Option) -> bool { + match setting { + Allowed::Everyone => true, + Allowed::Friends => relation == Some(Relation::Friend), + Allowed::Nobody => false, + } +} + +#[cfg(test)] +#[test] +fn privacy_settings() { + assert!(allows(Allowed::Everyone, None)); + assert!(allows(Allowed::Friends, Some(Relation::Friend))); + assert!(!allows(Allowed::Friends, Some(Relation::Neutral))); + assert!(!allows(Allowed::Friends, None)); + assert!(!allows(Allowed::Nobody, Some(Relation::Friend))); +} + pub(crate) struct SessionHandle { tx: mpsc::UnboundedSender, } @@ -869,6 +890,12 @@ impl Session { self.settings.current().get(&PRIVACY_BLOCK_MODE) } + /// Whether `privacy.private_messages` or `privacy.pokes` (`key`) lets + /// the person with this unique id reach us. + fn allowed(&self, key: &'static Key, uid: Option<&str>) -> bool { + allows(self.settings.current().get(key), uid.map(|u| self.contacts.relation(u))) + } + fn stream_input(&self, input: StreamInput) { match &self.streams { Some(s) => s.send(input), @@ -1339,6 +1366,10 @@ impl Session { debug!(?from_uid, "poke of a blocked contact hidden"); return; } + if !self.allowed(&PRIVACY_POKES, from_uid.as_deref()) { + debug!(?from_uid, "poke dropped (privacy.pokes)"); + return; + } let session = self.id; self.emit(Event::Poke { session, from, from_uid, from_name, message, blocked }); } @@ -1540,6 +1571,13 @@ impl Session { debug!(author = ?msg.author_uid, "private message of a blocked contact hidden"); return; } + if matches!(msg.target, ChatTarget::Private(_)) + && msg.author_id != self.state.own_client + && !self.allowed(&PRIVACY_PRIVATE_MESSAGES, msg.author_uid.as_deref()) + { + debug!(author = ?msg.author_uid, "private message dropped (privacy.private_messages)"); + return; + } if let Some(ctx) = self.chat_ctx() { let stored = match &entry { Some(entry) => history::gateway_message(&ctx.server_uid, entry), diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index e59177a..7accc11 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1141,6 +1141,33 @@ pub static PRIVACY_BLOCK_MODE: Key = Key::new( BlockMode::default, ); +/// Who may reach us with private messages or pokes; the others' are +/// dropped (neither reported nor stored). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Allowed { + /// Anyone (blocked contacts still follow `privacy.block_mode`). + #[default] + Everyone, + /// Contacts marked friend. + Friends, + Nobody, +} + +pub static PRIVACY_PRIVATE_MESSAGES: Key = Key::new( + "privacy.private_messages", + Kind::Choice(&["everyone", "friends", "nobody"]), + "Who may send us private messages: everyone, friends or nobody.", + Allowed::default, +); + +pub static PRIVACY_POKES: Key = Key::new( + "privacy.pokes", + Kind::Choice(&["everyone", "friends", "nobody"]), + "Who may poke us: everyone, friends or nobody.", + Allowed::default, +); + /// What an audio source of our stream captures, as stored; see /// [`AudioSourceSetting`]. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -1290,6 +1317,8 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> { &CACHE_FETCH_IMAGES, &FILES_PROGRESS_MS, &PRIVACY_BLOCK_MODE, + &PRIVACY_PRIVATE_MESSAGES, + &PRIVACY_POKES, #[cfg(feature = "media")] &STUDIO_SCENES, #[cfg(feature = "media")] diff --git a/crates/voelin-store/src/chat.rs b/crates/voelin-store/src/chat.rs index c7e6b01..3b1353b 100644 --- a/crates/voelin-store/src/chat.rs +++ b/crates/voelin-store/src/chat.rs @@ -529,6 +529,24 @@ impl Store { Ok(rows) } + /// The newest message of every chat (of every server), the most + /// recently active chat first, at most `limit` chats (`None`: all). + pub fn recent_chats(&self, limit: Option) -> Result> { + // SQLite takes the bare columns from the row with the MAX. + // ponytail: one pass over the time index; keep a table of each + // chat's last message if histories grow into the millions. + let sql = format!( + "SELECT {COLUMNS}, MAX(ts_ms) FROM messages WHERE server_uid <> '' + GROUP BY server_uid, target ORDER BY ts_ms DESC, id DESC LIMIT ?1" + ); + let limit = limit.map_or(-1, |l| l as i64); + Ok(self + .db + .prepare_cached(&sql)? + .query_map([limit], message_from_row)? + .collect::>>()?) + } + /// One message by its local id. pub fn message(&self, id: i64) -> Result> { Ok(self @@ -767,6 +785,30 @@ mod tests { rows.iter().map(|m| m.text.as_str()).collect() } + #[test] + fn recent_chats_newest_first() { + let mut store = Store::open_in_memory().unwrap(); + let mut dm = msg(MessageSource::Voice, "b", "hi", 3000); + dm.target = ChatTarget::Private("uid-b".into()); + let mut other = msg(MessageSource::Voice, "c", "elsewhere", 2500); + other.server_uid = "srv2".into(); + store + .write_messages( + &[ + msg(MessageSource::Voice, "a", "old", 1000), + msg(MessageSource::Voice, "a", "newer", 2000), + dm, + other, + ], + 0, + ) + .unwrap(); + let recent = store.recent_chats(None).unwrap(); + assert_eq!(texts(&recent), ["hi", "elsewhere", "newer"]); + assert_eq!(recent[0].target, ChatTarget::Private("uid-b".into())); + assert_eq!(texts(&store.recent_chats(Some(1)).unwrap()), ["hi"]); + } + #[test] fn batch_insert_and_pages() { let mut store = Store::open_in_memory().unwrap(); diff --git a/docs/architecture.md b/docs/architecture.md index 76c8947..983387e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -222,7 +222,9 @@ for Home's friends list, and records sightings in one write per change. A contact's mute and volume apply to their voice in every session. Messages of blocked contacts are flagged (`ChatMessage::blocked`, live and in history); their private messages and pokes are dropped or flagged per -`privacy.block_mode`. `stream.permissions = friends` lets friends watch our +`privacy.block_mode`. `privacy.private_messages` and `privacy.pokes` +(everyone, friends, nobody) drop those of everyone else. +`stream.permissions = friends` lets friends watch our stream without asking and asks for everyone else. ## Streams From c081476de98462a3804203befcaf358967bdbc04 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 11:56:06 +0300 Subject: [PATCH 02/15] Home, friends, direct messages, the bell, search, events and settings pages The screens of design mockups 01, 02, 03 (server sidebar links) and 11 on the existing pattern (Bridge models synced row by row, view models in vm/, callbacks in bind/), mapped onto what TeamSpeak has: - Home: a banner with Voelin and each server, friends online from the sessions' presence, live streams of our servers (our channel, the gateways' directories, clients flagged streaming), the servers with Join, the latest chats across servers (history store), friend activity, quick actions (add, join by address, find friends) and what is happening (gateway events, scheduled streams, server news). The Library lists the Stream Studio's recordings and clips. - Friends: contacts with where they are, message, poke, join, watch, relation, note, volume and mute. - Direct messages: private chats of every server and of the store, pokes among the messages, a clear state when the peer cannot be reached, TS3/TS6 offline messages (list, read, send, delete). - The bell (mentions, pokes, messages, event reminders, friends coming online; a setting per kind, desktop notifications), the Ctrl+K search (servers, channels, people, settings pages; keyboard). - A server's events page (RSVP, attendees, create/edit/delete, scheduled streams) and the Events/Members entries above the tree. - Inline pictures in chat (downloaded into memory up to ui.image_preview_kb, decoded once into the image cache). - Settings: My Account, Profiles (identities: default, rename, delete, export, import from the official clients, security level on every core, identity per bookmark), Appearance, Voice & Video (camera preview with blur, video and stream quality, streaming permissions), Streaming (defaults, simulcast layers, audio sources), Devices, Notifications, Privacy & Safety, Keybinds, Integrations (gateways, gateway administration, encoders) and Advanced (SRTP order, history, cache, every setting as JSON). The top bar's field now opens the search instead of filtering the channel tree; the search finds channels of every server. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-ui/Cargo.toml | 5 +- crates/voelin-ui/src/app.rs | 57 +- crates/voelin-ui/src/bind/mod.rs | 4 + crates/voelin-ui/src/bind/pages.rs | 120 ++ crates/voelin-ui/src/bind/servers.rs | 3 - crates/voelin-ui/src/bind/social.rs | 118 ++ crates/voelin-ui/src/camera.rs | 118 ++ crates/voelin-ui/src/chat.rs | 30 +- crates/voelin-ui/src/events.rs | 328 ++++ crates/voelin-ui/src/home.rs | 331 ++++ crates/voelin-ui/src/images.rs | 15 + crates/voelin-ui/src/lib.rs | 7 + crates/voelin-ui/src/messages.rs | 782 ++++++++++ crates/voelin-ui/src/previews.rs | 162 ++ crates/voelin-ui/src/servers.rs | 36 +- crates/voelin-ui/src/settings.rs | 151 ++ crates/voelin-ui/src/settings_pages.rs | 1383 +++++++++++++++++ crates/voelin-ui/src/social.rs | 1149 ++++++++++++++ crates/voelin-ui/src/video.rs | 11 +- crates/voelin-ui/src/vm/chat.rs | 7 +- crates/voelin-ui/src/vm/mod.rs | 1 + crates/voelin-ui/src/vm/servers.rs | 18 +- crates/voelin-ui/src/vm/social.rs | 233 +++ crates/voelin-ui/ui/app.slint | 115 +- .../voelin-ui/ui/assets/icons/arrow-down.svg | 16 + crates/voelin-ui/ui/assets/icons/arrow-up.svg | 16 + crates/voelin-ui/ui/assets/icons/ban.svg | 16 + .../voelin-ui/ui/assets/icons/bell-ring.svg | 17 + .../ui/assets/icons/calendar-days.svg | 24 + .../ui/assets/icons/calendar-plus.svg | 20 + .../ui/assets/icons/circle-check.svg | 16 + crates/voelin-ui/ui/assets/icons/circle-x.svg | 17 + .../ui/assets/icons/clapperboard.svg | 17 + crates/voelin-ui/ui/assets/icons/cpu.svg | 28 + crates/voelin-ui/ui/assets/icons/film.svg | 22 + .../ui/assets/icons/flask-conical.svg | 16 + crates/voelin-ui/ui/assets/icons/folder.svg | 15 + crates/voelin-ui/ui/assets/icons/gauge.svg | 16 + crates/voelin-ui/ui/assets/icons/id-card.svg | 19 + crates/voelin-ui/ui/assets/icons/inbox.svg | 15 + .../voelin-ui/ui/assets/icons/key-round.svg | 15 + crates/voelin-ui/ui/assets/icons/layers.svg | 15 + crates/voelin-ui/ui/assets/icons/mail.svg | 16 + .../voelin-ui/ui/assets/icons/megaphone.svg | 16 + .../ui/assets/icons/message-square-plus.svg | 16 + crates/voelin-ui/ui/assets/icons/plug.svg | 17 + .../voelin-ui/ui/assets/icons/rotate-ccw.svg | 16 + .../voelin-ui/ui/assets/icons/scroll-text.svg | 17 + crates/voelin-ui/ui/assets/icons/upload.svg | 17 + .../voelin-ui/ui/assets/icons/user-check.svg | 17 + crates/voelin-ui/ui/assets/icons/user-cog.svg | 25 + .../voelin-ui/ui/assets/icons/user-round.svg | 16 + crates/voelin-ui/ui/assets/icons/user-x.svg | 18 + .../ui/assets/icons/wand-sparkles.svg | 21 + crates/voelin-ui/ui/assets/icons/zap.svg | 15 + crates/voelin-ui/ui/bridge.slint | 589 +++++++ crates/voelin-ui/ui/icons.slint | 33 + crates/voelin-ui/ui/nav.slint | 113 +- crates/voelin-ui/ui/screens/chat.slint | 6 +- crates/voelin-ui/ui/screens/dialogs.slint | 13 +- crates/voelin-ui/ui/screens/events.slint | 444 ++++++ crates/voelin-ui/ui/screens/friends.slint | 443 ++++++ crates/voelin-ui/ui/screens/home.slint | 1263 +++++++++++++-- crates/voelin-ui/ui/screens/messages.slint | 679 ++++++++ crates/voelin-ui/ui/screens/overlays.slint | 482 ++++++ .../voelin-ui/ui/screens/settings-pages.slint | 1181 ++++++++++++++ crates/voelin-ui/ui/screens/settings.slint | 1219 +++++++++++---- crates/voelin-ui/ui/shells/desktop.slint | 29 +- crates/voelin-ui/ui/shells/mobile.slint | 13 +- 69 files changed, 11751 insertions(+), 487 deletions(-) create mode 100644 crates/voelin-ui/src/bind/pages.rs create mode 100644 crates/voelin-ui/src/bind/social.rs create mode 100644 crates/voelin-ui/src/camera.rs create mode 100644 crates/voelin-ui/src/events.rs create mode 100644 crates/voelin-ui/src/home.rs create mode 100644 crates/voelin-ui/src/messages.rs create mode 100644 crates/voelin-ui/src/previews.rs create mode 100644 crates/voelin-ui/src/settings_pages.rs create mode 100644 crates/voelin-ui/src/social.rs create mode 100644 crates/voelin-ui/src/vm/social.rs create mode 100644 crates/voelin-ui/ui/assets/icons/arrow-down.svg create mode 100644 crates/voelin-ui/ui/assets/icons/arrow-up.svg create mode 100644 crates/voelin-ui/ui/assets/icons/ban.svg create mode 100644 crates/voelin-ui/ui/assets/icons/bell-ring.svg create mode 100644 crates/voelin-ui/ui/assets/icons/calendar-days.svg create mode 100644 crates/voelin-ui/ui/assets/icons/calendar-plus.svg create mode 100644 crates/voelin-ui/ui/assets/icons/circle-check.svg create mode 100644 crates/voelin-ui/ui/assets/icons/circle-x.svg create mode 100644 crates/voelin-ui/ui/assets/icons/clapperboard.svg create mode 100644 crates/voelin-ui/ui/assets/icons/cpu.svg create mode 100644 crates/voelin-ui/ui/assets/icons/film.svg create mode 100644 crates/voelin-ui/ui/assets/icons/flask-conical.svg create mode 100644 crates/voelin-ui/ui/assets/icons/folder.svg create mode 100644 crates/voelin-ui/ui/assets/icons/gauge.svg create mode 100644 crates/voelin-ui/ui/assets/icons/id-card.svg create mode 100644 crates/voelin-ui/ui/assets/icons/inbox.svg create mode 100644 crates/voelin-ui/ui/assets/icons/key-round.svg create mode 100644 crates/voelin-ui/ui/assets/icons/layers.svg create mode 100644 crates/voelin-ui/ui/assets/icons/mail.svg create mode 100644 crates/voelin-ui/ui/assets/icons/megaphone.svg create mode 100644 crates/voelin-ui/ui/assets/icons/message-square-plus.svg create mode 100644 crates/voelin-ui/ui/assets/icons/plug.svg create mode 100644 crates/voelin-ui/ui/assets/icons/rotate-ccw.svg create mode 100644 crates/voelin-ui/ui/assets/icons/scroll-text.svg create mode 100644 crates/voelin-ui/ui/assets/icons/upload.svg create mode 100644 crates/voelin-ui/ui/assets/icons/user-check.svg create mode 100644 crates/voelin-ui/ui/assets/icons/user-cog.svg create mode 100644 crates/voelin-ui/ui/assets/icons/user-round.svg create mode 100644 crates/voelin-ui/ui/assets/icons/user-x.svg create mode 100644 crates/voelin-ui/ui/assets/icons/wand-sparkles.svg create mode 100644 crates/voelin-ui/ui/assets/icons/zap.svg create mode 100644 crates/voelin-ui/ui/screens/events.slint create mode 100644 crates/voelin-ui/ui/screens/friends.slint create mode 100644 crates/voelin-ui/ui/screens/messages.slint create mode 100644 crates/voelin-ui/ui/screens/overlays.slint create mode 100644 crates/voelin-ui/ui/screens/settings-pages.slint diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index f56c220..9b84489 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -24,6 +24,8 @@ dirs = "6" miniz_oxide = "0.8" png = "0.18" serde = { version = "1", features = ["derive"] } +# Settings and gateway values as JSON (the advanced and integrations pages). +serde_json = "1" tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "time", "sync"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } @@ -57,9 +59,6 @@ voelin-store = { path = "../voelin-store", features = ["keyring"] } slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "renderer-software", "backend-android-activity-06"] } voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] } -[dev-dependencies] -serde_json = "1" - [build-dependencies] slint-build = "1.18" diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index cab0dc7..2c253dc 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -50,6 +50,9 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings { for key in appearance_keys() { prefs.register(key); } + for key in crate::settings::page_keys() { + prefs.register(key); + } let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); @@ -214,6 +217,8 @@ pub(crate) struct SessionView { pub downloads: HashMap, /// The next transfer id. pub next_transfer: u64, + /// What the home, messages and events screens keep of the session. + pub extra: crate::social::SessionExtra, } impl Default for SessionView { @@ -237,6 +242,7 @@ impl Default for SessionView { stream_viewers: HashMap::new(), downloads: HashMap::new(), next_transfer: 1, + extra: Default::default(), } } } @@ -296,6 +302,15 @@ pub(crate) struct Models { pub qualities: Rc>, /// Shown when there is no chat. pub no_chat: Rc>, + /// Home, friends, messages, the bell, the search, events. + pub social: crate::social::SocialModels, + /// Settings pages. + pub layers: Rc>, + pub audio_sources: Rc>, + pub identities: Rc>, + pub gateway_config: Rc>, + pub gateway_perms: Rc>, + pub all_settings: Rc>, } impl Models { @@ -313,6 +328,13 @@ impl Models { topic_messages: Rc::default(), qualities: Rc::default(), no_chat: Rc::default(), + social: crate::social::SocialModels::new(bridge), + layers: Rc::default(), + audio_sources: Rc::default(), + identities: Rc::default(), + gateway_config: Rc::default(), + gateway_perms: Rc::default(), + all_settings: Rc::default(), }; bridge.set_servers(ModelRc::from(models.servers.clone())); bridge.set_tree(ModelRc::from(models.tree.clone())); @@ -326,6 +348,12 @@ impl Models { bridge.set_topic_messages(ModelRc::from(models.topic_messages.clone())); bridge.set_viewer_qualities(ModelRc::from(models.qualities.clone())); bridge.set_messages(ModelRc::from(models.no_chat.clone())); + bridge.set_layers(ModelRc::from(models.layers.clone())); + bridge.set_audio_sources(ModelRc::from(models.audio_sources.clone())); + bridge.set_identities(ModelRc::from(models.identities.clone())); + bridge.set_gateway_config(ModelRc::from(models.gateway_config.clone())); + bridge.set_gateway_perms(ModelRc::from(models.gateway_perms.clone())); + bridge.set_all_settings(ModelRc::from(models.all_settings.clone())); models } } @@ -341,8 +369,6 @@ pub(crate) struct App { pub sessions: HashMap, pub models: Models, pub status: String, - /// The top bar's search: filters the channel tree. - pub tree_filter: String, /// The members panel's search. pub member_filter: String, /// The topics drawer's search. @@ -389,6 +415,10 @@ pub(crate) struct App { /// Files being uploaded to a channel from the composer: session, /// channel and name, so the link can be posted when they are up. pub uploads: HashMap, + /// Home, friends, messages, the bell and the search. + pub social: crate::social::Social, + /// The settings pages of the new design. + pub pages: crate::settings_pages::Pages, } thread_local! { @@ -556,7 +586,6 @@ pub fn run(options: RunOptions) -> Result<()> { sessions: HashMap::new(), models, status: String::new(), - tree_filter: String::new(), member_filter: String::new(), topic_filter: String::new(), voice_view: false, @@ -583,14 +612,23 @@ pub fn run(options: RunOptions) -> Result<()> { open_client_pending: switches.open_client, notices_loaded: false, uploads: HashMap::new(), + social: Default::default(), + pages: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); crate::bind::wire(&ui); with_app(|app| { app.apply_appearance(); + app.load_default_identity(); + app.apply_srtp(); app.refresh_all(); app.refresh_settings_flags(); app.refresh_crash_notice(); + app.load_recent_chats(); + app.refresh_people(); + app.refresh_home(); + app.refresh_notices(); + app.refresh_pages(); if app.demo { app.start_demo(); } @@ -714,9 +752,16 @@ impl App { } else if appearance_keys().iter().any(|k| k.name() == key) { self.apply_appearance(); } + self.page_setting_changed(key); } pub(crate) fn handle_event(&mut self, event: Event) { + let touched = self.social_event(&event); + self.dispatch(event); + self.social_refresh(touched); + } + + fn dispatch(&mut self, event: Event) { match event { Event::State { session, state } => { let id = session as i64; @@ -813,7 +858,10 @@ impl App { Event::ChatHistory { session, target, messages, source, complete } => { self.history_batch(session as i64, &target, messages, source, complete); } - Event::Gateway { session, update } => self.gateway_update(session as i64, update), + Event::Gateway { session, update } => { + self.gateway_extra(session as i64, &update); + self.gateway_update(session as i64, update); + } Event::Groups { session, server_groups, .. } => { let view = self.sessions.entry(session as i64).or_default(); view.server_groups = (*server_groups).clone(); @@ -859,6 +907,7 @@ impl App { /// Once a second. fn tick(&mut self) { self.tick_streams(); + self.tick_pages(); if self.audio_dirty { self.save_audio(); } diff --git a/crates/voelin-ui/src/bind/mod.rs b/crates/voelin-ui/src/bind/mod.rs index 8537548..2ea8d57 100644 --- a/crates/voelin-ui/src/bind/mod.rs +++ b/crates/voelin-ui/src/bind/mod.rs @@ -3,8 +3,10 @@ mod chat; mod emoji; +mod pages; mod servers; mod settings; +mod social; mod streams; use crate::app::MainWindow; @@ -16,4 +18,6 @@ pub(crate) fn wire(ui: &MainWindow) { streams::wire(ui); settings::wire(ui); emoji::wire(ui); + social::wire(ui); + pages::wire(ui); } diff --git a/crates/voelin-ui/src/bind/pages.rs b/crates/voelin-ui/src/bind/pages.rs new file mode 100644 index 0000000..db8783f --- /dev/null +++ b/crates/voelin-ui/src/bind/pages.rs @@ -0,0 +1,120 @@ +//! The settings pages of the new design (settings_pages.rs). + +use slint::ComponentHandle; + +use crate::app::{Bridge, MainWindow, with_app}; + +pub(super) fn wire(ui: &MainWindow) { + let bridge = ui.global::(); + bridge.on_settings_section(|section| { + with_app(|app| app.settings_section(section)); + }); + // Profiles. + bridge.on_identity_action(|id, action| { + with_app(|app| app.identity_action(id, &action)); + }); + bridge.on_rename_identity(|id, name| { + with_app(|app| app.rename_identity(id, &name)); + }); + bridge.on_improve_target(|id, target| { + with_app(|app| app.improve_identity(id, target)); + }); + bridge.on_find_identities(|| { + with_app(|app| app.find_identities()); + }); + bridge.on_pick_found(|index, on| { + with_app(|app| app.pick_found(index, on)); + }); + bridge.on_import_identities(|| { + with_app(|app| app.import_identities()); + }); + bridge.on_bookmark_identity(|bookmark, index| { + with_app(|app| app.bookmark_identity(bookmark, index)); + }); + // Voice & Video. + bridge.on_video_changed(|form| { + with_app(|app| app.video_changed(&form)); + }); + bridge.on_toggle_camera_preview(|| { + with_app(|app| app.toggle_camera_preview()); + }); + bridge.on_test_sound(|| { + with_app(|app| app.test_sound()); + }); + // Streaming. + bridge.on_streaming_changed(|form| { + with_app(|app| app.streaming_changed(&form)); + }); + bridge.on_layer_changed(|index, item| { + with_app(|app| app.layer_changed(index, &item)); + }); + bridge.on_add_layer(|| { + with_app(|app| app.add_layer()); + }); + bridge.on_remove_layer(|index| { + with_app(|app| app.remove_layer(index)); + }); + bridge.on_audio_source_changed(|index, item| { + with_app(|app| app.audio_source_changed(index, &item)); + }); + bridge.on_add_audio_source(|kind, name| { + with_app(|app| app.add_audio_source(&kind, &name)); + }); + bridge.on_remove_audio_source(|index| { + with_app(|app| app.remove_audio_source(index)); + }); + // Notifications, privacy. + bridge.on_notify_changed(|form| { + with_app(|app| app.notify_changed(&form)); + }); + bridge.on_test_notification(|| { + with_app(|app| app.test_notification()); + }); + bridge.on_privacy_changed(|form| { + with_app(|app| app.privacy_changed(&form)); + }); + // Integrations. + bridge.on_gateway_admin(|session| { + with_app(|app| app.gateway_admin(session)); + }); + bridge.on_config_set(|key, value| { + with_app(|app| app.config_set(&key, &value)); + }); + bridge.on_config_reset(|key| { + with_app(|app| app.config_reset(&key)); + }); + bridge.on_config_reload(|| { + with_app(|app| app.config_reload()); + }); + bridge.on_perm_set(|action, everyone, server, channel| { + with_app(|app| app.perm_set(&action, everyone, &server, &channel)); + }); + bridge.on_perm_reset(|action| { + with_app(|app| app.perm_reset(&action)); + }); + bridge.on_refresh_encoders(|| { + with_app(|app| app.refresh_encoders()); + }); + // Advanced. + bridge.on_advanced_changed(|form| { + with_app(|app| app.advanced_changed(&form)); + }); + bridge.on_srtp_move(|index, by| { + with_app(|app| app.srtp_move(index, by)); + }); + bridge.on_srtp_toggle(|name| { + with_app(|app| app.srtp_toggle(&name)); + }); + bridge.on_setting_set(|key, value| { + with_app(|app| app.setting_set(&key, &value)).unwrap_or_default().into() + }); + bridge.on_setting_reset(|key| { + with_app(|app| app.setting_reset(&key)); + }); + bridge.on_search_settings(|text| { + with_app(|app| app.search_settings(text.to_string())); + }); + bridge.on_open_logs(|| { + with_app(|app| app.open_logs()); + }); +} diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index a5100ce..9680b1d 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -11,9 +11,6 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_select_server(|id| { with_app(|app| app.select_server(id as i64)); }); - bridge.on_search(|text| { - with_app(|app| app.search(text.to_string())); - }); bridge.on_search_members(|text| { with_app(|app| app.search_members(text.to_string())); }); diff --git a/crates/voelin-ui/src/bind/social.rs b/crates/voelin-ui/src/bind/social.rs new file mode 100644 index 0000000..343c443 --- /dev/null +++ b/crates/voelin-ui/src/bind/social.rs @@ -0,0 +1,118 @@ +//! Home, friends, direct messages, the bell, the search, a server's events +//! and pictures in chat. + +use slint::ComponentHandle; + +use crate::app::{Bridge, MainWindow, with_app}; + +pub(super) fn wire(ui: &MainWindow) { + let bridge = ui.global::(); + // Home. + bridge.on_open_conversation(|key| { + with_app(|app| app.open_conversation(key)); + }); + bridge.on_watch_live(|session, id| { + with_app(|app| app.watch_live(i64::from(session), &id)); + }); + bridge.on_open_happening(|index| { + with_app(|app| app.open_happening(index)); + }); + bridge.on_open_recording(|path| { + with_app(|app| app.open_recording(&path)); + }); + bridge.on_open_recordings_folder(|| { + with_app(|app| app.open_recordings_folder()); + }); + bridge.on_connect_server(|id| { + with_app(|app| app.connect_server(i64::from(id))); + }); + + // Friends. + bridge.on_friends_tab(|tab| { + with_app(|app| app.friends_tab(tab)); + }); + bridge.on_search_contacts(|text| { + with_app(|app| app.search_contacts(text.to_string())); + }); + bridge.on_select_contact(|uid| { + with_app(|app| app.select_contact(uid.to_string())); + }); + bridge.on_contact_action(|uid, action| { + with_app(|app| app.contact_action(&uid, &action)); + }); + bridge.on_contact_note(|uid, note| { + with_app(|app| app.contact_note(&uid, note.to_string())); + }); + bridge.on_contact_volume(|uid, percent| { + with_app(|app| app.contact_volume(&uid, percent)); + }); + + // Direct messages. + bridge.on_dm_tab(|tab| { + with_app(|app| app.dm_tab(tab)); + }); + bridge.on_search_conversations(|text| { + with_app(|app| app.search_conversations(text.to_string())); + }); + bridge.on_dm_action(|action| { + with_app(|app| app.dm_action(&action)); + }); + bridge.on_dm_volume(|percent| { + with_app(|app| app.dm_volume(percent)); + }); + bridge.on_send_offline(|form| { + with_app(|app| app.send_offline(form)); + }); + + // The bell. + bridge.on_open_notice(|key| { + with_app(|app| app.open_notice(key)); + }); + bridge.on_mark_notices_read(|| { + with_app(|app| app.mark_notices_read()); + }); + bridge.on_clear_notices(|| { + with_app(|app| app.clear_notices()); + }); + + // The search: the top bar's field used to filter the channel tree; + // it now opens the search (Ctrl+K), whose results are everywhere. + bridge.on_search(|text| { + with_app(|app| app.search(text.to_string())); + }); + bridge.on_search_activate(|index| { + with_app(|app| app.search_activate(index)); + }); + + // Events. + bridge.on_open_events(|| { + with_app(|app| app.open_events()); + }); + bridge.on_rsvp(|id, status| { + with_app(|app| app.rsvp(id, &status)); + }); + bridge.on_toggle_event(|id| { + with_app(|app| app.toggle_event(id)); + }); + bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default()); + bridge.on_save_event(|form| with_app(|app| app.save_event(&form)).unwrap_or_default().into()); + bridge.on_delete_event(|id| { + with_app(|app| app.delete_event(id)); + }); + bridge.on_watch_event(|id| { + with_app(|app| app.watch_event(id)); + }); + + // Pictures in chat. + bridge.on_open_preview(|key, index| { + with_app(|app| app.open_preview(key, index)).unwrap_or_default() + }); + + // Opening the messages or the Library loads what they list. + bridge.on_open_messages(|| { + with_app(|app| app.load_recent_chats()); + }); + bridge.on_open_library(|| { + with_app(|app| app.load_library()); + }); +} diff --git a/crates/voelin-ui/src/camera.rs b/crates/voelin-ui/src/camera.rs new file mode 100644 index 0000000..eabb17c --- /dev/null +++ b/crates/voelin-ui/src/camera.rs @@ -0,0 +1,118 @@ +//! The camera preview of the Voice & Video settings (the Stream Studio's +//! camera capture, with its background blur), and the speakers' test tone. + +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use slint::{Image, Rgba8Pixel, SharedPixelBuffer}; +use tokio::sync::oneshot; +use voelin_core::media::voelin_media::convert; +use voelin_core::studio::camera::{self, Capture}; +use voelin_core::studio::compose::Feed; +use voelin_core::studio::scene::Background; + +use crate::app::with_app; + +/// The cameras as (id, name): the devices, then the test pattern. +pub(crate) fn list() -> Vec<(String, String)> { + camera::list().into_iter().map(|c| (c.id, c.name)).collect() +} + +/// A running preview; the camera stops when it is dropped. +pub(crate) struct Preview { + feed: Arc, + status: Arc>, + mirror: bool, + _stop: oneshot::Sender<()>, + _timer: slint::Timer, +} + +impl Preview { + /// Open `device` (empty: the first camera) at `size` if it has it. + pub fn start( + runtime: &tokio::runtime::Handle, + device: &str, + size: Option<(u32, u32)>, + blur: bool, + mirror: bool, + ) -> Self { + let feed = Arc::new(Feed::new()); + let status = Arc::new(Mutex::new(String::new())); + let (stop, stopped) = oneshot::channel::<()>(); + let background = if blur { Background::Blur { strength: 0.04 } } else { Background::Keep }; + let (device, task_feed, task_status) = (device.to_owned(), feed.clone(), status.clone()); + runtime.spawn(async move { + match Capture::start(&device, size, 30, task_feed, background).await { + Ok(capture) => { + // Runs until the preview is dropped. + let _ = stopped.await; + drop(capture); + } + Err(e) => { + *task_status.lock().unwrap_or_else(PoisonError::into_inner) = + format!("The camera does not start: {e}"); + } + } + }); + let timer = slint::Timer::default(); + timer.start(slint::TimerMode::Repeated, Duration::from_millis(66), || { + with_app(|app| app.camera_frame()); + }); + Self { feed, status, mirror, _stop: stop, _timer: timer } + } + + /// The newest picture since the last call. + pub fn take_picture(&self) -> Option { + let frame = self.feed.take()?; + let mut buffer = SharedPixelBuffer::::new(frame.width, frame.height); + let stride = frame.width as usize * 4; + convert::to_rgba(&frame, buffer.make_mut_bytes(), stride).ok()?; + if self.mirror { + for row in buffer.make_mut_slice().chunks_mut(frame.width as usize) { + row.reverse(); + } + } + Some(Image::from_rgba8(buffer)) + } + + /// What to show while there is no picture. + pub fn status(&self) -> String { + let status = self.status.lock().unwrap_or_else(PoisonError::into_inner).clone(); + if !status.is_empty() { + return status; + } + match self.feed.error() { + Some(e) => e, + None if self.feed.delivered() == 0 => "Starting the camera…".into(), + None => String::new(), + } + } +} + +/// Play a short two-tone chime on `device` (the system default for +/// `None`) at `volume` (linear). Blocks while it plays. +pub(crate) fn play_tone(device: Option<&str>, volume: f32) -> Result<(), String> { + let mut out = voelin_audio::device::Playback::open(device, 300).map_err(|e| e.to_string())?; + let rate = out.rate as f32; + let channels = out.channels.max(1); + let samples: Vec = (0..(rate * 0.7) as usize) + .flat_map(|i| { + let t = i as f32 / rate; + let freq = if t < 0.35 { 660.0 } else { 880.0 }; + // Fade in and out of each note. + let local = t % 0.35; + let envelope = (local / 0.02).min(1.0) * ((0.35 - local) / 0.05).min(1.0); + let v = (t * freq * std::f32::consts::TAU).sin() * 0.3 * envelope * volume.min(2.0); + std::iter::repeat_n(v, channels) + }) + .collect(); + let mut written = 0; + while written < samples.len() { + written += out.write(&samples[written..]); + std::thread::sleep(Duration::from_millis(20)); + } + while out.queued() > 0 { + std::thread::sleep(Duration::from_millis(20)); + } + Ok(()) +} diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index b275dc8..a79294f 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -96,6 +96,9 @@ impl App { view.tabs[index].unread = 0; view.tabs[index].topic = None; } + if let Some(id) = self.current { + self.fetch_previews(id); + } self.refresh_chat(); self.refresh_servers(); } @@ -213,6 +216,7 @@ impl App { tab.unread += fresh; } if current { + self.fetch_previews(id); self.refresh_chat(); } if fresh > 0 && !shown { @@ -241,7 +245,7 @@ impl App { || view.gateway_has(feature::REACTIONS) || view.gateway_has(feature::TOPICS); let mut previous: Option = None; - let mut lines = Vec::with_capacity(messages.len()); + let mut lines: Vec<(i64, ChatLine)> = Vec::with_capacity(messages.len()); for m in messages { let avatar = m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid)); @@ -252,6 +256,14 @@ impl App { .and_then(|t| tab.topics.iter().find(|i| i.id == t)) .map(|t| t.title.clone()) .unwrap_or_default(); + let previews = m + .message + .message + .file_refs() + .iter() + .enumerate() + .filter_map(|(i, f)| crate::previews::image_of(view, f).map(|image| (i, image))) + .collect(); let ctx = LineCtx { key: m.key, avatar: vm::avatar::image(avatar), @@ -259,11 +271,20 @@ impl App { marked: tab.marked == Some(m.message.id), topic, downloads: self.downloads_of(view, m.key), + previews, }; - lines.push(vm::chat::history_line(&m.message, previous.as_ref(), &ctx)); + lines.push(( + m.message.message.ts_ms, + vm::chat::history_line(&m.message, previous.as_ref(), &ctx), + )); previous = Some(Previous::of(&m.message.message)); } - lines + // Pokes of a private chat's peer show among its messages. + if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.current) { + lines.extend(self.poke_lines(session, uid)); + lines.sort_by_key(|(ts, _)| *ts); + } + lines.into_iter().map(|(_, line)| line).collect() } /// The file cards of a message that has downloads running. @@ -694,6 +715,9 @@ impl App { } return; } + if self.preview_progress(id, transfer, &state) { + return; + } let done = matches!(state, TransferState::Done { .. }); let view = self.sessions.entry(id).or_default(); let Some(entry) = view.downloads.get_mut(&transfer) else { return }; diff --git a/crates/voelin-ui/src/events.rs b/crates/voelin-ui/src/events.rs new file mode 100644 index 0000000..db634d2 --- /dev/null +++ b/crates/voelin-ui/src/events.rs @@ -0,0 +1,328 @@ +//! What a server's gateway tells besides chat: its events (the events +//! page, RSVP, reminders), the stream directory and the activity feed (the +//! home page), our permissions there, its configuration (gateway +//! administration). The pins, reactions and topics are in `chat.rs`. + +use slint::{ComponentHandle, SharedString}; +use voelin_core::{Command, GatewayRequest, GatewayUpdate}; +use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature}; + +use crate::app::{App, Bridge, EventForm, EventItem}; +use crate::social::{NoticeKind, NoticeTarget, now_ms}; +use crate::vm; +use crate::vm::social::{date_block, event_when, format_local, parse_local, soon}; + +impl App { + /// A request to a session's gateway (not for the sample sessions). + pub(crate) fn gateway_to(&self, session: i64, request: GatewayRequest) { + if !self.demo_ui { + self.engine.send(Command::Gateway { session: session as u64, request }); + } + } + + /// Keep what a gateway update tells these screens (before the chat + /// handles its part). + pub(crate) fn gateway_extra(&mut self, id: i64, update: &GatewayUpdate) { + use GatewayUpdate as U; + let mut ask: Vec = Vec::new(); + let mut remind = None; + let extra = &mut self.sessions.entry(id).or_default().extra; + match update { + U::Connected { uid, capabilities, .. } => { + extra.gateway_uid = Some(uid.clone()); + let has = |f: &str| capabilities.iter().any(|c| c == f); + ask.push(GatewayRequest::Permissions { channel: None }); + if has(feature::EVENTS) { + ask.push(GatewayRequest::Events { query: EventQuery::default() }); + } + if has(feature::STREAMS) { + ask.push(GatewayRequest::Streams); + } + if has(feature::ACTIVITY) { + ask.push(GatewayRequest::Activity { before: None, limit: Some(30) }); + } + } + U::Disconnected { .. } => { + extra.directory.clear(); + extra.events.clear(); + extra.events_loaded = false; + extra.activity.clear(); + extra.actions.clear(); + extra.config.clear(); + extra.perms.clear(); + } + U::Permissions { channel: None, actions } => extra.actions = actions.clone(), + U::Events { events } => { + extra.events = events.clone(); + extra.events.sort_by_key(|e| e.spec.start_ms); + extra.events_loaded = true; + } + U::Event { event } => { + match extra.events.iter().position(|e| e.id == event.id) { + Some(i) => extra.events[i] = event.clone(), + None => extra.events.push(event.clone()), + } + extra.events.sort_by_key(|e| e.spec.start_ms); + } + U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event), + U::EventReminder { event, starts_in_ms } => { + remind = Some((event.clone(), *starts_in_ms)) + } + U::Streams { streams } => extra.directory = streams.clone(), + U::StreamStarted { stream } + | U::StreamUpdated { stream } + | U::StreamRegistered { stream } => { + extra.directory.retain(|e| e.id != stream.id); + extra.directory.push(stream.clone()); + } + U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream), + U::Activity { entries, .. } => extra.activity = entries.clone(), + U::ActivityAdded { entry } => { + extra.activity.insert(0, entry.clone()); + extra.activity.truncate(100); + } + U::Config { entries } => extra.config = entries.clone(), + U::ConfigValue { entry } => { + match extra.config.iter().position(|e| e.key == entry.key) { + Some(i) => extra.config[i] = entry.clone(), + None => extra.config.push(entry.clone()), + } + } + U::PermRules { rules } => extra.perms = rules.clone(), + _ => return, + } + for request in ask { + self.gateway_to(id, request); + } + if let Some((event, starts_in_ms)) = remind { + let minutes = starts_in_ms / 60_000; + let title = if minutes <= 0 { + format!("{} starts now", event.spec.title) + } else { + format!("{} starts in {minutes} min", event.spec.title) + }; + let body = format!("on {}", self.server_name(id)); + self.notify( + NoticeKind::Event, + title, + body, + NoticeTarget::Event(id, event.id), + event.creator.name.clone(), + Some(event.creator.uid.clone()), + ); + } + self.refresh_home(); + self.refresh_events(); + self.refresh_gateways(); + } + + /// The events page of the current server was opened. + pub(crate) fn open_events(&mut self) { + let Some(id) = self.current else { return }; + let loaded = self.sessions.get(&id).is_some_and(|v| v.extra.events_loaded); + if !loaded { + self.gateway_to(id, GatewayRequest::Events { query: EventQuery::default() }); + } + self.refresh_events(); + } + + /// Channels an event can be in: server-wide first. + fn event_channels(&self) -> Vec<(Option, String)> { + let mut out = vec![(None, "Server-wide".to_owned())]; + if let Some(view) = self.view() { + out.extend( + view.presence.channels.values().map(|c| (Some(c.id), format!("#{}", c.name))), + ); + } + out + } + + pub(crate) fn refresh_events(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let view = self.view(); + let has = view.is_some_and(|v| v.gateway_has(feature::EVENTS)); + bridge.set_has_events(has); + let extra = view.map(|v| &v.extra); + let moderate = extra.is_some_and(|e| e.actions.contains(&Action::Moderate)); + bridge.set_can_create_events( + has && extra + .is_some_and(|e| e.actions.is_empty() || e.actions.contains(&Action::CreateEvent)), + ); + bridge.set_events_loading(has && !extra.is_some_and(|e| e.events_loaded)); + let channels = self.event_channels(); + bridge.set_event_channels(crate::app::model( + channels.iter().map(|(_, n)| SharedString::from(n.as_str())).collect(), + )); + let now = now_ms(); + let items: Vec = extra + .map(|extra| { + extra + .events + .iter() + .filter(|e| e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000) >= now) + .map(|e| { + let (weekday, day, month) = date_block(e.spec.start_ms); + let place = channels + .iter() + .find(|(c, _)| *c == e.spec.channel) + .map_or_else(|| "A channel".to_owned(), |(_, n)| n.clone()); + let stream = if e.spec.kind == EventKind::Stream { + [e.spec.stream_title.clone(), e.spec.stream_game.clone()] + .into_iter() + .flatten() + .filter(|s| !s.is_empty()) + .collect::>() + .join(" · ") + } else { + String::new() + }; + let stream = if e.spec.kind == EventKind::Stream && stream.is_empty() { + "Scheduled stream".to_owned() + } else { + stream + }; + EventItem { + id: e.id as i32, + title: e.spec.title.clone().into(), + description: e.spec.description.clone().into(), + weekday: weekday.into(), + day: day.into(), + month: month.into(), + when: event_when(e.spec.start_ms, e.spec.end_ms).into(), + place: place.into(), + stream: stream.into(), + live: e.live_stream.is_some(), + going: e.going as i32, + maybe: e.maybe as i32, + not_going: e.not_going as i32, + rsvp: e.my_rsvp.map(RsvpStatus::as_str).unwrap_or_default().into(), + creator: e.creator.name.clone().into(), + editable: moderate + || extra.gateway_uid.as_deref() == Some(e.creator.uid.as_str()), + soon: soon(e.spec.start_ms, e.spec.end_ms, now).into(), + attendees: crate::app::model( + e.attendees + .iter() + .map(|a| { + let status = match a.status { + RsvpStatus::Going => "going", + RsvpStatus::Maybe => "maybe", + RsvpStatus::NotGoing => "not going", + RsvpStatus::Unknown => "?", + }; + SharedString::from(format!("{} ({status})", a.user.name)) + }) + .collect(), + ), + expanded: extra.expanded.contains(&e.id), + } + }) + .collect() + }) + .unwrap_or_default(); + vm::list::sync(&self.models.social.events, &items); + } + + /// Answer an event ("" withdraws the answer). + pub(crate) fn rsvp(&mut self, event_id: i32, status: &str) { + let Some(id) = self.current else { return }; + let status = (!status.is_empty()).then(|| RsvpStatus::parse(status)); + self.gateway_to(id, GatewayRequest::Rsvp { event_id: i64::from(event_id), status }); + } + + /// Show or hide who answered (fetching the event with its attendees). + pub(crate) fn toggle_event(&mut self, event_id: i32) { + let Some(id) = self.current else { return }; + let event_id = i64::from(event_id); + let view = self.sessions.entry(id).or_default(); + if !view.extra.expanded.remove(&event_id) { + view.extra.expanded.insert(event_id); + self.gateway_to(id, GatewayRequest::GetEvent { id: event_id }); + } + self.refresh_events(); + } + + /// The form for a new event (`-1`) or an existing one. + pub(crate) fn edit_event(&self, event_id: i32) -> EventForm { + let channels = self.event_channels(); + let event = + self.view().and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id))); + match event { + Some(e) => EventForm { + id: event_id, + title: e.spec.title.clone().into(), + description: e.spec.description.clone().into(), + start: format_local(e.spec.start_ms).into(), + end: e.spec.end_ms.map(format_local).unwrap_or_default().into(), + channel: channels.iter().position(|(c, _)| *c == e.spec.channel).unwrap_or(0) + as i32, + stream: e.spec.kind == EventKind::Stream, + stream_title: e.spec.stream_title.clone().unwrap_or_default().into(), + game: e.spec.stream_game.clone().unwrap_or_default().into(), + }, + None => { + // The next full hour. + let start = (now_ms() / 3_600_000 + 1) * 3_600_000; + EventForm { id: -1, start: format_local(start).into(), ..Default::default() } + } + } + } + + /// Create or change an event; the reason when the form is not right. + pub(crate) fn save_event(&mut self, form: &EventForm) -> String { + let Some(id) = self.current else { return "No server selected.".into() }; + let Some(start_ms) = parse_local(&form.start) else { + return "Write the start as YYYY-MM-DD HH:MM.".into(); + }; + let end_ms = if form.end.trim().is_empty() { + None + } else { + match parse_local(&form.end) { + Some(end) if end > start_ms => Some(end), + Some(_) => return "The end must be after the start.".into(), + None => return "Write the end as YYYY-MM-DD HH:MM, or leave it empty.".into(), + } + }; + let channels = self.event_channels(); + let text = |s: &slint::SharedString| Some(s.to_string()).filter(|s| !s.trim().is_empty()); + let spec = EventSpec { + title: form.title.trim().to_owned(), + description: form.description.to_string(), + start_ms, + end_ms, + channel: channels.get(form.channel.max(0) as usize).and_then(|(c, _)| *c), + kind: if form.stream { EventKind::Stream } else { EventKind::General }, + stream_title: text(&form.stream_title).filter(|_| form.stream), + stream_game: text(&form.game).filter(|_| form.stream), + host_uid: None, + }; + self.gateway_to( + id, + if form.id < 0 { + GatewayRequest::CreateEvent { event: spec } + } else { + GatewayRequest::UpdateEvent { id: i64::from(form.id), event: spec } + }, + ); + String::new() + } + + pub(crate) fn delete_event(&mut self, event_id: i32) { + if let Some(id) = self.current { + self.gateway_to(id, GatewayRequest::DeleteEvent { id: i64::from(event_id) }); + } + } + + /// Watch the stream of a live scheduled stream. + pub(crate) fn watch_event(&mut self, event_id: i32) { + let Some(id) = self.current else { return }; + let stream = self + .view() + .and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id))) + .and_then(|e| e.live_stream.clone()); + if let Some(stream) = stream { + self.watch_live(id, &stream); + } + } +} diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs new file mode 100644 index 0000000..457af30 --- /dev/null +++ b/crates/voelin-ui/src/home.rs @@ -0,0 +1,331 @@ +//! The home page (design mockup 01): live streams on our servers, what is +//! happening there (events, scheduled streams, server news), and the +//! Library of recordings and clips. Friends are in `social.rs`, the recent +//! chats in `messages.rs`. + +use std::path::{Path, PathBuf}; + +use slint::ComponentHandle; +use voelin_core::VoiceState; + +use crate::app::{App, Bridge, HappeningItem, LiveItem, Nav, Page, RecordingItem}; +use crate::vm; +use crate::vm::social::{event_when, plain}; + +/// What a "What's Happening" entry opens. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Happening { + Event(i64, i64), + News(i64), +} + +/// "screen" → "Screen". +fn kind_label(kind: &str) -> String { + let mut chars = kind.chars(); + chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default() +} + +impl App { + /// Streams on our servers: those in our channel (we can watch them at + /// once), the gateways' directories, and clients flagged streaming. + fn live_rooms(&self) -> Vec { + let mut rooms = Vec::new(); + for b in &self.bookmarks { + let Some(view) = self.sessions.get(&b.id) else { continue }; + let channel_of = |cid: Option| { + cid.and_then(|c| view.presence.channels.get(&c)) + .map(|c| c.name.clone()) + .unwrap_or_default() + }; + let backdrop = vm::avatar::tint(&b.name); + let item = |id: String, + title: String, + client: Option, + uid: Option<&str>, + name: String| { + let avatar = match (client, uid) { + (Some(c), _) if view.avatar(c).is_some() => vm::avatar::image(view.avatar(c)), + (_, Some(uid)) => self.avatar_of(uid), + _ => slint::Image::default(), + }; + LiveItem { + session: b.id as i32, + id: id.into(), + title: title.into(), + initials: vm::avatar::initials(&name).into(), + tint: vm::avatar::tint(&name), + avatar, + streamer: name.into(), + server: b.name.clone().into(), + backdrop, + ..Default::default() + } + }; + let mut covered: Vec = Vec::new(); + if view.streams_available() { + for s in &view.streams { + let name = view.nickname(s.streamer.0); + let title = + if s.name.is_empty() { format!("{name}'s stream") } else { s.name.clone() }; + let mut room = item(s.id.clone(), title, Some(s.streamer.0), None, name); + room.channel = channel_of(view.state.own_channel).into(); + room.viewers = view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32); + room.kind = match s.kind { + voelin_core::stream::StreamKind::Screen => "Screen", + voelin_core::stream::StreamKind::Window => "Window", + voelin_core::stream::StreamKind::Camera => "Camera", + voelin_core::stream::StreamKind::Other(_) => "", + } + .into(); + room.watchable = view.state.own_client != Some(s.streamer.0); + covered.push(s.streamer.0); + rooms.push(room); + } + } + for e in &view.extra.directory { + if e.client_id.is_some_and(|c| covered.contains(&c)) { + continue; + } + let title = if e.title.is_empty() { + format!("{}'s stream", e.streamer.name) + } else { + e.title.clone() + }; + let mut room = item( + e.id.clone(), + title, + e.client_id, + Some(&e.streamer.uid), + e.streamer.name.clone(), + ); + room.channel = channel_of(e.channel).into(); + room.viewers = e.viewers.map_or(0, |v| v as i32); + room.kind = kind_label(&e.kind).into(); + covered.extend(e.client_id); + rooms.push(room); + } + for c in view.presence.clients.values() { + if c.streaming != Some(true) + || covered.contains(&c.id) + || Some(c.id) == view.state.own_client + { + continue; + } + let mut room = item( + format!("client/{}", c.id), + format!("{} is live", c.nickname), + Some(c.id), + c.uid.as_deref(), + c.nickname.clone(), + ); + room.channel = channel_of(Some(c.channel)).into(); + rooms.push(room); + } + } + rooms + } + + /// Events, scheduled streams and server news of our servers, what is + /// soonest first. + pub(crate) fn happenings(&self) -> Vec<(HappeningItem, Happening)> { + let now = crate::social::now_ms(); + let mut events: Vec<(i64, HappeningItem, Happening)> = Vec::new(); + let mut news = Vec::new(); + for b in &self.bookmarks { + let Some(view) = self.sessions.get(&b.id) else { continue }; + for e in &view.extra.events { + let ends = e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000); + if ends < now { + continue; + } + let stream = e.spec.kind == voelin_gateway_proto::EventKind::Stream; + events.push(( + e.spec.start_ms, + HappeningItem { + kind: if stream { "stream" } else { "event" }.into(), + title: e.spec.title.clone().into(), + subtitle: if stream { + format!("Scheduled stream · {}", b.name) + } else { + format!("Event · {}", b.name) + } + .into(), + when: event_when(e.spec.start_ms, e.spec.end_ms).into(), + session: b.id as i32, + id: e.id as i32, + live: e.live_stream.is_some(), + }, + Happening::Event(b.id, e.id), + )); + } + let details = &view.presence.server; + for (title, text) in [ + (format!("Welcome to {}", b.name), &details.welcome_message), + (format!("News of {}", b.name), &details.host_message), + ] { + let text = plain(text); + if !text.is_empty() { + news.push(( + HappeningItem { + kind: "news".into(), + title: title.into(), + subtitle: text.into(), + session: b.id as i32, + ..Default::default() + }, + Happening::News(b.id), + )); + } + } + } + events.sort_by_key(|(start, ..)| *start); + events + .into_iter() + .map(|(_, item, h)| (item, h)) + .take(6) + .chain(news.into_iter().take(3)) + .collect() + } + + /// Live rooms and what is happening (friends: `refresh_people`, chats: + /// `refresh_chats`). + pub(crate) fn refresh_home(&self) { + let m = &self.models.social; + vm::list::sync(&m.live, &self.live_rooms()); + let items: Vec = self.happenings().into_iter().map(|(i, _)| i).collect(); + vm::list::sync(&m.happenings, &items); + } + + /// A live room's card: watch it at once in our channel, else go to its + /// server (and the streamer's channel, watching once there). + pub(crate) fn watch_live(&mut self, session: i64, id: &str) { + self.show_server(session); + let Some(view) = self.sessions.get(&session) else { return }; + if view.streams_available() && view.streams.iter().any(|s| s.id == id) { + self.watch_stream(id.to_owned()); + return; + } + let client = view + .extra + .directory + .iter() + .find(|e| e.id == id) + .and_then(|e| e.client_id) + .or_else(|| id.strip_prefix("client/").and_then(|c| c.parse().ok())); + let Some(uid) = + client.and_then(|c| view.presence.clients.get(&c)).and_then(|c| c.uid.clone()) + else { + self.set_status("Join the streamer's channel with voice to watch."); + return; + }; + if view.state.voice == VoiceState::Connected { + self.contact_action(&uid, "watch"); + } else { + self.set_status("Connect with voice and join the streamer's channel to watch."); + } + } + + pub(crate) fn open_happening(&mut self, index: i32) { + let Some((_, target)) = + usize::try_from(index).ok().and_then(|i| self.happenings().into_iter().nth(i)) + else { + return; + }; + match target { + Happening::Event(session, _) => { + self.select_server(session); + if let Some(ui) = self.ui.upgrade() { + ui.global::