From 2d6cbf66af021b803f333bb77c78509c0d4e2705 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 13:41:29 +0300 Subject: [PATCH] Split the social controller: the friends, the bell, the search and the social events into voelin-ui-vm social/logic.rs now has the contacts as rows (contact_item, people), the buttons of a contact and what they ask the window to do next, the bell (notify, the rows, read, clear, open), the search with what each result opens, and what an engine event does to the friends, the pokes, the offline messages and the notices (event). events::handle runs that first, then events::apply, so a front end has one entry point; Social is the state those keep, with what the messages page keeps as D for now. Refresh got people, conversations and dm, the host got dm_shown and now_ms, and Persist.Settings pages are told apart from the new notices. The Slint side (social/bind.rs) writes the Bridge, shows the desktop toasts and navigates. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-ui-vm/src/events/mod.rs | 45 +- crates/voelin-ui-vm/src/host.rs | 31 + crates/voelin-ui-vm/src/social/logic.rs | 1636 +++++++++++++++++ .../src/{social.rs => social/mod.rs} | 7 + crates/voelin-ui/src/app.rs | 10 - crates/voelin-ui/src/home.rs | 2 +- crates/voelin-ui/src/host.rs | 70 +- crates/voelin-ui/src/messages.rs | 14 +- crates/voelin-ui/src/social.rs | 993 ---------- crates/voelin-ui/src/social/bind.rs | 254 +++ crates/voelin-ui/src/social/mod.rs | 80 + docs/ui.md | 58 +- 12 files changed, 2137 insertions(+), 1063 deletions(-) create mode 100644 crates/voelin-ui-vm/src/social/logic.rs rename crates/voelin-ui-vm/src/{social.rs => social/mod.rs} (99%) delete mode 100644 crates/voelin-ui/src/social.rs create mode 100644 crates/voelin-ui/src/social/bind.rs create mode 100644 crates/voelin-ui/src/social/mod.rs diff --git a/crates/voelin-ui-vm/src/events/mod.rs b/crates/voelin-ui-vm/src/events/mod.rs index 233540e..c8f54c9 100644 --- a/crates/voelin-ui-vm/src/events/mod.rs +++ b/crates/voelin-ui-vm/src/events/mod.rs @@ -1,15 +1,19 @@ -//! What the engine's events do to the client's state. [`apply`] takes an -//! [`Event`], changes the [`AppState`] and returns an [`Update`]: what to -//! draw again, the status line, the commands for the engine, what to keep. -//! A front end calls it for every event and then does what the update says; -//! it has no dispatch of its own, so the Slint client and a GPUI one change -//! the state the same way. +//! What the engine's events do to the client's state. [`handle`] takes an +//! [`Event`], changes the [`AppState`] and the [`Social`] state and returns +//! an [`Update`]: what to draw again, the status line, the commands for the +//! engine, what to keep. A front end calls it for every event and then does +//! what the update says; it has no dispatch of its own, so the Slint client +//! and a GPUI one change the state the same way. [`apply`] is the part that +//! changes the [`AppState`] alone; [`handle`] first lets +//! [`crate::social::logic::event`] look at the event (the friends, the +//! pokes, the notices and the offline messages), which has to see the state +//! as it was before the event. //! //! In [`Update::rest`] come back the events whose state is not in the //! [`AppState`]: the Stream Studio's stream (`Host::studio_streams_to`), a -//! setting that changed (the settings service), and the friends, pokes and -//! offline messages that `social.rs` of the Slint client keeps. They move -//! here with their areas (docs/ui.md, "Controllers still to split"). +//! setting that changed (the settings service), and the offline messages +//! and their requests, which the messages page keeps (docs/ui.md, +//! "Controllers still to split"). mod gateway; @@ -25,13 +29,34 @@ use crate::host::{Cx, Host, Persist, Update}; use crate::previews::fetch_previews; use crate::servers::{AfterConnect, JoinStep, after_connect, join_password}; use crate::settings::LastVoice; +use crate::social::logic::Social; use crate::state::{AppState, Lines, SessionView}; use crate::streams::logic as streams; -/// Apply an event to the state; see the [module](self). +/// Apply an event to the [`AppState`]; see the [module](self). pub fn apply(state: &mut AppState, host: &dyn Host, event: Event) -> Update { let mut cx = Cx::new(host); dispatch(state, &mut cx, event); + finish(state, cx) +} + +/// Take an event in: what the social screens make of it first +/// ([`crate::social::logic::event`]), then [`apply`]. The one entry point +/// of a front end. +pub fn handle( + state: &mut AppState, + social: &mut Social, + host: &dyn Host, + event: Event, +) -> Update { + let mut cx = Cx::new(host); + crate::social::logic::event(state, social, &mut cx, &event); + dispatch(state, &mut cx, event); + finish(state, cx) +} + +/// The status line shows what the update says. +fn finish(state: &mut AppState, cx: Cx<'_>) -> Update { if let Some(text) = &cx.update.status { state.status.clone_from(text); } diff --git a/crates/voelin-ui-vm/src/host.rs b/crates/voelin-ui-vm/src/host.rs index c1209f4..67b674e 100644 --- a/crates/voelin-ui-vm/src/host.rs +++ b/crates/voelin-ui-vm/src/host.rs @@ -43,6 +43,15 @@ pub trait Host { /// Pictures on the web are fetched and shown (`cache.fetch_images`). fn fetch_images(&self) -> bool; + /// The private chat with this peer (unique id) of this session is on + /// screen, in the messages page. + fn dm_shown(&self, session: i64, uid: &str) -> bool; + + /// Now, in milliseconds since the epoch. + fn now_ms(&self) -> i64 { + crate::social::now_ms() + } + /// How far the chats of a server were read, from the store. fn chat_reads(&self, server_uid: &str) -> Result, String>; @@ -79,6 +88,13 @@ pub struct Refresh { pub events: bool, /// The gateway pages of the settings. pub gateways: bool, + /// The friends page, home's friends and activity, the block list. + pub people: bool, + /// The lists of direct messages and the offline messages (asked for + /// again when a voice connection came up). + pub conversations: bool, + /// The peer card of the open direct message. + pub dm: bool, } impl Refresh { @@ -94,6 +110,9 @@ impl Refresh { home: true, events: true, gateways: true, + people: true, + conversations: true, + dm: true, }; /// Whether nothing is to be drawn. @@ -279,6 +298,10 @@ pub(crate) mod testing { /// The session the Stream Studio streams to. pub(crate) studio: Option, pub(crate) limit: u64, + /// The private chat on screen: session and peer. + pub(crate) dm: Option<(i64, String)>, + /// What time it is. + pub(crate) now: Cell, /// What the store has: server unique id, its chats' reads. pub(crate) reads: HashMap>, /// What was stored. @@ -314,6 +337,14 @@ pub(crate) mod testing { false } + fn dm_shown(&self, session: i64, uid: &str) -> bool { + self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid) + } + + fn now_ms(&self) -> i64 { + self.now.get() + } + fn chat_reads(&self, server_uid: &str) -> Result, String> { Ok(self.reads.get(server_uid).cloned().unwrap_or_default()) } diff --git a/crates/voelin-ui-vm/src/social/logic.rs b/crates/voelin-ui-vm/src/social/logic.rs new file mode 100644 index 0000000..8427c67 --- /dev/null +++ b/crates/voelin-ui-vm/src/social/logic.rs @@ -0,0 +1,1636 @@ +//! People across servers: the contacts and where they are, the bell's +//! notifications, the pokes we got and the search (Ctrl+K), as the friends +//! page, home, the bell and the search show them, and what the user's moves +//! on them do. [`event`] is what an engine event does to the friends, the +//! pokes, the offline messages and the notices; it runs before +//! [`crate::events::apply`] sees the same event (the chat messages a history +//! batch brings are told apart from the ones already known only before the +//! batch is taken in). +//! +//! The functions change the [`AppState`] and the [`Social`] state and say in +//! the [`Cx`]'s update what to draw again and send; the desktop toasts, the +//! store and the window are the front end's. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use voelin_core::{Command, Contact, Event, FriendSpot, HistorySource, Relation}; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_store::Bookmark; + +use super::{ + NoticeKind, NoticeRequest, NoticeTarget, Poke, Spot, ago, avatar_of, found_channels, is_own, + matches, mentions, plain, server_name, spots_of, +}; +use crate::bridge::{ContactItem, NoticeItem, SearchItem}; +use crate::host::{Cx, Refresh}; +use crate::image::ImageRef; +use crate::settings::NotifyLevel; +use crate::state::{AppState, Lines}; + +/// The most notices the bell keeps. +const NOTICES: usize = 100; + +/// A notification of the bell. +#[derive(Clone, Debug, PartialEq)] +pub struct Notice { + /// What the rows call it. + pub key: i32, + /// What it is about. + pub kind: NoticeKind, + /// The headline. + pub title: String, + /// The line under it. + pub body: String, + /// When it came, in milliseconds since the epoch. + pub ts_ms: i64, + /// It was not opened or marked read. + pub unread: bool, + /// Where it leads. + pub target: NoticeTarget, + /// Whose avatar it shows (initials from the name). + pub name: String, + /// Whose avatar picture it shows. + pub uid: Option, +} + +/// A page of the settings, as the search leads to it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SettingsPage { + /// My Account. + Account, + /// Profiles (identities). + Profiles, + /// Appearance. + Appearance, + /// Voice and video. + Voice, + /// Streaming. + Streaming, + /// Devices. + Devices, + /// Notifications. + Notifications, + /// Privacy and safety. + Privacy, + /// Keybinds. + Keybinds, + /// Integrations (gateways, encoders). + Integrations, + /// Advanced. + Advanced, +} + +/// What a search result opens. +#[derive(Clone, Debug, PartialEq)] +pub enum Found { + /// A server. + Server(i64), + /// A channel (session, channel). + Channel(i64, u64), + /// Someone on a server (session, client, unique id). + Person(i64, u16, Option), + /// A contact, by unique id. + Contact(String), + /// A page of the settings. + Setting(SettingsPage), +} + +/// State of the home, friends, messages, bell and search screens, besides +/// the [`AppState`]. `D` is what the messages page keeps (`dm`), which its +/// front end owns for now. +#[derive(Clone, Debug, Default)] +pub struct Social { + /// Friends that are somewhere ([`Event::FriendPresence`]), and since when + /// (this run). + pub online_since: HashMap, + /// The pokes we got, oldest first. + pub pokes: Vec, + /// The bell's notices, newest first. + pub notices: Vec, + /// The key of the newest notice. + pub next_notice: i32, + /// The friends page's tab: 0 online, 1 all, 2 blocked. + pub friends_tab: i32, + /// The friends page's search. + pub contact_filter: String, + /// The contact the friends page shows in full. + pub selected: Option, + /// What the search results open, by index. + pub found: Vec, + /// The direct messages. + pub dm: D, +} + +/// The settings pages a search finds, with words that lead to them. +const SETTING_PAGES: [(&str, &str, SettingsPage); 11] = [ + ("My Account", "account identity unique id nickname myteamspeak", SettingsPage::Account), + ("Profiles", "identities import export security level", SettingsPage::Profiles), + ("Appearance", "theme dark light text size font layout", SettingsPage::Appearance), + ( + "Voice & Video", + "microphone speakers output input camera noise echo gain volume quality", + SettingsPage::Voice, + ), + ( + "Streaming", + "stream fps bitrate codec layers simulcast audio sources", + SettingsPage::Streaming, + ), + ("Devices", "devices microphone speakers camera screen capture", SettingsPage::Devices), + ("Notifications", "notifications bell mentions pokes alerts", SettingsPage::Notifications), + ("Privacy & Safety", "privacy block blocked pokes messages crash", SettingsPage::Privacy), + ("Keybinds", "keybinds push to talk hotkey shortcut transmit", SettingsPage::Keybinds), + ("Integrations", "gateway integrations encoders ffmpeg admin", SettingsPage::Integrations), + ("Advanced", "advanced srtp history cache logs settings experimental", SettingsPage::Advanced), +]; + +// Contacts. + +/// The title of what someone streams, if a directory or the voice +/// connection says. +fn stream_title(state: &AppState, spot: &Spot, uid: &str) -> Option { + let view = state.sessions.get(&spot.session)?; + view.streams + .iter() + .find(|s| s.streamer == spot.client) + .map(|s| s.name.clone()) + .or_else(|| { + view.extra.directory.iter().find(|e| e.streamer.uid == uid).map(|e| e.title.clone()) + }) + .filter(|t| !t.is_empty()) +} + +/// A contact for the screens. +pub fn contact_item( + state: &AppState, + social: &Social, + contact: &Contact, +) -> ContactItem { + let spots = spots_of(state, &contact.uid); + let first = spots.first(); + let name = if contact.nickname.is_empty() { + first + .map(|s| state.sessions[&s.session].nickname(s.client)) + .unwrap_or_else(|| contact.uid.chars().take(8).collect()) + } else { + contact.nickname.clone() + }; + let streaming = spots.iter().find(|s| s.streaming); + let status = match (first, streaming) { + (_, Some(s)) => match stream_title(state, s, &contact.uid) { + Some(title) => format!("Streaming {title}"), + None => "Streaming".into(), + }, + (Some(s), None) => match &s.away { + Some(m) if !m.is_empty() => format!("Away: {m}"), + Some(_) => "Away".into(), + None if s.channel_title.is_empty() => "Online".into(), + None => format!("In {}", s.channel_title), + }, + (None, None) => "Offline".into(), + }; + let place = match first { + Some(s) => s.server.clone(), + None if contact.last_seen_ms > 0 => match &contact.last_server { + Some(server) => format!("Last seen {} on {server}", ago(contact.last_seen_ms)), + None => format!("Last seen {}", ago(contact.last_seen_ms)), + }, + None => String::new(), + }; + let when = match first { + Some(_) => social.online_since.get(&contact.uid).map(|t| ago(*t)).unwrap_or_default(), + None => ago(contact.last_seen_ms), + }; + let since = chrono::DateTime::from_timestamp_millis(contact.added_ms) + .filter(|_| contact.added_ms > 0) + .map(|t| format!("Contact since {}", t.with_timezone(&chrono::Local).format("%-d %b %Y"))) + .unwrap_or_default(); + let spot_texts: Vec> = spots + .iter() + .map(|s| { + if s.channel_title.is_empty() { + s.server.clone().into() + } else { + format!("{} · {}", s.server, s.channel_title).into() + } + }) + .collect(); + ContactItem { + uid: contact.uid.clone().into(), + name: name.clone().into(), + initials: crate::avatar::initials(&name).into(), + tint: crate::avatar::tint(&name), + avatar: avatar_of(state, &contact.uid), + relation: contact.relation.as_str().into(), + online: first.is_some(), + away: first.is_some_and(|s| s.away.is_some()), + streaming: streaming.is_some(), + status: status.into(), + place: place.into(), + when: when.into(), + note: contact.note.clone().into(), + volume: contact.volume * 100.0, + muted: contact.muted, + since: since.into(), + spots: spot_texts, + reachable: spots.iter().any(|s| s.voice), + selected: social.selected.as_deref() == Some(contact.uid.as_str()), + } +} + +/// What the friends page, home and the block list show ([`people`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct People { + /// Home's friends who are somewhere, at most 20. + pub online: Vec, + /// Home's friends' activity: those online first, then by when they were + /// seen, at most 7. + pub activity: Vec, + /// The contacts we blocked. + pub blocked: Vec, + /// The friends page's list: its tab's, filtered by its search. + pub shown: Vec, + /// The selected contact in full (the default one without). + pub selected: ContactItem, + /// Contacts online, blocked ones not counted. + pub online_count: i32, + /// All the contacts. + pub all_count: i32, + /// The blocked ones. + pub blocked_count: i32, +} + +/// Contacts sorted for lists: online first (streaming, then present, then +/// away), then by name. +fn sort_contacts(items: &mut [ContactItem]) { + items.sort_by_key(|c| { + (!c.online, !c.streaming, c.away, &*c.relation != "friend", c.name.to_lowercase()) + }); +} + +/// The friends page, home's friends and activity, and the block list. +pub fn people(state: &AppState, social: &Social) -> People { + let mut all: Vec = + state.contacts.values().map(|c| contact_item(state, social, c)).collect(); + sort_contacts(&mut all); + let friends: Vec = + all.iter().filter(|c| &*c.relation == "friend").cloned().collect(); + let mut online: Vec = friends.iter().filter(|c| c.online).cloned().collect(); + online.truncate(20); + // Online friends first, then the others by when they were seen. + let mut activity = friends; + activity.sort_by_key(|c| { + let seen = state.contacts.get(c.uid.as_ref()).map_or(0, |c| c.last_seen_ms); + let since = social.online_since.get(c.uid.as_ref()).copied().unwrap_or(0); + (!c.online, !c.streaming, std::cmp::Reverse(if c.online { since } else { seen })) + }); + activity.truncate(7); + let blocked: Vec = + all.iter().filter(|c| &*c.relation == "blocked").cloned().collect(); + let shown = all + .iter() + .filter(|c| match social.friends_tab { + 0 => c.online && &*c.relation != "blocked", + 2 => &*c.relation == "blocked", + _ => true, + }) + .filter(|c| matches(&social.contact_filter, &[&c.name, &c.uid, &c.note])) + .cloned() + .collect(); + let selected = social + .selected + .as_ref() + .and_then(|uid| all.iter().find(|c| c.uid.as_ref() == uid)) + .cloned() + .unwrap_or_default(); + People { + online, + activity, + online_count: all.iter().filter(|c| c.online && &*c.relation != "blocked").count() as i32, + all_count: all.len() as i32, + blocked_count: blocked.len() as i32, + blocked, + shown, + selected, + } +} + +/// The friends page shows another tab. +pub fn set_friends_tab(social: &mut Social, cx: &mut Cx<'_>, tab: i32) { + social.friends_tab = tab; + cx.update.refresh.people = true; +} + +/// The friends page's search. +pub fn search_contacts(social: &mut Social, cx: &mut Cx<'_>, text: String) { + social.contact_filter = text; + cx.update.refresh.people = true; +} + +/// The friends page shows a contact in full (none: nobody). +pub fn select_contact(social: &mut Social, cx: &mut Cx<'_>, uid: String) { + social.selected = (!uid.is_empty()).then_some(uid); + cx.update.refresh.people = true; +} + +/// Change a contact (or make one of someone we see); the engine keeps it. +fn update_contact( + state: &mut AppState, + cx: &mut Cx<'_>, + uid: &str, + f: impl FnOnce(&mut Contact), +) { + let mut contact = state.contacts.get(uid).cloned().unwrap_or_else(|| { + let mut c = Contact::new(uid); + if let Some(s) = spots_of(state, uid).first() { + c.nickname = state.sessions[&s.session].nickname(s.client); + } + c + }); + f(&mut contact); + state.contacts.insert(uid.to_owned(), contact.clone()); + cx.send_real(Command::SetContact { contact: Box::new(contact) }); + let r = &mut cx.update.refresh; + (r.people, r.member_card, r.dm) = (true, true, true); +} + +/// What a button of a contact asks the front end to do next +/// ([`contact_action`]). +#[derive(Clone, Debug, PartialEq)] +pub enum ContactMove { + /// Open the conversation with the contact. + Message, + /// Ask what to poke the client with (session, client). + Poke(i64, u16), + /// Show the server of the spot and join its channel. + Join(Spot), + /// Show the server of the spot and watch its client's stream. + Watch(Spot), +} + +/// The buttons of a contact: "message", "poke", "join", "watch", "friend", +/// "block", "neutral", "remove", "mute". Those that change the contact do +/// it; the others come back as what to do next. +pub fn contact_action( + state: &mut AppState, + social: &mut Social, + cx: &mut Cx<'_>, + uid: &str, + action: &str, +) -> Option { + let spots = spots_of(state, uid); + match action { + "message" => return Some(ContactMove::Message), + "poke" => { + let Some(s) = spots.iter().find(|s| s.voice) else { + cx.status("Connect with voice to a server they are on to poke them."); + return None; + }; + return Some(ContactMove::Poke(s.session, s.client)); + } + "join" => return join_person(cx, &spots), + "watch" => return watch_person(state, cx, &spots), + "friend" => update_contact(state, cx, uid, |c| c.relation = Relation::Friend), + "block" => update_contact(state, cx, uid, |c| c.relation = Relation::Blocked), + "neutral" => update_contact(state, cx, uid, |c| c.relation = Relation::Neutral), + "mute" => update_contact(state, cx, uid, |c| c.muted = !c.muted), + "remove" => { + state.contacts.remove(uid); + if social.selected.as_deref() == Some(uid) { + social.selected = None; + } + cx.send_real(Command::RemoveContact { uid: uid.to_owned() }); + cx.update.refresh.people = true; + } + _ => {} + } + None +} + +/// Go to someone's channel: where we have voice, else where they are. +fn join_person(cx: &mut Cx<'_>, spots: &[Spot]) -> Option { + let Some(s) = spots.iter().find(|s| s.voice).or(spots.first()) else { + cx.status("They are not on any of your servers right now."); + return None; + }; + Some(ContactMove::Join(s.clone())) +} + +/// Watch someone's stream: from any channel of a server we are on with +/// voice (once the lookup brings it), else join them first and watch it +/// when it shows. +fn watch_person( + state: &mut AppState, + cx: &mut Cx<'_>, + spots: &[Spot], +) -> Option { + let s = spots.iter().find(|s| s.streaming)?; + if s.voice { + return Some(ContactMove::Watch(s.clone())); + } + state.pending_watch = Some((s.session, s.client)); + join_person(cx, std::slice::from_ref(s)) +} + +/// A contact's note, kept by the engine. +pub fn contact_note(state: &mut AppState, cx: &mut Cx<'_>, uid: &str, note: String) { + update_contact(state, cx, uid, |c| c.note = note); + cx.status("Note saved"); +} + +/// A contact's playback volume in percent, kept by the engine. +pub fn contact_volume(state: &mut AppState, cx: &mut Cx<'_>, uid: &str, percent: f32) { + update_contact(state, cx, uid, |c| c.volume = (percent / 100.0).max(0.0)); +} + +// The bell. + +/// A desktop notification to show ([`notify`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Toast { + /// The headline. + pub title: String, + /// The line under it. + pub body: String, + /// Pokes and messages are urgent. + pub urgent: bool, +} + +/// Add a notification to the bell as the setting of its kind (`level`) +/// says: not at all, in the bell, or in the bell and on the desktop (then a +/// toast comes back, except for the sample data of `VOELIN_DEMO_UI`, which +/// never reaches the desktop). +pub fn notify( + social: &mut Social, + level: NotifyLevel, + demo: bool, + request: NoticeRequest, + now_ms: i64, +) -> Option { + if level == NotifyLevel::Off { + return None; + } + let NoticeRequest { kind, title, body, target, name, uid } = request; + let toast = (level == NotifyLevel::Desktop && !demo).then(|| Toast { + title: title.clone(), + body: body.clone(), + urgent: kind == NoticeKind::Poke || kind == NoticeKind::Message, + }); + social.next_notice += 1; + social.notices.insert( + 0, + Notice { + key: social.next_notice, + kind, + title, + body, + ts_ms: now_ms, + unread: true, + target, + name, + uid, + }, + ); + social.notices.truncate(NOTICES); + toast +} + +/// What the bell and home's mentions show ([`notice_rows`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct NoticeRows { + /// The bell's notices, newest first. + pub notices: Vec, + /// Home's unread mentions, the newest three. + pub mentions: Vec, + /// How many notices are unread. + pub unread: i32, +} + +/// The bell's notices, and home's unread mentions (the newest three). +pub fn notice_rows(state: &AppState, social: &Social) -> NoticeRows { + let item = |n: &Notice| NoticeItem { + key: n.key, + kind: n.kind.name().into(), + title: n.title.clone().into(), + body: n.body.clone().into(), + time: ago(n.ts_ms).into(), + unread: n.unread, + initials: crate::avatar::initials(&n.name).into(), + tint: crate::avatar::tint(&n.name), + avatar: n.uid.as_deref().map(|u| avatar_of(state, u)).unwrap_or_default(), + }; + let notices = &social.notices; + NoticeRows { + notices: notices.iter().map(item).collect(), + mentions: notices + .iter() + .filter(|n| n.unread && n.kind == NoticeKind::Mention) + .take(3) + .map(item) + .collect(), + unread: notices.iter().filter(|n| n.unread).count() as i32, + } +} + +/// The bell's notices are all read. +pub fn mark_notices_read(social: &mut Social) { + for n in &mut social.notices { + n.unread = false; + } +} + +/// The bell is emptied. +pub fn clear_notices(social: &mut Social) { + social.notices.clear(); +} + +/// A notice was opened: it is read, and what it is about comes back for the +/// front end to show. A contact's notice selects the contact. +pub fn open_notice(social: &mut Social, cx: &mut Cx<'_>, key: i32) -> Option { + let n = social.notices.iter_mut().find(|n| n.key == key)?; + n.unread = false; + let target = n.target.clone(); + if let NoticeTarget::Contact(uid) = &target { + social.selected = Some(uid.clone()); + cx.update.refresh.people = true; + } + Some(target) +} + +// Engine events. + +/// Our nickname in a session. +fn own_nick(state: &AppState, session: i64) -> String { + let view = state.sessions.get(&session); + view.and_then(|v| v.state.own_client.map(|c| v.nickname(c))) + .or_else(|| state.bookmarks.iter().find(|b| b.id == session).map(|b| b.nickname.clone())) + .unwrap_or_default() +} + +/// A new chat message: a private message, or one that mentions us. The +/// notice it asks for, if any. +fn chat_notice( + state: &AppState, + cx: &Cx<'_>, + session: i64, + message: &ChatMessage, +) -> Option { + if message.blocked || is_own(state, session, message) { + return None; + } + let server = server_name(state, session); + match &message.target { + ChatTarget::Private(uid) => { + if cx.host.dm_shown(session, uid) { + return None; + } + Some(NoticeRequest { + kind: NoticeKind::Message, + title: message.author_name.clone(), + body: plain(&message.text), + target: NoticeTarget::Dm(session, uid.clone()), + name: message.author_name.clone(), + uid: Some(uid.clone()), + }) + } + target => { + if !mentions(&message.text, &own_nick(state, session)) { + return None; + } + let place = match target { + ChatTarget::Channel(cid) => state + .sessions + .get(&session) + .and_then(|v| v.presence.channels.get(cid)) + .map(|c| format!("{} · {server}", crate::tree::channel_title(c).0)) + .unwrap_or(server), + _ => server, + }; + Some(NoticeRequest { + kind: NoticeKind::Mention, + title: format!("{} mentioned you", message.author_name), + body: format!("{} — {place}", plain(&message.text)), + target: NoticeTarget::Chat(session, target.clone()), + name: message.author_name.clone(), + uid: message.author_uid.clone(), + }) + } + } +} + +/// Look at an event before [`crate::events::apply`] takes it in: +/// notifications, pokes, friends' whereabouts, offline messages. The parts +/// of the screen it touches are in the update. +pub fn event( + state: &mut AppState, + social: &mut Social, + cx: &mut Cx<'_>, + event: &Event, +) { + let mut touched = Refresh::default(); + match event { + Event::Presence { session, .. } => { + let view = state.sessions.entry(*session as i64).or_default(); + if view.extra.presence_since == 0 { + view.extra.presence_since = cx.host.now_ms(); + } + (touched.people, touched.home) = (true, true); + } + Event::State { session, state: now } => { + let id = *session as i64; + let was = state.sessions.get(&id).map(|v| v.state.voice); + if now.voice != voelin_core::VoiceState::Connected { + if let Some(view) = state.sessions.get_mut(&id) { + view.extra.inbox_asked = false; + } + } else if was != Some(voelin_core::VoiceState::Connected) { + touched.conversations = true; + } + (touched.people, touched.home) = (true, true); + } + Event::ServerInfo { session, backend, .. } => { + state.sessions.entry(*session as i64).or_default().extra.product = + backend.product.clone(); + (touched.people, touched.home) = (true, true); + } + Event::ContactsChanged { .. } | Event::AvatarReady { .. } => { + (touched.people, touched.home, touched.conversations) = (true, true, true); + } + Event::StreamsChanged { .. } => (touched.home, touched.people) = (true, true), + Event::FriendPresence { uid, sessions } => { + friend_presence(state, social, cx, uid, sessions); + } + Event::Poke { session, from_uid, from_name, message, .. } => { + let id = *session as i64; + social.pokes.push(Poke { + session: id, + uid: from_uid.clone(), + name: from_name.clone(), + message: message.clone(), + ts_ms: cx.host.now_ms(), + }); + let body = if message.is_empty() { + format!("on {}", server_name(state, id)) + } else { + message.clone() + }; + let target = match from_uid { + Some(uid) => NoticeTarget::Dm(id, uid.clone()), + None => NoticeTarget::Chat(id, ChatTarget::Server), + }; + cx.update.notices.push(NoticeRequest { + kind: NoticeKind::Poke, + title: format!("{from_name} poked you"), + body, + target, + name: from_name.clone(), + uid: from_uid.clone(), + }); + touched.conversations = true; + } + Event::Chat { session, message } => { + let id = *session as i64; + if !state.sessions.get(&id).is_some_and(|v| v.has_history()) { + cx.update.notices.extend(chat_notice(state, cx, id, message)); + touched.conversations = true; + } + } + Event::ChatHistory { session, target, messages, source, .. } => { + let id = *session as i64; + if *source == HistorySource::Live { + let known: HashSet = state + .sessions + .get(&id) + .and_then(|v| v.tabs.iter().find(|t| t.target == *target)) + .map(|t| t.messages.iter().map(|m| m.message.id).collect()) + .unwrap_or_default(); + for m in messages.iter().filter(|m| !known.contains(&m.id)) { + cx.update.notices.extend(chat_notice(state, cx, id, &m.message)); + } + } + touched.conversations = true; + } + Event::OfflineMessages { session, result: Ok(list), .. } => { + state.sessions.entry(*session as i64).or_default().extra.inbox = list.clone(); + touched.conversations = true; + } + Event::OfflineMessages { .. } | Event::OfflineMessage { .. } => { + touched.conversations = true; + } + _ => {} + } + let r = &mut cx.update.refresh; + r.people |= touched.people; + r.home |= touched.home; + r.conversations |= touched.conversations; +} + +/// A friend came online or left (everywhere). +fn friend_presence( + state: &AppState, + social: &mut Social, + cx: &mut Cx<'_>, + uid: &str, + sessions: &[FriendSpot], +) { + let was = social.online_since.contains_key(uid); + if sessions.is_empty() { + social.online_since.remove(uid); + } else if !was { + let now = cx.host.now_ms(); + social.online_since.insert(uid.to_owned(), now); + // Friends found in a session's first presence were there before. + let new = sessions.iter().all(|s| { + state.sessions.get(&(s.session as i64)).is_some_and(|v| { + v.extra.presence_since > 0 && now - v.extra.presence_since > 10_000 + }) + }); + if new { + let s = &sessions[0]; + let channel = state + .sessions + .get(&(s.session as i64)) + .and_then(|v| v.presence.channels.get(&s.channel)) + .map_or(s.channel_name.as_str(), |c| crate::tree::channel_title(c).0); + let server = server_name(state, s.session as i64); + let place = if channel.is_empty() { + format!("on {server}") + } else { + format!("on {server} · {channel}") + }; + cx.update.notices.push(NoticeRequest { + kind: NoticeKind::Friend, + title: format!("{} is online", s.nickname), + body: place, + target: NoticeTarget::Contact(uid.to_owned()), + name: s.nickname.clone(), + uid: Some(uid.to_owned()), + }); + } + } + let r = &mut cx.update.refresh; + (r.people, r.home) = (true, true); +} + +// The search (Ctrl+K). + +/// Add a group of results; at most 8, the first one with the group's name. +fn group(results: &mut Vec<(SearchItem, Found)>, header: &str, mut add: Vec<(SearchItem, Found)>) { + add.truncate(8); + for (i, (mut item, found)) in add.into_iter().enumerate() { + if i == 0 { + item.header = header.into(); + } + results.push((item, found)); + } +} + +/// The results for `text`: servers, channels, people, contacts, settings +/// pages ("@…": people only), and what each opens under the same index +/// (the front end keeps them in [`Social::found`]). `icon` gives a server's +/// icon. +pub fn search( + state: &AppState, + text: &str, + icon: impl Fn(&Bookmark) -> ImageRef, +) -> (Vec, Vec) { + let people_only = text.starts_with('@'); + let query = text.trim_start_matches('@').trim().to_owned(); + let mut results: Vec<(SearchItem, Found)> = Vec::new(); + if !people_only { + let servers = state + .bookmarks + .iter() + .zip(crate::servers::tints(&state.bookmarks)) + .filter(|(b, _)| matches(&query, &[&b.name, &b.address])) + .map(|(b, tint)| { + ( + SearchItem { + kind: "server".into(), + title: b.name.clone().into(), + subtitle: b.address.clone().into(), + initials: crate::avatar::initials(&b.name).into(), + tint, + avatar: icon(b), + ..Default::default() + }, + Found::Server(b.id), + ) + }) + .collect(); + group(&mut results, "Servers", servers); + } + if !query.is_empty() && !people_only { + let mut channels = Vec::new(); + for b in &state.bookmarks { + let Some(view) = state.sessions.get(&b.id) else { continue }; + for (channel, title) in found_channels(view.presence.channels.values(), &query) { + channels.push(( + SearchItem { + kind: "channel".into(), + title: title.into(), + subtitle: b.name.clone().into(), + ..Default::default() + }, + Found::Channel(b.id, channel), + )); + } + } + group(&mut results, "Channels", channels); + } + if !query.is_empty() || people_only { + let mut people = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for b in &state.bookmarks { + let Some(view) = state.sessions.get(&b.id) else { continue }; + for c in view.presence.clients.values() { + if c.is_query || Some(c.id) == view.state.own_client { + continue; + } + if !matches(&query, &[&c.nickname]) { + continue; + } + if let Some(uid) = &c.uid { + seen.insert(uid.clone()); + } + let channel = view + .presence + .channels + .get(&c.channel) + .map_or("", |ch| crate::tree::channel_title(ch).0); + people.push(( + SearchItem { + kind: "person".into(), + title: c.nickname.clone().into(), + subtitle: format!("{} · {channel}", b.name).into(), + initials: crate::avatar::initials(&c.nickname).into(), + tint: crate::avatar::tint(&c.nickname), + avatar: crate::avatar::image(view.avatar(c.id)), + ..Default::default() + }, + Found::Person(b.id, c.id, c.uid.clone()), + )); + } + } + for c in state.contacts.values() { + if seen.contains(&c.uid) || !matches(&query, &[&c.nickname, &c.note]) { + continue; + } + let name = if c.nickname.is_empty() { c.uid.clone() } else { c.nickname.clone() }; + people.push(( + SearchItem { + kind: "contact".into(), + title: name.clone().into(), + subtitle: match c.relation { + Relation::Friend => "Friend · offline".into(), + Relation::Blocked => "Blocked".into(), + Relation::Neutral => "Contact · offline".into(), + }, + initials: crate::avatar::initials(&name).into(), + tint: crate::avatar::tint(&name), + avatar: avatar_of(state, &c.uid), + ..Default::default() + }, + Found::Contact(c.uid.clone()), + )); + } + group(&mut results, "People", people); + } + if !people_only { + let pages = SETTING_PAGES + .iter() + .filter(|(title, words, _)| matches(&query, &[title, words])) + .map(|(title, _, page)| { + ( + SearchItem { + kind: "setting".into(), + title: (*title).into(), + subtitle: "Settings".into(), + ..Default::default() + }, + Found::Setting(*page), + ) + }) + .collect(); + group(&mut results, "Settings", pages); + } + results.into_iter().unzip() +} + +/// A search result was chosen: what it opens. A contact is selected on the +/// friends page. +pub fn search_activate(social: &mut Social, cx: &mut Cx<'_>, index: i32) -> Option { + let found = usize::try_from(index).ok().and_then(|i| social.found.get(i)).cloned()?; + if let Found::Contact(uid) = &found { + social.selected = Some(uid.clone()); + cx.update.refresh.people = true; + } + Some(found) +} + +#[cfg(test)] +mod tests { + use voelin_core::{BackendInfo, OfflineMessageInfo, VoiceState}; + use voelin_model::ClientInfo; + + use super::*; + use crate::events::handle; + use crate::host::testing::{Fake, State, presence, said, session, state}; + + type Soc = Social<()>; + + fn contact(uid: &str, nickname: &str, relation: Relation) -> Contact { + Contact { nickname: nickname.into(), relation, ..Contact::new(uid) } + } + + /// Alice (a friend, "alice=") is in Games with us; Bob (a friend) is + /// not on any server; Mallory is blocked and Carol neutral. + fn with_contacts() -> State { + let mut st = state(); + let view = st.sessions.entry(1).or_default(); + view.presence = presence(); + view.state = session(VoiceState::Connected, Some(2)); + for c in [ + contact("alice=", "Alice", Relation::Friend), + Contact { last_seen_ms: 5, ..contact("bob=", "Bob", Relation::Friend) }, + contact("mallory=", "Mallory", Relation::Blocked), + contact("carol=", "Carol", Relation::Neutral), + ] { + st.contacts.insert(c.uid.clone(), c); + } + st + } + + fn names(items: &[ContactItem]) -> Vec<&str> { + items.iter().map(|c| &*c.name).collect() + } + + #[test] + fn the_friends_page_lists_who_is_online_first() { + let st = with_contacts(); + let mut social = Soc::default(); + let p = people(&st, &social); + assert_eq!(names(&p.online), ["Alice"]); + assert_eq!(names(&p.blocked), ["Mallory"]); + assert_eq!((p.online_count, p.all_count, p.blocked_count), (1, 4, 1)); + // The online tab: those somewhere, not the blocked. + assert_eq!(names(&p.shown), ["Alice"]); + // Online friends first, then the others by name. + social.friends_tab = 1; + assert_eq!(names(&people(&st, &social).shown), ["Alice", "Bob", "Carol", "Mallory"]); + social.friends_tab = 2; + assert_eq!(names(&people(&st, &social).shown), ["Mallory"]); + // The search looks at the name, the unique id and the note. + social.friends_tab = 1; + social.contact_filter = "bob=".into(); + assert_eq!(names(&people(&st, &social).shown), ["Bob"]); + // The activity: online first, then by when they were seen. + let activity = people(&st, &social).activity; + assert_eq!(names(&activity), ["Alice", "Bob"]); + // The selected contact in full. + social.selected = Some("carol=".into()); + let p = people(&st, &social); + assert_eq!((&*p.selected.name, p.selected.selected), ("Carol", true)); + social.selected = Some("nobody=".into()); + assert_eq!(people(&st, &social).selected, ContactItem::default()); + } + + #[test] + fn a_contact_says_where_it_is() { + let mut st = with_contacts(); + let social = Soc::default(); + let item = |st: &State, uid: &str| contact_item(st, &social, &st.contacts[uid]); + let alice = item(&st, "alice="); + assert_eq!((&*alice.status, &*alice.place), ("In Games", "ts.example")); + assert!(alice.online && alice.reachable && !alice.streaming); + assert_eq!(alice.spots.iter().map(|s| &**s).collect::>(), ["ts.example · Games"]); + // Away, with and without a message; streaming wins. + let view = st.sessions.get_mut(&1).unwrap(); + let mut p = (*view.presence).clone(); + p.clients.get_mut(&11).unwrap().away = Some("brb".into()); + view.presence = Arc::new(p.clone()); + assert_eq!(&*item(&st, "alice=").status, "Away: brb"); + let view = st.sessions.get_mut(&1).unwrap(); + p.clients.get_mut(&11).unwrap().away = Some(String::new()); + view.presence = Arc::new(p.clone()); + assert_eq!(&*item(&st, "alice=").status, "Away"); + let view = st.sessions.get_mut(&1).unwrap(); + p.clients.get_mut(&11).unwrap().streaming = Some(true); + view.presence = Arc::new(p); + assert_eq!(&*item(&st, "alice=").status, "Streaming"); + // Offline: where they were last seen. + let bob = item(&st, "bob="); + assert_eq!((&*bob.status, bob.online), ("Offline", false)); + let seen = Contact { + last_seen_ms: 1, + last_server: Some("Home".into()), + ..contact("dave=", "", Relation::Neutral) + }; + let dave = contact_item(&st, &social, &seen); + assert!(dave.place.starts_with("Last seen ") && dave.place.ends_with(" on Home")); + // Without a nickname: the name where they are, else the uid's start. + let nameless = contact("alice=", "", Relation::Neutral); + assert_eq!(&*contact_item(&st, &social, &nameless).name, "Alice"); + let nameless = contact("0123456789abc=", "", Relation::Neutral); + assert_eq!(&*contact_item(&st, &social, &nameless).name, "01234567"); + } + + #[test] + fn the_buttons_of_a_contact() { + let mut st = with_contacts(); + let mut social = Soc::default(); + let host = Fake::default(); + let act = |st: &mut State, social: &mut Soc, uid: &str, action: &str| { + let mut cx = Cx::new(&host); + let next = contact_action(st, social, &mut cx, uid, action); + (next, cx.update) + }; + // Changing a contact tells the engine and the screens. + let (next, up) = act(&mut st, &mut social, "carol=", "friend"); + assert_eq!(next, None); + assert_eq!(st.contacts["carol="].relation, Relation::Friend); + assert!( + matches!(up.commands.as_slice(), [Command::SetContact { contact }] if contact.uid == "carol=") + ); + assert!(up.refresh.people && up.refresh.member_card && up.refresh.dm); + act(&mut st, &mut social, "carol=", "block"); + assert_eq!(st.contacts["carol="].relation, Relation::Blocked); + act(&mut st, &mut social, "carol=", "neutral"); + assert_eq!(st.contacts["carol="].relation, Relation::Neutral); + act(&mut st, &mut social, "carol=", "mute"); + assert!(st.contacts["carol="].muted); + act(&mut st, &mut social, "carol=", "mute"); + assert!(!st.contacts["carol="].muted); + // Someone we only see becomes a contact, named as seen. + let (_, up) = act(&mut st, &mut social, "me=", "friend"); + assert_eq!(st.contacts["me="].nickname, "Me"); + assert_eq!(up.commands.len(), 1); + // The sample data of VOELIN_DEMO_UI never reaches the engine. + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + contact_action(&mut st, &mut social, &mut cx, "carol=", "block"); + assert!(cx.update.commands.is_empty()); + assert_eq!(st.contacts["carol="].relation, Relation::Blocked); + // Removing forgets the contact, and deselects it. + social.selected = Some("carol=".into()); + let (_, up) = act(&mut st, &mut social, "carol=", "remove"); + assert!(!st.contacts.contains_key("carol=") && social.selected.is_none()); + assert!( + matches!(up.commands.as_slice(), [Command::RemoveContact { uid }] if uid == "carol=") + ); + // Moves for the front end: message, poke (where we have voice). + assert_eq!(act(&mut st, &mut social, "alice=", "message").0, Some(ContactMove::Message)); + assert_eq!(act(&mut st, &mut social, "alice=", "poke").0, Some(ContactMove::Poke(1, 11))); + let (next, up) = act(&mut st, &mut social, "bob=", "poke"); + assert_eq!(next, None); + assert_eq!( + up.status.as_deref(), + Some("Connect with voice to a server they are on to poke them.") + ); + let (next, up) = act(&mut st, &mut social, "bob=", "join"); + assert_eq!(next, None); + assert_eq!(up.status.as_deref(), Some("They are not on any of your servers right now.")); + let Some(ContactMove::Join(spot)) = act(&mut st, &mut social, "alice=", "join").0 else { + panic!("no move"); + }; + assert_eq!((spot.session, spot.client, spot.channel), (1, 11, 2)); + // Nothing to watch: nothing happens. + assert_eq!(act(&mut st, &mut social, "alice=", "watch").0, None); + assert_eq!(act(&mut st, &mut social, "alice=", "dance").0, None); + } + + #[test] + fn a_stream_is_watched_where_we_have_voice_or_after_joining() { + let mut st = with_contacts(); + let mut social = Soc::default(); + let host = Fake::default(); + let view = st.sessions.get_mut(&1).unwrap(); + let mut p = (*view.presence).clone(); + p.clients.get_mut(&11).unwrap().streaming = Some(true); + view.presence = Arc::new(p); + let mut cx = Cx::new(&host); + let next = contact_action(&mut st, &mut social, &mut cx, "alice=", "watch"); + assert!(matches!(next, Some(ContactMove::Watch(s)) if s.client == 11)); + assert_eq!(st.pending_watch, None); + // Not in voice there: join first, and watch when the stream shows. + st.sessions.get_mut(&1).unwrap().state = SessionStateExt::offline(); + let next = contact_action(&mut st, &mut social, &mut cx, "alice=", "watch"); + assert!(matches!(next, Some(ContactMove::Join(s)) if s.channel == 2)); + assert_eq!(st.pending_watch, Some((1, 11))); + } + + /// A session that sees the client without voice. + struct SessionStateExt; + impl SessionStateExt { + fn offline() -> voelin_core::SessionState { + voelin_core::SessionState { + observe: voelin_core::ObserveState::Observing, + ..Default::default() + } + } + } + + #[test] + fn the_note_and_the_volume_are_kept_by_the_engine() { + let mut st = with_contacts(); + let host = Fake::default(); + let mut cx = Cx::new(&host); + contact_note(&mut st, &mut cx, "alice=", "met at the raid".into()); + assert_eq!(st.contacts["alice="].note, "met at the raid"); + assert_eq!(cx.update.status.as_deref(), Some("Note saved")); + contact_volume(&mut st, &mut cx, "alice=", 150.0); + assert_eq!(st.contacts["alice="].volume, 1.5); + contact_volume(&mut st, &mut cx, "alice=", -20.0); + assert_eq!(st.contacts["alice="].volume, 0.0); + assert_eq!(cx.update.commands.len(), 3); + } + + fn request(kind: NoticeKind, title: &str) -> NoticeRequest { + NoticeRequest { + kind, + title: title.into(), + body: "body".into(), + target: NoticeTarget::Contact("alice=".into()), + name: "Alice".into(), + uid: Some("alice=".into()), + } + } + + #[test] + fn the_bell_adds_what_its_setting_says() { + let mut social = Soc::default(); + let poke = || request(NoticeKind::Poke, "Alice poked you"); + assert_eq!(notify(&mut social, NotifyLevel::Off, false, poke(), 1), None); + assert!(social.notices.is_empty()); + assert_eq!(notify(&mut social, NotifyLevel::App, false, poke(), 2), None); + // A toast on the desktop, urgent for pokes and messages. + let toast = notify(&mut social, NotifyLevel::Desktop, false, poke(), 3).unwrap(); + assert_eq!( + toast, + Toast { title: "Alice poked you".into(), body: "body".into(), urgent: true } + ); + let toast = + notify(&mut social, NotifyLevel::Desktop, false, request(NoticeKind::Event, "e"), 4); + assert_eq!(toast.map(|t| t.urgent), Some(false)); + // Not for the sample data. + assert_eq!(notify(&mut social, NotifyLevel::Desktop, true, poke(), 5), None); + // Newest first, with rising keys. + let keys: Vec<(i32, i64)> = social.notices.iter().map(|n| (n.key, n.ts_ms)).collect(); + assert_eq!(keys, [(4, 5), (3, 4), (2, 3), (1, 2)]); + // At most a hundred. + for i in 0..150 { + notify(&mut social, NotifyLevel::App, false, poke(), 10 + i); + } + assert_eq!(social.notices.len(), 100); + assert_eq!(social.notices[0].key, 154); + } + + #[test] + fn the_bell_shows_notices_and_the_newest_unread_mentions() { + let st = with_contacts(); + let mut social = Soc::default(); + let host = Fake::default(); + for (i, kind) in [ + NoticeKind::Mention, + NoticeKind::Poke, + NoticeKind::Mention, + NoticeKind::Mention, + NoticeKind::Mention, + ] + .into_iter() + .enumerate() + { + notify(&mut social, NotifyLevel::App, false, request(kind, &format!("n{i}")), 1); + } + let rows = notice_rows(&st, &social); + assert_eq!(rows.unread, 5); + assert_eq!(rows.notices.len(), 5); + assert_eq!(rows.notices[0].kind.as_ref(), "mention"); + assert_eq!(rows.mentions.iter().map(|n| &*n.title).collect::>(), ["n4", "n3", "n2"]); + // Opening one reads it; a contact's notice selects the contact. + let mut cx = Cx::new(&host); + let key = social.notices[0].key; + assert_eq!( + open_notice(&mut social, &mut cx, key), + Some(NoticeTarget::Contact("alice=".into())) + ); + assert_eq!(social.selected.as_deref(), Some("alice=")); + assert!(cx.update.refresh.people); + assert_eq!(notice_rows(&st, &social).unread, 4); + assert_eq!(open_notice(&mut social, &mut cx, 999), None); + mark_notices_read(&mut social); + let rows = notice_rows(&st, &social); + assert_eq!((rows.unread, rows.mentions.len()), (0, 0)); + clear_notices(&mut social); + assert!(notice_rows(&st, &social).notices.is_empty()); + } + + fn run( + st: &mut State, + social: &mut Soc, + host: &Fake, + tape: Vec, + ) -> Vec { + tape.into_iter().map(|e| handle(st, social, host, e)).collect() + } + + fn channel_message(author: &str, uid: &str, text: &str) -> ChatMessage { + ChatMessage { + target: ChatTarget::Channel(2), + author_name: author.into(), + author_uid: Some(uid.into()), + author_id: Some(11), + text: text.into(), + ts_ms: 1, + via_relay: false, + blocked: false, + } + } + + /// Pokes, mentions and private messages: who gets a notice in the bell. + #[test] + fn a_tape_of_pokes_and_messages() { + let mut st = state(); + let mut social = Soc::default(); + let host = Fake::default(); + host.now.set(5_000); + let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() }; + let ups = run( + &mut st, + &mut social, + &host, + vec![ + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }, + Event::ServerInfo { + session: 1, + name: "Nightfall Guild".into(), + backend, + capabilities: Default::default(), + }, + ], + ); + // Where the first presence came from, once. + assert_eq!(st.sessions[&1].extra.presence_since, 5_000); + assert_eq!(st.sessions[&1].extra.product, "TeamSpeak 6"); + for up in &ups { + assert!(up.refresh.people && up.refresh.home, "{:?}", up.refresh); + } + // Connecting with voice for the first time asks for the offline messages. + assert!(!ups[0].refresh.conversations && ups[1].refresh.conversations); + host.now.set(9_000); + run( + &mut st, + &mut social, + &host, + vec![Event::Presence { session: 1, presence: presence() }], + ); + assert_eq!(st.sessions[&1].extra.presence_since, 5_000); + + // A poke: in the list, in the bell, in the private chat with them. + let ups = run( + &mut st, + &mut social, + &host, + vec![ + Event::Poke { + session: 1, + from: 11, + from_uid: Some("alice=".into()), + from_name: "Alice".into(), + message: String::new(), + blocked: false, + }, + Event::Poke { + session: 1, + from: 11, + from_uid: None, + from_name: "Admin".into(), + message: "wake up".into(), + blocked: false, + }, + ], + ); + assert_eq!(social.pokes.len(), 2); + assert_eq!( + (social.pokes[0].ts_ms, social.pokes[0].uid.as_deref()), + (9_000, Some("alice=")) + ); + let n = &ups[0].notices[0]; + assert_eq!( + (n.kind, n.title.as_str(), n.body.as_str()), + (NoticeKind::Poke, "Alice poked you", "on Nightfall Guild") + ); + assert_eq!(n.target, NoticeTarget::Dm(1, "alice=".into())); + let n = &ups[1].notices[0]; + assert_eq!( + (n.body.as_str(), &n.target), + ("wake up", &NoticeTarget::Chat(1, ChatTarget::Server)) + ); + assert!(ups[0].refresh.conversations); + + // A message that names us in a channel, on a server the engine keeps + // no history of. + st.sessions.get_mut(&1).unwrap().state.server_uid = None; + st.own_uids.insert("me=".into()); + let ups = run( + &mut st, + &mut social, + &host, + vec![ + Event::Chat { session: 1, message: channel_message("Alice", "alice=", "hello") }, + Event::Chat { + session: 1, + message: channel_message("Alice", "alice=", "hi Me, you there?"), + }, + Event::Chat { session: 1, message: channel_message("Me", "me=", "hi Me") }, + ], + ); + assert!(ups[0].notices.is_empty(), "no mention"); + let n = &ups[1].notices[0]; + assert_eq!((n.kind, n.title.as_str()), (NoticeKind::Mention, "Alice mentioned you")); + assert_eq!(n.body, "hi Me, you there? — Games · Nightfall Guild"); + assert_eq!(n.target, NoticeTarget::Chat(1, ChatTarget::Channel(2))); + assert!(ups[2].notices.is_empty(), "our own message"); + } + + #[test] + fn private_messages_notify_unless_their_chat_is_on_screen() { + let mut st = state(); + let mut social = Soc::default(); + st.sessions.entry(1).or_default().presence = presence(); + let private = |blocked| { + let mut m = channel_message("Alice", "alice=", "psst"); + m.target = ChatTarget::Private("alice=".into()); + m.blocked = blocked; + Event::Chat { session: 1, message: m } + }; + let shown = Fake { dm: Some((1, "alice=".into())), ..Default::default() }; + let up = handle(&mut st, &mut social, &shown, private(false)); + assert!(up.notices.is_empty(), "the chat is on screen"); + let hidden = Fake::default(); + let up = handle(&mut st, &mut social, &hidden, private(false)); + let n = &up.notices[0]; + assert_eq!( + (n.kind, n.title.as_str(), n.body.as_str()), + (NoticeKind::Message, "Alice", "psst") + ); + assert_eq!(n.target, NoticeTarget::Dm(1, "alice=".into())); + assert_eq!(n.uid.as_deref(), Some("alice=")); + let up = handle(&mut st, &mut social, &hidden, private(true)); + assert!(up.notices.is_empty(), "blocked"); + // A server the engine keeps the history of tells of its messages + // through the history, not here. + st.sessions.get_mut(&1).unwrap().state = session(VoiceState::Connected, Some(2)); + let up = handle(&mut st, &mut social, &hidden, private(false)); + assert!(up.notices.is_empty() && !up.refresh.conversations); + } + + /// A live history batch notifies for the messages that are new only. + #[test] + fn a_live_history_batch_notifies_for_what_is_new() { + let mut st = state(); + let mut social = Soc::default(); + let host = Fake::default(); + st.sessions.entry(1).or_default().presence = presence(); + st.sessions.get_mut(&1).unwrap().state = session(VoiceState::Connected, Some(2)); + let batch = |messages, source| Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages, + source, + complete: true, + }; + let mention = |id, ts| said(id, ts, false, "Me, look"); + let ups = run( + &mut st, + &mut social, + &host, + vec![ + // What the history brings is not told of. + batch(vec![mention(1, 10)], HistorySource::Local), + batch(vec![mention(2, 20)], HistorySource::Live), + // The same again, and one more: only the new one. + batch(vec![mention(2, 20), mention(3, 30)], HistorySource::Live), + ], + ); + assert!(ups[0].notices.is_empty()); + assert_eq!(ups[1].notices.len(), 1); + assert_eq!(ups[2].notices.len(), 1, "{:?}", ups[2].notices); + assert!(ups.iter().all(|u| u.refresh.conversations)); + } + + #[test] + fn offline_messages_are_listed_and_their_screens_asked_to_follow() { + let mut st = state(); + let mut social = Soc::default(); + let host = Fake::default(); + let info = OfflineMessageInfo { + id: 4, + from_uid: "alice=".into(), + subject: "hi".into(), + ts_s: 1, + read: false, + }; + let ups = run( + &mut st, + &mut social, + &host, + vec![ + Event::OfflineMessages { session: 1, request: 1, result: Ok(vec![info.clone()]) }, + Event::OfflineMessages { session: 1, request: 2, result: Err("no".into()) }, + ], + ); + // An error keeps the list, and goes back to the front end to log. + assert_eq!(st.sessions[&1].extra.inbox, [info]); + assert!(ups.iter().all(|u| u.refresh.conversations)); + assert!(matches!(ups[1].rest, Some(Event::OfflineMessages { .. }))); + // Leaving voice lets the list be asked for again. + st.sessions.get_mut(&1).unwrap().extra.inbox_asked = true; + run( + &mut st, + &mut social, + &host, + vec![Event::State { session: 1, state: session(VoiceState::Disconnected, None) }], + ); + assert!(!st.sessions[&1].extra.inbox_asked); + } + + fn spot(session: i64, channel: &str) -> FriendSpot { + FriendSpot { + session: session as u64, + server_name: "Nightfall Guild".into(), + client: 11, + nickname: "Alice".into(), + channel: 2, + channel_name: channel.into(), + away: None, + streaming: false, + } + } + + /// A friend who comes online after the first presence of the session + /// was there for ten seconds is told of; one found in it is not. + #[test] + fn a_friend_coming_online_is_told_of_once() { + let mut st = with_contacts(); + let mut social = Soc::default(); + let host = Fake::default(); + let online = |sessions| Event::FriendPresence { uid: "alice=".into(), sessions }; + st.sessions.get_mut(&1).unwrap().extra.presence_since = 1_000; + // In the first seconds of the session: they were there before. + host.now.set(5_000); + let up = handle(&mut st, &mut social, &host, online(vec![spot(1, "Games")])); + assert!(up.notices.is_empty()); + assert_eq!(social.online_since["alice="], 5_000); + assert!(up.refresh.people && up.refresh.home); + // Gone, and back later: told. + handle(&mut st, &mut social, &host, online(vec![])); + assert!(!social.online_since.contains_key("alice=")); + host.now.set(60_000); + let up = handle(&mut st, &mut social, &host, online(vec![spot(1, "Games")])); + let n = &up.notices[0]; + assert_eq!((n.kind, n.title.as_str()), (NoticeKind::Friend, "Alice is online")); + assert_eq!(n.body, "on ts.example · Games"); + assert_eq!(n.target, NoticeTarget::Contact("alice=".into())); + // Seen again while online: not again. Without a known channel, the + // server alone. + let up = handle(&mut st, &mut social, &host, online(vec![spot(1, "Games")])); + assert!(up.notices.is_empty()); + handle(&mut st, &mut social, &host, online(vec![])); + let mut gone = spot(1, ""); + gone.channel = 99; + let up = handle(&mut st, &mut social, &host, online(vec![gone])); + assert_eq!(up.notices[0].body, "on ts.example"); + } + + #[test] + fn contacts_and_streams_redraw_the_people() { + let mut st = state(); + let mut social = Soc::default(); + let host = Fake::default(); + let ups = run( + &mut st, + &mut social, + &host, + vec![ + Event::ContactsChanged { contacts: Arc::new(vec![Contact::new("alice=")]) }, + Event::StreamsChanged { session: 1, streams: Vec::new() }, + Event::Talking { session: 1, client: 1, talking: true }, + ], + ); + assert!(ups[0].refresh.people && ups[0].refresh.home && ups[0].refresh.conversations); + assert!(ups[1].refresh.people && ups[1].refresh.home && !ups[1].refresh.conversations); + assert!(!ups[2].refresh.people && !ups[2].refresh.home); + assert!(st.contacts.contains_key("alice=")); + } + + fn clients(st: &mut State) { + let view = st.sessions.entry(1).or_default(); + let mut p = (*presence()).clone(); + p.clients.insert( + 12, + ClientInfo { + id: 12, + channel: 1, + nickname: "Alicia".into(), + is_query: false, + ..Default::default() + }, + ); + view.presence = Arc::new(p); + view.state = session(VoiceState::Connected, Some(2)); + } + + #[test] + fn the_search_groups_its_results_and_says_what_each_opens() { + let mut st = with_contacts(); + clients(&mut st); + let none = |_: &Bookmark| ImageRef::default(); + // Nothing typed: the servers and the settings pages. + let (items, found) = search(&st, "", none); + assert_eq!(items[0].kind.as_ref(), "server"); + assert_eq!(&*items[0].header, "Servers"); + // The settings pages are no more than eight in their group. + assert_eq!(items.len(), 1 + 8); + assert_eq!(&*items[1].header, "Settings"); + assert_eq!(found[0], Found::Server(1)); + assert_eq!(found.len(), items.len()); + // A name: channels, people (clients first, then contacts not seen) and pages. + let (items, found) = search(&st, "alic", none); + let kinds: Vec<&str> = items.iter().map(|i| &*i.kind).collect(); + assert_eq!(kinds, ["person", "person"]); + assert_eq!(items[0].header.as_ref(), "People"); + assert_eq!(items[1].header.as_ref(), ""); + let mut found = found.clone(); + found.sort_by_key(|f| format!("{f:?}")); + assert_eq!( + found, + [Found::Person(1, 11, Some("alice=".into())), Found::Person(1, 12, None),] + ); + // The contacts that are not on a server are listed after, once. + let (items, found) = search(&st, "mal", none); + assert_eq!(items.len(), 1); + assert_eq!((&*items[0].kind, &*items[0].subtitle), ("contact", "Blocked")); + assert_eq!(found, [Found::Contact("mallory=".into())]); + // A channel, a server, a page. + let (items, found) = search(&st, "games", none); + assert_eq!(&*items[0].kind, "channel"); + assert_eq!(&*items[0].subtitle, "ts.example"); + assert_eq!(found, [Found::Channel(1, 2)]); + let (items, found) = search(&st, "hotkey", none); + assert_eq!(found, [Found::Setting(SettingsPage::Keybinds)]); + assert_eq!(&*items[0].title, "Keybinds"); + // "@": people only, with an empty query, everyone. + let (items, _) = search(&st, "@", none); + assert!(items.iter().all(|i| matches!(&*i.kind, "person" | "contact"))); + assert!(items.len() >= 5); + let (items, _) = search(&st, "@alic", none); + assert_eq!(items.len(), 2); + // No more than eight in a group. + let mut many = state(); + many.bookmarks = (1..=12) + .map(|id| Bookmark { + id, + name: format!("S{id}"), + address: format!("s{id}"), + ..Default::default() + }) + .collect(); + let items = search(&many, "s", none).0; + assert_eq!(items.iter().filter(|i| &*i.kind == "server").count(), 8); + } + + #[test] + fn choosing_a_result() { + let mut social = Soc { + found: vec![Found::Server(1), Found::Contact("alice=".into())], + ..Default::default() + }; + let host = Fake::default(); + let mut cx = Cx::new(&host); + assert_eq!(search_activate(&mut social, &mut cx, 0), Some(Found::Server(1))); + assert!(social.selected.is_none() && !cx.update.refresh.people); + assert_eq!(search_activate(&mut social, &mut cx, 1), Some(Found::Contact("alice=".into()))); + assert_eq!(social.selected.as_deref(), Some("alice=")); + assert!(cx.update.refresh.people); + assert_eq!(search_activate(&mut social, &mut cx, 2), None); + assert_eq!(search_activate(&mut social, &mut cx, -1), None); + } + + #[test] + fn the_friends_page_state() { + let mut social = Soc::default(); + let host = Fake::default(); + let mut cx = Cx::new(&host); + set_friends_tab(&mut social, &mut cx, 2); + search_contacts(&mut social, &mut cx, "ali".into()); + select_contact(&mut social, &mut cx, "alice=".into()); + assert_eq!((social.friends_tab, social.contact_filter.as_str()), (2, "ali")); + assert_eq!(social.selected.as_deref(), Some("alice=")); + select_contact(&mut social, &mut cx, String::new()); + assert_eq!(social.selected, None); + assert!(cx.update.refresh.people); + } +} diff --git a/crates/voelin-ui-vm/src/social.rs b/crates/voelin-ui-vm/src/social/mod.rs similarity index 99% rename from crates/voelin-ui-vm/src/social.rs rename to crates/voelin-ui-vm/src/social/mod.rs index 1ff85dd..ca10266 100644 --- a/crates/voelin-ui-vm/src/social.rs +++ b/crates/voelin-ui-vm/src/social/mod.rs @@ -3,6 +3,8 @@ //! `vm::bbcode`), mentions, event dates, a poke's message, the private //! chats of the home sidebar; pure, so they are tested here. +pub mod logic; + use std::collections::HashSet; use chrono::{DateTime, Local, NaiveDateTime, TimeZone}; @@ -11,6 +13,11 @@ use voelin_model::{ChatMessage, ChatTarget}; use crate::state::AppState; +/// Now, in milliseconds since the epoch. +pub fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + /// What a notification of the bell is about. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NoticeKind { diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index f020e98..71caa38 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -657,16 +657,6 @@ impl App { self.page_setting_changed(key); } - /// An engine event. What it does to the state is in - /// `voelin_ui_vm::events::apply`; the window, the engine and the store - /// follow what that says ([`App::perform`]). The friends, pokes and offline - /// messages (`social.rs`) look at it before and after. - pub(crate) fn handle_event(&mut self, event: Event) { - let touched = self.social_event(&event); - self.apply_event(event); - self.social_refresh(touched); - } - /// Once a second. fn tick(&mut self) { self.tick_streams(); diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs index 6064391..da89475 100644 --- a/crates/voelin-ui/src/home.rs +++ b/crates/voelin-ui/src/home.rs @@ -1,7 +1,7 @@ //! The home page (design mockup 01): where we were with voice last, live //! streams on our servers, what is happening there (events, scheduled //! streams, server news), and the Library of recordings and clips. -//! Friends and the unread mentions are in `social.rs`, the recent chats in +//! Friends and the unread mentions are in `social/`, the recent chats in //! `messages.rs`. use std::path::{Path, PathBuf}; diff --git a/crates/voelin-ui/src/host.rs b/crates/voelin-ui/src/host.rs index 4e5f32d..7c1d6e4 100644 --- a/crates/voelin-ui/src/host.rs +++ b/crates/voelin-ui/src/host.rs @@ -10,8 +10,9 @@ use voelin_core::Event; use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings}; use voelin_store::{ChatRead, ChatTarget as StoredTarget, Store}; -use crate::app::{App, AppState, Bridge, MainWindow, Nav}; +use crate::app::{App, AppState, Bridge, MainWindow, Nav, Page}; use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB}; +use crate::social::Social; use crate::studio::StudioState; use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update}; @@ -20,6 +21,8 @@ use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update}; pub(crate) struct SlintHost<'a> { pub demo_ui: bool, pub watching: bool, + /// The private chat the messages page has open: session and peer. + pub dm: Option<(i64, String)>, pub ui: &'a slint::Weak, pub store: &'a Store, pub prefs: &'a Settings, @@ -55,6 +58,11 @@ impl Host for SlintHost<'_> { self.prefs.get(&CACHE_FETCH_IMAGES) } + fn dm_shown(&self, session: i64, uid: &str) -> bool { + self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid) + && self.ui.upgrade().is_some_and(|ui| ui.global::