diff --git a/Cargo.lock b/Cargo.lock index 3d23d0e..8d8e7e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9489,6 +9489,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 67fa22d..44fb3fd 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -49,6 +49,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 bbda305..7b3864d 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}; @@ -253,6 +254,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]; @@ -502,6 +548,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 4f0a5fb..8a76b19 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, } @@ -875,6 +896,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), @@ -1347,6 +1374,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 }); } @@ -1548,6 +1579,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 7f07646..0b51b7f 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1170,6 +1170,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)] @@ -1322,6 +1349,8 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> { &IDENTITY_IMPORT, &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/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 9420d28..27d95b1 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -54,6 +54,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); + } prefs.register(&crate::studio::STUDIO_UI); let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) @@ -219,6 +222,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 { @@ -242,6 +247,7 @@ impl Default for SessionView { stream_viewers: HashMap::new(), downloads: HashMap::new(), next_transfer: 1, + extra: Default::default(), } } } @@ -314,6 +320,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 { @@ -331,6 +346,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())); @@ -344,6 +366,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 } } @@ -359,8 +387,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. @@ -410,6 +436,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, /// The Stream Studio (studio.rs). pub studio: crate::studio::StudioState, } @@ -596,7 +626,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, @@ -624,15 +653,24 @@ pub fn run(options: RunOptions) -> Result<()> { open_client_pending: switches.open_client, notices_loaded: false, uploads: HashMap::new(), + social: Default::default(), + pages: Default::default(), studio: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); crate::bind::wire(&ui); with_app(|app| { app.apply_appearance(); + app.load_own_uids(); + 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(); } @@ -766,9 +804,16 @@ impl App { } else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() { self.video.set_decoder_preference(decoder_preference(&self.prefs)); } + 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; @@ -866,7 +911,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(); @@ -894,6 +942,8 @@ impl App { Event::Transfer { session, transfer, state } => { self.transfer_progress(session as i64, transfer, state); } + // The engine's contacts would replace the sample ones. + Event::ContactsChanged { .. } if self.demo_ui && !self.contacts.is_empty() => {} Event::ContactsChanged { contacts } => { self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); self.refresh_member_card(); @@ -919,6 +969,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 92ff348..74eef87 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; pub(crate) mod studio; @@ -19,5 +21,7 @@ pub(crate) fn wire(ui: &MainWindow) { streams::wire(ui); settings::wire(ui); emoji::wire(ui); + social::wire(ui); + pages::wire(ui); studio::wire(&ui.global::()); } 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 e232a47..6c631e0 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 80bea68..d31bff3 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -67,7 +67,7 @@ impl App { format!("#{}", name.unwrap_or_else(|| cid.to_string())) } ChatTarget::Server => "Server".into(), - ChatTarget::Private(uid) => format!("@{uid}"), + ChatTarget::Private(uid) => format!("@{}", self.peer_name(uid, None)), }; let view = self.sessions.entry(id).or_default(); let index = match view.tabs.iter().position(|t| t.target == target) { @@ -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(); } @@ -183,9 +186,20 @@ impl App { complete: bool, ) { let current = self.current == Some(id); + // A private chat is named after the peer, whoever wrote first. + let peer = match target { + ChatTarget::Private(uid) => Some(format!( + "@{}", + self.peer_name( + uid, + messages.iter().find(|m| m.message.author_uid.as_deref() == Some(uid.as_str())) + ) + )), + _ => None, + }; let view = self.sessions.entry(id).or_default(); let author = messages.first().map_or("", |m| m.message.author_name.as_str()); - let title = Self::tab_title(view, target, author); + let title = peer.unwrap_or_else(|| Self::tab_title(view, target, author)); let index = Self::tab_for(view, target, || title); let shown = current && view.current_tab == index; let tab = &mut view.tabs[index]; @@ -214,6 +228,7 @@ impl App { tab.unread += fresh; } if current { + self.fetch_previews(id); self.refresh_chat(); } if fresh > 0 && !shown { @@ -249,7 +264,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)); @@ -260,6 +275,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), @@ -267,11 +290,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. @@ -712,6 +744,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/dev.rs b/crates/voelin-ui/src/dev.rs index 4c6aaa1..c238a23 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -12,7 +12,7 @@ //! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer. //! - `VOELIN_OPEN=[,...]`: open screens on start: `home`, //! `server`, `settings[:
]` (voice, keybinds, streaming, privacy, -//! appearance, identities, or 0-5), `about`, `share`, `bookmark` (add a server; +//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server; //! `bookmark:edit` the current one, Advanced open), //! `emoji` (the picker), `client` (the volume dialog of the first other //! client once connected), `panel` / `no-panel` (the members panel), @@ -23,7 +23,14 @@ //! `topic:` (a topic's messages), `member` (the member card of the //! first other client), `watch` (the first stream; with sample data the //! local test pattern in its place), `popout` (the same, popped out), -//! `tab:` (phone layout), +//! `tab:` (phone layout); `friends[:]`, +//! `messages[:]` (a private chat), `inbox` (offline messages), +//! `library`, `events`, `event-form`, `search[:]`, +//! `notifications` (the bell), `join` (join by address), `offline` (an +//! offline message), `picture` (a chat picture opened large), `camera` +//! (the settings' camera preview); settings sections also `account`, +//! `profiles` (also `identities`), `devices`, `notifications`, +//! `integrations`, `advanced` (5-10); //! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo //! studio from synthetic sources), `studio:window` in a window of its own, //! `studio:live` going live, `studio:record`, or a dialog: `studio:source`, @@ -42,16 +49,22 @@ use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::gateway::Pin; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{ - Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, SessionState, Source, - VoiceState, + Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, OfflineMessageInfo, + Relation, SessionState, Source, VoiceState, +}; +use voelin_gateway_proto::{ + Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule, + PermRuleInfo, ReactionCount, RsvpStatus, StreamEntry, StreamSource, TopicInfo, UserRef, + feature, }; -use voelin_gateway_proto::{ReactionCount, StreamEntry, StreamSource, TopicInfo, UserRef, feature}; use voelin_model::{ ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor, }; use voelin_store::{Bookmark, MessageSource}; -use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app}; +use crate::app::{ + App, Bridge, MainWindow, MobileTab, Nav, Page, RecordingItem, SettingsSection, with_app, +}; /// The switches read at start. #[derive(Clone, Debug, Default)] @@ -108,7 +121,12 @@ fn section(name: &str) -> SettingsSection { "2" | "streaming" => SettingsSection::Streaming, "3" | "privacy" => SettingsSection::Privacy, "4" | "appearance" => SettingsSection::Appearance, - "5" | "identities" => SettingsSection::Identities, + "5" | "account" => SettingsSection::Account, + "6" | "profiles" | "identities" => SettingsSection::Profiles, + "7" | "devices" => SettingsSection::Devices, + "8" | "notifications" => SettingsSection::Notifications, + "9" | "integrations" => SettingsSection::Integrations, + "10" | "advanced" => SettingsSection::Advanced, _ => SettingsSection::Voice, } } @@ -202,6 +220,41 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { }); ui.global::().set_viewer_popped(what == "popout"); } + // Home, friends, messages, events, the bell, the search. + "friends" => { + with_app(|app| app.select_contact(arg.to_owned())); + nav.invoke_show(Page::Friends); + } + "messages" | "dm" => { + let uid = if arg.is_empty() { "demo-3" } else { arg }; + with_app(|app| app.open_dm_with(Some(DEMO), uid)); + nav.invoke_show(Page::Messages); + } + "inbox" => { + nav.set_dm_tab(2); + with_app(|app| app.dm_tab(2)); + nav.invoke_show(Page::Messages); + } + "library" => nav.invoke_show(Page::Library), + "events" => nav.invoke_show(Page::Events), + "event-form" => nav.invoke_create_event(), + "search" => nav.invoke_open_search(arg.into()), + "notifications" => nav.set_notifications_open(true), + "join" => nav.invoke_join_server(), + "offline" => nav.invoke_write_offline("demo-ari".into(), "Ari".into()), + "picture" => { + let picture = demo_picture(1280, 720, 16); + let image = crate::images::picture("demo:lightbox", &picture); + nav.set_lightbox(image); + nav.set_lightbox_open(true); + } + // The camera preview of the settings (the test pattern). + "camera" => { + with_app(|app| { + app.start_camera(); + app.refresh_pages(); + }); + } "studio" => { if arg != "window" { nav.invoke_open_studio(); @@ -318,7 +371,10 @@ fn demo_ui(app: &mut App) { client_version: None, }; app.bookmarks = vec![ - bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987"), + Bookmark { + gateway_url: Some("wss://gw.nightfall.example/v1".into()), + ..bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987") + }, bookmark(DEMO + 1, "Pixel Lounge", "pixel.example"), bookmark(DEMO + 2, "Dev TS3", "127.0.0.1:9987"), ]; @@ -326,6 +382,9 @@ fn demo_ui(app: &mut App) { let session = DEMO as u64; let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() }; + p.server.welcome_message = + "Welcome to [b]Nightfall Guild[/b]! Raids on Tuesdays and Fridays, all levels welcome." + .into(); let mut chill = channel(2, 0, 1, "Chill Zone"); chill.max_clients = Some(50); chill.topic = Some("Hang out, chat, and explore the worlds beyond.".into()); @@ -354,6 +413,9 @@ fn demo_ui(app: &mut App) { client(9, 1, "Rin"), ]; clients[1].streaming = Some(true); + // Live in other channels (the gateway's directory has their streams). + clients[5].streaming = Some(true); + clients[6].streaming = Some(true); clients[4].input_muted = true; clients[7].away = Some("brb".into()); clients[8].output_muted = true; @@ -426,6 +488,10 @@ fn demo_ui(app: &mut App) { feature::PINS.into(), feature::REACTIONS.into(), feature::TOPICS.into(), + feature::EVENTS.into(), + feature::STREAMS.into(), + feature::ACTIVITY.into(), + feature::ADMIN.into(), ], }, }, @@ -452,11 +518,529 @@ fn demo_ui(app: &mut App) { app.handle_event(event); } demo_chat(app, session); + demo_social(app); // No toast over the screenshots. app.set_status(""); app.refresh_all(); } +/// Sample people, private chats, pokes, notifications, events, a picture +/// and recordings for the home, friends, messages, events and settings +/// screens (`VOELIN_DEMO_UI`). +fn demo_social(app: &mut App) { + let session = DEMO as u64; + let now = chrono::Utc::now().timestamp_millis(); + let min = 60_000; + // The second sample server is observed: a few people there. + let mut lounge = Presence { server_name: "Pixel Lounge".into(), ..Default::default() }; + for c in [channel(1, 0, 0, "Lobby"), channel(2, 0, 1, "Art Corner"), channel(3, 0, 2, "Music")] + { + lounge.channels.insert(c.id, c); + } + let mut ivy = client(21, 2, "Ivy"); + ivy.uid = Some("demo-ivy".into()); + let mut sora = client(22, 3, "Sora"); + sora.uid = Some("demo-sora".into()); + sora.away = Some("painting".into()); + let mut pixel = client(23, 1, "Pixel"); + pixel.uid = Some("demo-pixel".into()); + for c in [ivy, sora, pixel] { + lounge.clients.insert(c.id, c); + } + app.handle_event(Event::Presence { session: session + 1, presence: Arc::new(lounge) }); + app.handle_event(Event::State { + session: session + 1, + state: SessionState { + observe: ObserveState::Observing, + presence_source: Some(Source::Gateway), + server_uid: Some("demo-lounge".into()), + ..Default::default() + }, + }); + app.handle_event(Event::ServerInfo { + session: session + 1, + name: "Pixel Lounge".into(), + flavor: ServerFlavor::from_version_string("3.13.8 [Build: 1]"), + capabilities: Default::default(), + }); + + // Contacts: friends here and there, some offline, one blocked. + let contact = + |uid: &str, nick: &str, relation: Relation, seen_min: i64, server: &str| Contact { + uid: uid.into(), + nickname: nick.into(), + relation, + note: String::new(), + muted: false, + volume: 1.0, + added_ms: now - 400 * 86_400_000, + last_seen_ms: if seen_min > 0 { now - seen_min * min } else { 0 }, + last_server: (!server.is_empty()).then(|| server.to_owned()), + }; + let mut kairo = contact("demo-3", "Kairo", Relation::Friend, 1, "Nightfall Guild"); + kairo.note = "Tank on Tuesday raids. Always down for co-op.".into(); + let contacts = vec![ + contact("demo-2", "Lumen", Relation::Friend, 1, "Nightfall Guild"), + kairo, + contact("demo-4", "Mira", Relation::Friend, 1, "Nightfall Guild"), + contact("demo-5", "dex", Relation::Friend, 1, "Nightfall Guild"), + contact("demo-6", "Talon", Relation::Friend, 1, "Nightfall Guild"), + contact("demo-7", "Zeph", Relation::Friend, 1, "Nightfall Guild"), + contact("demo-ivy", "Ivy", Relation::Friend, 1, "Pixel Lounge"), + contact("demo-sora", "Sora", Relation::Friend, 1, "Pixel Lounge"), + contact("demo-ari", "Ari", Relation::Friend, 130, "Nightfall Guild"), + contact("demo-neon", "Neon", Relation::Friend, 26 * 60, "Dev TS3"), + contact("demo-9", "Rin", Relation::Neutral, 1, "Nightfall Guild"), + contact("demo-spam", "FreeSkinsBot", Relation::Blocked, 3 * 24 * 60, "Pixel Lounge"), + ]; + app.handle_event(Event::ContactsChanged { contacts: Arc::new(contacts) }); + for (uid, ago) in [ + ("demo-2", 12), + ("demo-3", 28), + ("demo-4", 42), + ("demo-5", 64), + ("demo-6", 95), + ("demo-7", 130), + ("demo-ivy", 8), + ("demo-sora", 50), + ] { + app.social.online_since.insert(uid.into(), now - ago * min); + } + + // Private chats: with Kairo (a picture, a file), Mira, Lumen, dex, + // and Ivy on the other server; Neon's is only stored. + let picture = file_link(2, "night-castle.png", 412_331); + let private = + |id: i64, peer: &str, from_me: bool, author: (&str, u16), text: String, ago: i64| { + HistoryMessage { + id, + message: ChatMessage { + target: ChatTarget::Private(peer.into()), + author_name: author.0.into(), + author_uid: Some(if from_me { "demo-1".into() } else { peer.into() }), + author_id: (author.1 > 0).then_some(author.1), + text, + ts_ms: now - ago * min, + via_relay: false, + blocked: false, + }, + source: MessageSource::Voice, + remote_id: None, + topic_id: None, + reactions: Vec::new(), + pinned: false, + rev: 0, + } + }; + let nova = ("Nova", 1); + let kairo = ("Kairo", 3); + let lines = vec![ + private( + 300, + "demo-3", + true, + nova, + format!("Hey! Check out this shot I got last night while exploring 👀 {picture}"), + 95, + ), + private(301, "demo-3", false, kairo, "That looks incredible! Where was this?".into(), 93), + private( + 302, + "demo-3", + true, + nova, + "In the northern region. The lighting was perfect.".into(), + 91, + ), + private( + 303, + "demo-3", + false, + kairo, + "We should explore together this weekend! I found some cool locations too.".into(), + 89, + ), + private( + 304, + "demo-3", + false, + kairo, + format!( + "Here are the spots I marked. {}", + file_link(2, "exploration-routes.pdf", 2_516_582) + ), + 88, + ), + private(305, "demo-3", true, nova, "That sunset looks unreal. Let's do it! 🙌".into(), 6), + private( + 310, + "demo-4", + false, + ("Mira", 4), + "Working on a new video today, want to see a sneak peek?".into(), + 70, + ), + private(311, "demo-2", false, ("Lumen", 2), "Let's run it tonight!".into(), 120), + private(312, "demo-5", false, ("dex", 5), file_link(2, "map-notes.png", 96_120), 26 * 60), + ]; + for m in lines { + let target = m.message.target.clone(); + app.handle_event(Event::ChatHistory { + session, + target, + messages: vec![m], + source: HistorySource::Gateway, + complete: true, + }); + } + app.handle_event(Event::ChatHistory { + session: session + 1, + target: ChatTarget::Private("demo-ivy".into()), + messages: vec![HistoryMessage { + message: ChatMessage { + target: ChatTarget::Private("demo-ivy".into()), + author_name: "Ivy".into(), + author_uid: Some("demo-ivy".into()), + author_id: Some(21), + text: "Same here! The new channel is great.".into(), + ts_ms: now - 30 * min, + via_relay: true, + blocked: false, + }, + ..private(320, "demo-ivy", false, ("Ivy", 21), String::new(), 30) + }], + source: HistorySource::Gateway, + complete: true, + }); + let mut neon = private( + 330, + "demo-neon", + false, + ("Neon", 0), + "Sent you the config, check the server folder.".into(), + 3 * 24 * 60, + ); + neon.message.author_id = None; + app.social.dm.stored.push(("demo-dev".into(), neon)); + app.social.dm.bookmark_of.insert("demo-dev".into(), DEMO + 2); + // Unread: Mira's and Lumen's messages came while away. + if let Some(view) = app.sessions.get_mut(&DEMO) { + for tab in &mut view.tabs { + match &tab.target { + ChatTarget::Private(uid) if uid == "demo-4" => tab.unread = 1, + ChatTarget::Private(uid) if uid == "demo-2" => tab.unread = 2, + _ => {} + } + } + } + // A poke from Kairo, shown among the messages and in the bell. + app.handle_event(Event::Poke { + session, + from: 3, + from_uid: Some("demo-3".into()), + from_name: "Kairo".into(), + message: "raid in 5?".into(), + blocked: false, + }); + if let Some(p) = app.social.pokes.last_mut() { + p.ts_ms = now - 7 * min; + } + // Offline messages the server keeps (the Inbox tab). + let mail = |id: u32, from: &str, subject: &str, ago_min: i64, read: bool| OfflineMessageInfo { + id, + from_uid: from.into(), + subject: subject.into(), + ts_s: (now - ago_min * min) / 1000, + read, + }; + app.handle_event(Event::OfflineMessages { + session, + request: 0, + result: Ok(vec![ + mail(1, "demo-ari", "Raid roster for Friday", 3 * 60, false), + mail(2, "demo-neon", "The config for the dev server", 26 * 60, true), + mail(3, "demo-4", "Thumbnails for the stream", 3 * 24 * 60, true), + ]), + }); + + // The pictures of the links, as if downloaded. + if let Some(view) = app.sessions.get_mut(&DEMO) { + for (channel, name) in + [(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")] + { + let file = voelin_model::FileRef { + channel, + path: "/".into(), + name: name.into(), + ..Default::default() + }; + view.extra.previews.insert( + crate::previews::link_key(&file), + crate::previews::Preview::Ready(voelin_core::Bytes( + demo_picture(640, 360, name.len() as u32).into(), + )), + ); + } + } + + // The gateway's events (one is live), its configuration and rules. + let by = |name: &str, uid: &str| UserRef { uid: uid.into(), name: name.into() }; + let event = + |id: i64, title: &str, start: i64, hours: i64, channel: Option, stream: bool| { + EventInfo { + id, + spec: EventSpec { + title: title.into(), + description: String::new(), + start_ms: start, + end_ms: Some(start + hours * 3_600_000), + channel, + kind: if stream { EventKind::Stream } else { EventKind::General }, + stream_title: None, + stream_game: None, + host_uid: None, + }, + creator: by("Nova", "demo-1"), + created_ms: now - 86_400_000, + updated_ms: now - 86_400_000, + going: 0, + maybe: 0, + not_going: 0, + my_rsvp: None, + attendees: Vec::new(), + live_stream: None, + } + }; + let hour = 3_600_000; + let tomorrow = (now / 86_400_000 + 1) * 86_400_000 + 18 * hour; + let mut raid = event(1, "Raid Night: The Frozen Citadel", tomorrow, 3, Some(4), false); + raid.spec.description = "Bring elixirs and fire resistance. Voice in Raid Night.".into(); + raid.going = 12; + raid.maybe = 4; + raid.not_going = 1; + raid.my_rsvp = Some(RsvpStatus::Going); + raid.attendees = vec![ + Attendee { user: by("Nova", "demo-1"), status: RsvpStatus::Going, ts_ms: now }, + Attendee { user: by("Kairo", "demo-3"), status: RsvpStatus::Going, ts_ms: now }, + Attendee { user: by("Mira", "demo-4"), status: RsvpStatus::Maybe, ts_ms: now }, + Attendee { user: by("dex", "demo-5"), status: RsvpStatus::NotGoing, ts_ms: now }, + ]; + let mut live = event(2, "Exploring the Lands Between", now - 12 * min, 2, Some(2), true); + live.spec.stream_title = Some("Exploring the Lands Between".into()); + live.spec.stream_game = Some("Elden Ring".into()); + live.creator = by("Lumen", "demo-2"); + live.going = 8; + live.live_stream = Some("demo-stream".into()); + let mut night = event(3, "Community Game Night", tomorrow + 2 * 86_400_000, 3, None, false); + night.spec.description = "Party games for everyone: drop in any time.".into(); + night.creator = by("Talon", "demo-6"); + night.going = 23; + night.maybe = 9; + let mut lofi = event(4, "Late Night Lofi & Chat", now + 50 * min, 2, Some(5), true); + lofi.spec.stream_title = Some("Lofi beats to raid to".into()); + lofi.creator = by("Mira", "demo-4"); + lofi.going = 5; + lofi.maybe = 2; + app.handle_event(Event::Gateway { + session, + update: GatewayUpdate::Events { events: vec![raid, live, night, lofi] }, + }); + app.handle_event(Event::Gateway { + session, + update: GatewayUpdate::Permissions { + channel: None, + actions: vec![ + Action::React, + Action::Pin, + Action::CreateEvent, + Action::Rsvp, + Action::Moderate, + Action::Admin, + ], + }, + }); + let config = |key: &str, value: serde_json::Value, source: ConfigSource, description: &str| { + ConfigEntry { + key: key.into(), + default: value.clone(), + value, + source, + value_type: "int".into(), + description: description.into(), + bootstrap: false, + } + }; + app.handle_event(Event::Gateway { + session, + update: GatewayUpdate::Config { + entries: vec![ + config( + "history.retention_days", + serde_json::json!(90), + ConfigSource::Db, + "Days of chat history the gateway keeps.", + ), + config( + "events.reminders_min", + serde_json::json!([60, 15, 0]), + ConfigSource::File, + "Minutes before an event when reminders go out.", + ), + config( + "streams.directory", + serde_json::json!(true), + ConfigSource::Default, + "Keep a directory of the server's streams.", + ), + ], + }, + }); + app.handle_event(Event::Gateway { + session, + update: GatewayUpdate::PermRules { + rules: vec![ + PermRuleInfo { + action: Action::CreateEvent, + rule: Some(PermRule { + everyone: false, + server_groups: vec![GROUP_ADMIN, GROUP_MOD], + channel_groups: vec![], + }), + source: ConfigSource::Db, + default: "server admins".into(), + }, + PermRuleInfo { + action: Action::Pin, + rule: None, + source: ConfigSource::Default, + default: "moderators".into(), + }, + ], + }, + }); + + // Notifications: a mention, a message, an event, a friend online (and + // the poke above). + use crate::social::{NoticeKind, NoticeTarget}; + app.notify( + NoticeKind::Mention, + "Talon mentioned you".into(), + "Nova, can you open the raid at 20:00? — #Chill Zone · Nightfall Guild".into(), + NoticeTarget::Chat(DEMO, ChatTarget::Channel(2)), + "Talon".into(), + Some("demo-6".into()), + ); + app.notify( + NoticeKind::Event, + "Late Night Lofi & Chat starts in 50 min".into(), + "on Nightfall Guild".into(), + NoticeTarget::Event(DEMO, 4), + "Mira".into(), + Some("demo-4".into()), + ); + app.notify( + NoticeKind::Friend, + "Ivy is online".into(), + "on Pixel Lounge · #Art Corner".into(), + NoticeTarget::Contact("demo-ivy".into()), + "Ivy".into(), + Some("demo-ivy".into()), + ); + app.notify( + NoticeKind::Message, + "Mira".into(), + "Working on a new video today, want to see a sneak peek?".into(), + NoticeTarget::Dm(DEMO, "demo-4".into()), + "Mira".into(), + Some("demo-4".into()), + ); + for (i, n) in app.social.notices.iter_mut().enumerate() { + n.ts_ms = now - (i as i64 * 9 + 2) * min; + n.unread = i < 3; + } + app.refresh_notices(); + + // Recordings and clips of the Studio. + let recording = |name: &str, detail: &str| RecordingItem { + name: name.into(), + detail: detail.into(), + clip: name.contains("clip"), + path: format!("/tmp/{name}").into(), + }; + crate::vm::list::sync( + &app.models.social.recordings, + &[ + recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"), + recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"), + recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"), + recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"), + ], + ); + app.refresh_chats(); + app.refresh_people(); + app.refresh_home(); +} + +/// A painted night: sky, moon, stars, hills and a castle; PNG bytes. +fn demo_picture(width: u32, height: u32, seed: u32) -> Vec { + let mut rgba = Vec::with_capacity((width * height * 4) as usize); + let (w, h) = (width as f32, height as f32); + let (mx, my, mr) = (w * 0.68, h * 0.3, h * 0.17); + let hash = |x: u32, y: u32| { + let mut v = x.wrapping_mul(374_761_393) + ^ y.wrapping_mul(668_265_263) + ^ seed.wrapping_mul(2_654_435_761); + v = (v ^ (v >> 13)).wrapping_mul(1_274_126_177); + v ^ (v >> 16) + }; + for y in 0..height { + for x in 0..width { + let (fx, fy) = (x as f32, y as f32); + let t = fy / h; + // Sky: deep blue to violet at the horizon. + let mut c = [12.0 + 50.0 * t, 18.0 + 30.0 * t, 60.0 + 90.0 * t]; + // Moon and its glow. + let d = ((fx - mx).powi(2) + (fy - my).powi(2)).sqrt(); + if d < mr { + let shade = 1.0 - 0.25 * ((fx - mx + mr * 0.3) / mr).max(0.0); + c = [200.0 * shade, 210.0 * shade, 245.0 * shade]; + } else { + let glow = (1.0 - (d - mr) / (mr * 2.5)).max(0.0) * 60.0; + c = [c[0] + glow, c[1] + glow, c[2] + glow * 1.2]; + } + if hash(x, y) % 900 == 0 && t < 0.6 { + c = [235.0, 235.0, 255.0]; + } + // Hills, then a castle on the middle one. + let far = h * 0.62 + (fx / w * 9.0 + seed as f32).sin() * h * 0.05; + let near = h * 0.78 + (fx / w * 5.0 + 1.3).sin() * h * 0.06; + let castle = (fx > w * 0.36 + && fx < w * 0.52 + && fy > h * 0.38 + && ((((fx - w * 0.36) / (w * 0.02)) as u32).is_multiple_of(2) || fy > h * 0.45)) + || (fx > w * 0.42 && fx < w * 0.46 && fy > h * 0.24); + if fy > near { + c = [6.0, 10.0, 26.0]; + } else if fy > far || castle { + c = [16.0, 20.0, 52.0]; + // Lit windows. + if castle && hash(x / 6, y / 8) % 7 == 0 && (x % 6) < 3 && (y % 8) < 4 { + c = [255.0, 190.0, 90.0]; + } + } + rgba.extend([c[0].min(255.0) as u8, c[1].min(255.0) as u8, c[2].min(255.0) as u8, 255]); + } + } + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + if let Ok(mut writer) = encoder.write_header() { + let _ = writer.write_image_data(&rgba); + } + out +} + /// Server group ids of the sample server. const GROUP_ADMIN: u64 = 6; const GROUP_MOD: u64 = 7; @@ -680,19 +1264,47 @@ fn demo_chat(app: &mut App, session: u64) { app.handle_event(Event::Gateway { session, update: GatewayUpdate::Streams { - streams: vec![StreamEntry { - id: "demo-stream".into(), - stream_id: Some("demo-stream".into()), - streamer: UserRef { uid: "demo-2".into(), name: "Lumen".into() }, - client_id: Some(2), - channel: Some(2), - title: "Exploring the Lands Between".into(), - kind: "screen".into(), - started_ms: now - 12 * 60_000, - viewers: Some(12), - source: StreamSource::Registered, - event_id: None, - }], + streams: vec![ + StreamEntry { + id: "demo-stream".into(), + stream_id: Some("demo-stream".into()), + streamer: UserRef { uid: "demo-2".into(), name: "Lumen".into() }, + client_id: Some(2), + channel: Some(2), + title: "Exploring the Lands Between".into(), + kind: "screen".into(), + started_ms: now - 12 * 60_000, + viewers: Some(12), + source: StreamSource::Registered, + event_id: None, + }, + StreamEntry { + id: "demo-stream-2".into(), + stream_id: Some("demo-stream-2".into()), + streamer: UserRef { uid: "demo-6".into(), name: "Talon".into() }, + client_id: Some(6), + channel: Some(3), + title: "Ranked Grind & Vibes".into(), + kind: "screen".into(), + started_ms: now - 41 * 60_000, + viewers: Some(38), + source: StreamSource::Registered, + event_id: None, + }, + StreamEntry { + id: "demo-stream-3".into(), + stream_id: Some("demo-stream-3".into()), + streamer: UserRef { uid: "demo-7".into(), name: "Zeph".into() }, + client_id: Some(7), + channel: Some(4), + title: "Raid prep: gear check".into(), + kind: "camera".into(), + started_ms: now - 8 * 60_000, + viewers: Some(9), + source: StreamSource::Registered, + event_id: None, + }, + ], }, }); let by = |name: &str| UserRef { uid: format!("demo-{name}"), name: name.into() }; 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..6f4a9e9 --- /dev/null +++ b/crates/voelin-ui/src/home.rs @@ -0,0 +1,330 @@ +//! 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, 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 the server lists (any 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.channel_of(s.streamer.0)).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())); + match client { + Some(client) if view.state.voice == VoiceState::Connected => self.watch_client(client), + _ => self.set_status("Connect with voice 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); + self.navigate(|nav| nav.invoke_show(Page::Events)); + } + Happening::News(session) => self.show_server(session), + } + } + + /// Connect a bookmark with voice (the Join buttons). + pub(crate) fn connect_server(&mut self, id: i64) { + self.select_server(id); + self.connect_voice(); + } + + /// The folder of recordings and clips. + fn recordings_dir(&self) -> PathBuf { + voelin_core::studio::recording_dir(&self.prefs) + } + + /// List the recordings and clips (when the Library opens). + pub(crate) fn load_library(&mut self) { + // Sample data shows sample recordings, not the user's. + if self.demo_ui { + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_recordings_dir("~/Videos/Voelin".into()); + } + return; + } + let dir = self.recordings_dir(); + let items = recordings_in(&dir); + vm::list::sync(&self.models.social.recordings, &items); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_recordings_dir(dir.display().to_string().into()); + } + } + + pub(crate) fn open_recording(&mut self, path: &str) { + if let Err(e) = crate::app::open_path(Path::new(path)) { + self.set_status(format!("Cannot open {path}: {e}")); + } + } + + pub(crate) fn open_recordings_folder(&mut self) { + let dir = self.recordings_dir(); + if let Err(e) = std::fs::create_dir_all(&dir).and_then(|()| crate::app::open_path(&dir)) { + self.set_status(format!("Cannot open {}: {e}", dir.display())); + } + } +} + +/// The videos in `dir`, newest first. +pub(crate) fn recordings_in(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut files: Vec<(std::time::SystemTime, RecordingItem)> = entries + .flatten() + .filter_map(|e| { + let path = e.path(); + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + if !["webm", "mkv", "mp4", "mov"].contains(&ext.as_str()) { + return None; + } + let meta = e.metadata().ok()?; + let modified = meta.modified().ok()?; + let name = path.file_name()?.to_string_lossy().to_string(); + let when = chrono::DateTime::::from(modified).format("%-d %b %H:%M"); + Some(( + modified, + RecordingItem { + clip: name.to_lowercase().contains("clip"), + detail: format!("{} · {when}", vm::chat::size_text(meta.len())).into(), + name: name.into(), + path: path.display().to_string().into(), + }, + )) + }) + .collect(); + files.sort_by_key(|(t, _)| std::cmp::Reverse(*t)); + files.into_iter().map(|(_, item)| item).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn library_lists_videos() { + let dir = std::env::temp_dir().join(format!("voelin-library-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("raid.webm"), b"1234").unwrap(); + std::fs::write(dir.join("clip-boss.mkv"), b"12").unwrap(); + std::fs::write(dir.join("notes.txt"), b"x").unwrap(); + let items = recordings_in(&dir); + let mut names: Vec = items.iter().map(|i| i.name.to_string()).collect(); + names.sort(); + assert_eq!(names, ["clip-boss.mkv", "raid.webm"]); + assert!(items.iter().any(|i| i.clip && i.detail.starts_with("2 B"))); + assert!(recordings_in(&dir.join("missing")).is_empty()); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(kind_label("screen"), "Screen"); + assert_eq!(kind_label(""), ""); + } +} diff --git a/crates/voelin-ui/src/identities.rs b/crates/voelin-ui/src/identities.rs index 39892dd..d08eef8 100644 --- a/crates/voelin-ui/src/identities.rs +++ b/crates/voelin-ui/src/identities.rs @@ -1,46 +1,25 @@ -//! Settings → Identities: the stored identities, which one servers see us -//! as (the default), and the import of the official clients' identities on -//! start (`voelin_core::identity::import_new`, app.rs). +//! The identity servers see us as: the store's default (schema 4, +//! `Store::default_identity`), chosen under Settings → Profiles, and the +//! import of the official clients' identities on start +//! (`voelin_core::identity::import_new`, app.rs). The rest of the Profiles +//! page is in `settings_pages.rs`. -use slint::ComponentHandle; use tracing::warn; use voelin_core::settings::IDENTITY_IMPORT; -use voelin_store::{IdentityEntry, IdentityOrigin}; +use voelin_store::IdentityOrigin; -use crate::app::{App, Bridge, IdentityItem, model}; -use crate::vm::avatar; +use crate::app::App; -/// A row of the identities card. -fn item(entry: &IdentityEntry) -> IdentityItem { - let origin = match entry.origin { - IdentityOrigin::Imported => "From TeamSpeak", - IdentityOrigin::Created | IdentityOrigin::User => "Made in Voelin", - }; - IdentityItem { - id: entry.id as i32, - name: entry.name.clone().into(), - detail: format!("{origin} · level {}", entry.level).into(), - uid: entry.uid.clone().into(), - initials: avatar::initials(&entry.name).into(), - tint: avatar::tint(&entry.name), - is_default: entry.is_default, +/// Where an identity came from, as Profiles says it. +pub(crate) fn origin_label(origin: IdentityOrigin) -> &'static str { + match origin { + IdentityOrigin::Created => "Made in Voelin", + IdentityOrigin::Imported => "Imported", + IdentityOrigin::User => "Chosen by you", } } impl App { - pub(crate) fn refresh_identities(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let mut entries = self.store.identities().unwrap_or_default(); - // A store from before defaults were marked: the first one. - let default = self.store.default_identity().ok().flatten().map(|e| e.id); - for entry in &mut entries { - entry.is_default = Some(entry.id) == default; - } - bridge.set_identities(model(entries.iter().map(item).collect())); - bridge.set_identity_import(self.prefs.get(&IDENTITY_IMPORT)); - } - /// The user's choice of the identity servers see us as, from the next /// connection on; no import replaces it. pub(crate) fn use_identity(&mut self, id: i64) { @@ -79,23 +58,9 @@ mod tests { #[test] fn rows_say_where_an_identity_came_from() { - let entry = |origin, is_default| IdentityEntry { - id: 3, - name: "Main Nick".into(), - uid: "uid=".into(), - level: 8, - origin, - is_default, - }; - let row = item(&entry(IdentityOrigin::Imported, true)); - assert_eq!((row.id, row.name.as_str(), row.uid.as_str()), (3, "Main Nick", "uid=")); - assert_eq!(row.detail, "From TeamSpeak · level 8"); - assert!(row.is_default); - assert_eq!(row.initials, avatar::initials("Main Nick")); - for origin in [IdentityOrigin::Created, IdentityOrigin::User] { - let row = item(&entry(origin, false)); - assert_eq!(row.detail, "Made in Voelin · level 8"); - assert!(!row.is_default); - } + assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin"); + assert_eq!(origin_label(IdentityOrigin::Imported), "Imported"); + // Made by the app, then chosen: an import never replaces it. + assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you"); } } diff --git a/crates/voelin-ui/src/images.rs b/crates/voelin-ui/src/images.rs index c7af2cf..fed489c 100644 --- a/crates/voelin-ui/src/images.rs +++ b/crates/voelin-ui/src/images.rs @@ -116,6 +116,21 @@ pub fn file(path: &std::path::Path) -> Image { .unwrap_or_default() } +/// A picture from encoded bytes (PNG, JPEG, GIF, WebP), decoded once and +/// kept by `key`; an empty image if it cannot be decoded. +pub fn picture(key: &str, bytes: &[u8]) -> Image { + let cache_key = format!("picture:{key}"); + CACHE + .with(|c| { + c.borrow_mut().get_or_load(&cache_key, || { + let image = Image::load_from_data(bytes, None).ok()?; + let size = image.size(); + Some((image, size.width as usize * size.height as usize * 4)) + }) + }) + .unwrap_or_default() +} + /// A Twemoji by key; an empty image if there is none. pub fn emoji(key: &str) -> Image { if key.is_empty() { @@ -165,6 +180,17 @@ mod tests { assert_eq!(lru.get_or_load("none", || None), None); } + #[test] + fn pictures_decode() { + let mut png = Vec::new(); + let mut encoder = png::Encoder::new(&mut png, 4, 2); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.write_header().unwrap().write_image_data(&[200; 32]).unwrap(); + assert_eq!(picture("test:4x2", &png).size().width, 4); + assert_eq!(picture("test:junk", b"not a picture").size().width, 0); + } + #[test] fn emoji_images_decode() { let image = emoji("1f600"); diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index ef10c12..8ea898c 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -3,17 +3,24 @@ mod app; mod appearance; mod bind; +mod camera; mod chat; mod dev; mod emoji; +mod events; +mod home; mod hotkey; mod identities; mod images; mod inbox; mod members; +mod messages; +mod previews; mod servers; mod settings; mod settings_page; +mod settings_pages; +mod social; mod streams; mod studio; mod video; diff --git a/crates/voelin-ui/src/messages.rs b/crates/voelin-ui/src/messages.rs new file mode 100644 index 0000000..877d2f6 --- /dev/null +++ b/crates/voelin-ui/src/messages.rs @@ -0,0 +1,799 @@ +//! Direct messages (design mockup 02) and the recent chats of the home +//! page: every chat the sessions hold and the newest ones in the history +//! store, across servers; the open private chat with who it is with; TS3 +//! and TS6 offline messages (mail the server keeps). +//! +//! A private chat is a chat tab of its session (`ChatTarget::Private` +//! stored under the peer's unique id), so opening one selects its server +//! and its tab: the chat view's machinery (history pages, the composer) +//! serves it. A chat only in the store (its server is not connected, or no +//! longer a bookmark) is read from there and shown read-only. + +use std::collections::HashMap; + +use slint::{ComponentHandle, Image, SharedString}; +use voelin_core::{Command, HistoryMessage, OfflineMessage, OfflineMessageInfo, VoiceState}; +use voelin_model::ChatTarget; +use voelin_store::PageQuery; + +use crate::app::{App, Bridge, ConversationItem, DmPeer, FileItem, Nav, OfflineForm, Page, later}; +use crate::vm; +use crate::vm::social::{ago, list_time, matches, plain, preview}; + +/// Keys of offline messages in the conversation list start here. +const MAIL: i32 = 10_000; + +/// A chat of any server. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ChatRef { + /// The bookmark (session) it belongs to, when known. + pub session: Option, + pub server_uid: Option, + pub target: ChatTarget, + pub last: Option, + pub unread: i32, +} + +/// The open conversation. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Open { + pub session: Option, + pub server_uid: Option, + pub uid: String, + /// An offline message (session, id) shown instead of the chat. + pub mail: Option<(i64, u32)>, + /// Read from the store: no session holds the chat. + pub stored: bool, +} + +#[derive(Default)] +pub(crate) struct Dms { + /// The newest stored message of every chat, with its server's unique id. + pub stored: Vec<(String, HistoryMessage)>, + /// Bookmarks by the server unique id remembered for their address. + pub bookmark_of: HashMap, + /// Every chat, newest first (the keys of the lists). + pub chats: Vec, + /// The Inbox tab's offline messages: session and message. + pub inbox: Vec<(i64, OfflineMessageInfo)>, + /// 0 all, 1 unread, 2 inbox. + pub tab: i32, + pub filter: String, + pub open: Option, + /// The text of the open offline message. + pub mail: Option, + /// Offline message requests in flight: session and what for. + pub requests: HashMap, + pub next_request: u64, +} + +impl App { + /// Read the newest chats of the history store (start, and when the + /// lists are shown). + pub(crate) fn load_recent_chats(&mut self) { + if self.demo_ui { + return; + } + self.social.dm.bookmark_of.clear(); + for b in &self.bookmarks { + for alias in [ + Some(format!("voice:{}", b.address)), + b.gateway_url.as_ref().map(|u| format!("gateway:{u}")), + ] + .into_iter() + .flatten() + { + if let Ok(Some(uid)) = self.store.server_alias(&alias) { + self.social.dm.bookmark_of.insert(uid, b.id); + } + } + } + let history = self.engine.history(); + self.engine.runtime().spawn(async move { + let result = history.recent_chats(60).await; + later(move |app| match result { + Ok(list) => { + app.social.dm.stored = list; + app.refresh_chats(); + app.refresh_home(); + } + Err(e) => tracing::warn!("cannot read recent chats: {e}"), + }); + }); + } + + /// The session a server unique id belongs to. + fn session_of_server(&self, server_uid: &str) -> Option { + self.sessions + .iter() + .find(|(_, v)| v.state.server_uid.as_deref() == Some(server_uid)) + .map(|(id, _)| *id) + .or_else(|| self.social.dm.bookmark_of.get(server_uid).copied()) + } + + /// What we call the peer of a private chat. + pub(crate) fn peer_name(&self, uid: &str, last: Option<&HistoryMessage>) -> String { + if let Some(c) = self.contacts.get(uid).filter(|c| !c.nickname.is_empty()) { + return c.nickname.clone(); + } + if let Some(s) = self.spots_of(uid).first() { + return self.sessions[&s.session].nickname(s.client); + } + let from_peer = |m: &HistoryMessage| { + (m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone()) + }; + last.and_then(from_peer) + .or_else(|| { + self.sessions.values().flat_map(|v| &v.tabs).find_map(|t| { + (t.target == ChatTarget::Private(uid.to_owned())) + .then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message))) + .flatten() + }) + }) + .unwrap_or_else(|| uid.chars().take(8).collect()) + } + + /// Every chat, newest first; then the lists that show them. + pub(crate) fn refresh_chats(&mut self) { + let mut chats: Vec = Vec::new(); + for b in &self.bookmarks { + let Some(view) = self.sessions.get(&b.id) else { continue }; + for tab in &view.tabs { + let last = tab.messages.last().map(|m| m.message.clone()); + if last.is_none() && !matches!(tab.target, ChatTarget::Private(_)) { + continue; + } + chats.push(ChatRef { + session: Some(b.id), + server_uid: view.state.server_uid.clone(), + target: tab.target.clone(), + last, + unread: tab.unread, + }); + } + } + for (server_uid, m) in &self.social.dm.stored { + let known = chats.iter().any(|c| { + c.target == m.message.target && c.server_uid.as_deref() == Some(server_uid.as_str()) + }); + if !known { + chats.push(ChatRef { + session: self.session_of_server(server_uid), + server_uid: Some(server_uid.clone()), + target: m.message.target.clone(), + last: Some(m.clone()), + unread: 0, + }); + } + } + chats.sort_by_key(|c| std::cmp::Reverse(c.last.as_ref().map_or(0, |m| m.message.ts_ms))); + self.social.dm.chats = chats; + self.social.dm.inbox = self + .bookmarks + .iter() + .filter_map(|b| self.sessions.get(&b.id).map(|v| (b.id, v))) + .flat_map(|(id, v)| v.extra.inbox.iter().map(move |m| (id, m.clone()))) + .collect(); + self.social.dm.inbox.sort_by_key(|(_, m)| std::cmp::Reverse(m.ts_s)); + self.refresh_conversations(); + self.refresh_dm(); + } + + /// One chat for a list. + fn conversation_item(&self, key: usize, chat: &ChatRef) -> ConversationItem { + let session = chat.session; + let server = + session.map(|s| self.server_name(s)).unwrap_or_else(|| "Another server".into()); + let (title, avatar, online, kind) = match &chat.target { + ChatTarget::Private(uid) => ( + self.peer_name(uid, chat.last.as_ref()), + self.avatar_of(uid), + !self.spots_of(uid).is_empty(), + 2, + ), + ChatTarget::Channel(cid) => { + let name = session + .and_then(|s| self.sessions.get(&s)) + .and_then(|v| v.presence.channels.get(cid)) + .map_or_else(|| format!("#channel {cid}"), |c| format!("#{}", c.name)); + (name, slint::Image::default(), false, 1) + } + ChatTarget::Server => (server.clone(), slint::Image::default(), false, 0), + }; + let (text, ts) = match &chat.last { + Some(m) => { + let mine = session.is_some_and(|s| self.is_own(s, &m.message)); + let files = m.message.file_refs(); + let mut text = preview(&m.message.text, mine, &files); + if kind != 2 && !mine { + text = format!("{}: {text}", m.message.author_name); + } + (text, m.message.ts_ms) + } + None => (String::new(), 0), + }; + let open = self.social.dm.open.as_ref(); + ConversationItem { + key: key as i32, + kind, + title: title.clone().into(), + server: server.into(), + preview: text.into(), + time: list_time(ts).into(), + ago: ago(ts).into(), + unread: chat.unread, + initials: vm::avatar::initials(&title).into(), + tint: vm::avatar::tint(&title), + avatar, + online, + selected: open.is_some_and(|o| { + o.mail.is_none() + && ChatTarget::Private(o.uid.clone()) == chat.target + && (o.session == chat.session || o.server_uid == chat.server_uid) + }), + } + } + + /// The DM list, the recent chats of home and the unread counts. + fn refresh_conversations(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let dm = &self.social.dm; + let recent: Vec = dm + .chats + .iter() + .enumerate() + .filter(|(_, c)| c.last.is_some()) + .take(4) + .map(|(i, c)| self.conversation_item(i, c)) + .collect(); + vm::list::sync(&self.models.social.recent, &recent); + let private = |c: &&ChatRef| matches!(c.target, ChatTarget::Private(_)); + let items: Vec = if dm.tab == 2 { + dm.inbox + .iter() + .enumerate() + .map(|(i, (session, m))| { + let name = self.peer_name(&m.from_uid, None); + ConversationItem { + key: MAIL + i as i32, + kind: 3, + title: name.clone().into(), + server: self.server_name(*session).into(), + preview: m.subject.clone().into(), + time: list_time(m.ts_s * 1000).into(), + ago: ago(m.ts_s * 1000).into(), + unread: i32::from(!m.read), + // A letter in the sender's colour, no initials or + // picture under it. + initials: SharedString::new(), + tint: vm::avatar::tint(&name), + avatar: Image::default(), + online: false, + selected: dm + .open + .as_ref() + .is_some_and(|o| o.mail == Some((*session, m.id))), + } + }) + .filter(|c| matches(&dm.filter, &[&c.title, &c.preview])) + .collect() + } else { + dm.chats + .iter() + .enumerate() + .filter(|(_, c)| private(c) && (dm.tab == 0 || c.unread > 0)) + .map(|(i, c)| self.conversation_item(i, c)) + .filter(|c| matches(&dm.filter, &[&c.title, &c.preview])) + .collect() + }; + vm::list::sync(&self.models.social.conversations, &items); + let unread: i32 = dm.chats.iter().filter(private).map(|c| c.unread).sum(); + bridge.set_dm_unread(unread); + bridge.set_inbox_unread(dm.inbox.iter().filter(|(_, m)| !m.read).count() as i32); + } + + pub(crate) fn dm_tab(&mut self, tab: i32) { + self.social.dm.tab = tab; + if tab == 2 { + for view in self.sessions.values_mut() { + view.extra.inbox_asked = false; + } + self.ask_inboxes(); + } + self.refresh_conversations(); + } + + pub(crate) fn search_conversations(&mut self, text: String) { + self.social.dm.filter = text; + self.refresh_conversations(); + } + + /// Open a chat of the lists (`-1` closes the open one). + pub(crate) fn open_conversation(&mut self, key: i32) { + if key < 0 { + self.social.dm.open = None; + self.refresh_dm(); + return; + } + if key >= MAIL { + let Some((session, m)) = self.social.dm.inbox.get((key - MAIL) as usize).cloned() + else { + return; + }; + self.open_mail(session, &m); + return; + } + let Some(chat) = self.social.dm.chats.get(key as usize).cloned() else { return }; + match &chat.target { + ChatTarget::Private(uid) => self.open_dm(chat.session, chat.server_uid.clone(), uid), + target => { + let Some(session) = chat.session else { + self.set_status("That server is not in your bookmarks."); + return; + }; + self.show_server(session); + self.open_chat(target.clone(), true); + } + } + } + + /// Message someone: where they are with voice, else the newest + /// conversation with them, else where they were seen. + pub(crate) fn message_person(&mut self, uid: &str) { + let spots = self.spots_of(uid); + let session = spots.iter().find(|s| s.voice).or(spots.first()).map(|s| s.session); + self.open_dm_with(session, uid); + } + + /// Open the private chat with `uid`, in `session` if given. + pub(crate) fn open_dm_with(&mut self, session: Option, uid: &str) { + let target = ChatTarget::Private(uid.to_owned()); + let known = self + .social + .dm + .chats + .iter() + .find(|c| c.target == target && (session.is_none() || c.session == session)); + let session = session.or_else(|| known.and_then(|c| c.session)); + let server_uid = session + .and_then(|s| self.sessions.get(&s)) + .and_then(|v| v.state.server_uid.clone()) + .or_else(|| known.and_then(|c| c.server_uid.clone())); + self.open_dm(session, server_uid, uid); + } + + /// Open a private chat: in its session when one holds it, else from + /// the store. + pub(crate) fn open_dm(&mut self, session: Option, server_uid: Option, uid: &str) { + let live = session + .and_then(|s| self.sessions.get(&s)) + .is_some_and(|v| v.has_history() || v.state.voice == VoiceState::Connected); + self.social.dm.open = Some(Open { + session, + server_uid: server_uid.clone(), + uid: uid.to_owned(), + mail: None, + stored: !live, + }); + self.social.dm.mail = None; + vm::list::sync(&self.models.social.dm_lines, &[]); + let target = ChatTarget::Private(uid.to_owned()); + if let (true, Some(id)) = (live, session) { + if self.current != Some(id) { + self.select_server(id); + } + self.open_chat(target, true); + } else if let Some(server_uid) = server_uid.filter(|_| !self.demo_ui) { + let history = self.engine.history(); + let uid = uid.to_owned(); + self.engine.runtime().spawn(async move { + let query = PageQuery { limit: Some(200), ..PageQuery::default() }; + let page = history.page(&server_uid, &target, query, false).await; + later(move |app| app.stored_dm(&uid, page.unwrap_or_default())); + }); + } + self.navigate(|nav| nav.invoke_show(Page::Messages)); + self.refresh_chats(); + } + + /// The stored messages of a chat no session holds. + pub(crate) fn stored_dm(&mut self, uid: &str, messages: Vec) { + if !self.social.dm.open.as_ref().is_some_and(|o| o.stored && o.uid == uid) { + return; + } + let mut previous = None; + let lines: Vec<_> = messages + .iter() + .enumerate() + .map(|(i, m)| { + let ctx = vm::chat::LineCtx { + key: -1 - i as i32, + avatar: m + .message + .author_uid + .as_deref() + .map(|u| self.avatar_of(u)) + .unwrap_or_default(), + ..Default::default() + }; + let line = vm::chat::history_line(m, previous.as_ref(), &ctx); + previous = Some(vm::chat::Previous::of(&m.message)); + line + }) + .collect(); + vm::list::sync(&self.models.social.dm_lines, &lines); + self.refresh_dm(); + } + + /// Whether the private chat with `uid` in `session` is on screen. + pub(crate) fn dm_shown(&self, session: i64, uid: &str) -> bool { + let page = self.ui.upgrade().map(|ui| ui.global::