//! Chat: tabs per session (server, channels, private chats), their //! messages, and what a gateway adds to them (pins, reactions, topics). //! The chat strip shows the server's and the channels' tabs; a private chat //! is the current tab only while the messages page shows it (messages.rs). //! //! The engine keeps the history: [`Event::ChatHistory`] is an upsert of //! messages by their local id (see `voelin_core::history`), so a tab holds //! the messages it was given, ordered by `(ts_ms, id)`, and the lines of //! the selected tab are rebuilt from them and synced ([`Rows::sync`]), which //! touches only the rows that changed. Sessions the engine keeps no history //! for (it does not know the server yet) fall back to [`Event::Chat`]. //! //! Messages are read while their tab is on screen in the focused window //! ([`App::track_reading`]). A tab remembers the newest message read //! (`Tab::read`, kept in the store's `chat_reads`), counts what came after //! it, and when it comes on screen shows a "New" divider above the first //! of those until it is left. use std::collections::HashMap; use std::path::PathBuf; use slint::ComponentHandle; use voelin_core::gateway::Pin; use voelin_core::settings::CACHE_FETCH_IMAGES; use voelin_core::{ Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, TransferState, }; use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails}; use voelin_store::ChatRead; use crate::app::{App, Bridge, Nav, SessionView, Tab}; use crate::settings::UI_IMAGE_PREVIEW_KB; use crate::vm; use crate::vm::bbcode::LinkKind; use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem}; use crate::vm::chat::{LineCache, LineCtx, Previous}; use crate::vm::state::{Download, Msg, PinRow, store_target}; /// Where the server's welcome and host message keep what their lines were /// built from (`LineCache`), apart from the messages' ids. const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1]; /// What the server says to everyone who connects, with where its line keeps /// its parts: its welcome message, and its host message when that goes to /// the chat log. pub(crate) fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> { let host = details.host_message_mode == HostMessageMode::Log; [Some(&details.welcome_message), host.then_some(&details.host_message)] .into_iter() .zip(SERVER_LINES) .filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id))) .collect() } /// The text of the server's line `key` (-1, -2, …) of a server chat /// ([`App::lines_of`]), if `tab` is one. pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> { if tab.target != ChatTarget::Server || key >= 0 { return None; } server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) } /// "3 min ago", "yesterday", "12 Mar". fn ago(ts_ms: i64) -> String { let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() }; let minutes = (chrono::Utc::now() - then).num_minutes(); match minutes { i64::MIN..=0 => "just now".into(), 1 => "1 min ago".into(), 2..=59 => format!("{minutes} min ago"), 60..=119 => "1 hour ago".into(), 120..=1439 => format!("{} hours ago", minutes / 60), 1440..=2879 => "yesterday".into(), _ => then.with_timezone(&chrono::Local).format("%e %b").to_string().trim().into(), } } impl App { pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) { let Some(id) = self.state.current else { return }; let index = self.chat_tab(id, target); if focus { self.state.sessions.entry(id).or_default().focus_tab(index); self.prefetch_counts(); self.track_reading(); } self.refresh_chat(); self.refresh_servers(); } /// The index of `target`'s tab in session `id`, opened if new (the /// engine then sends its history). pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize { let peer = match &target { ChatTarget::Private(uid) => self.peer_name(uid, None), _ => String::new(), }; let view = self.state.sessions.entry(id).or_default(); if let Some(i) = view.tabs.iter().position(|t| t.target == target) { return i; } let title = vm::chat::tab_title(&view.presence, &target, &peer); let tab = view.new_tab(target.clone(), title); view.tabs.push(tab); if !self.demo_ui { self.engine.send(Command::OpenChat { session: id as u64, target }); } view.tabs.len() - 1 } /// The session's tab that tab `index` of the chat strip is /// (`Bridge.tabs`, [`vm::chat::strip`]). pub(crate) fn strip_tab(&self, index: i32) -> Option { self.models.strip.borrow().get(usize::try_from(index).ok()?).copied() } pub(crate) fn select_tab(&mut self, index: usize) { if let Some(view) = self.view_mut() && index < view.tabs.len() { view.set_current_tab(index); view.tabs[index].topic = None; } if let Some(id) = self.state.current { self.fetch_previews(id); } self.prefetch_counts(); self.track_reading(); self.refresh_chat(); self.refresh_servers(); } pub(crate) fn close_tab(&mut self, index: usize) { let Some(id) = self.state.current else { return }; let view = self.state.sessions.entry(id).or_default(); if index == 0 || index >= view.tabs.len() { return; } self.save_read(id, index); let tab = self.state.sessions.entry(id).or_default().remove_tab(index); self.engine.send(Command::CloseChat { session: id as u64, target: tab.target }); self.prefetch_counts(); self.track_reading(); self.refresh_chat(); self.refresh_servers(); } pub(crate) fn send_message(&mut self, text: String) { let Some(id) = self.state.current else { return }; let Some(view) = self.state.sessions.get(&id) else { return }; let target = view.tabs[view.current_tab].target.clone(); self.engine.send(Command::SendChat { session: id as u64, target, text }); } /// The index of `target`'s tab, opening one if it is new. fn tab_for( view: &mut SessionView, target: &ChatTarget, title: impl FnOnce() -> String, ) -> usize { match view.tabs.iter().position(|t| t.target == *target) { Some(i) => i, None => { let tab = view.new_tab(target.clone(), title()); view.tabs.push(tab); view.tabs.len() - 1 } } } /// A live message of a session without stored history: appended as it /// comes, without an id. pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) { let current = self.state.current == Some(id); let reading = self.reads_now(id); let new = !self.is_own(id, &message); let view = self.state.sessions.entry(id).or_default(); let title = vm::chat::tab_title(&view.presence, &message.target, &message.author_name); let index = Self::tab_for(view, &message.target, || title); let seen = reading && view.current_tab == index; let tab = &mut view.tabs[index]; let line = vm::chat::line(&message, tab.last.as_ref()); tab.last = Some(Previous::of(&message)); tab.lines.push(line); let counted = new && !seen; if counted { tab.unread += 1; } if current { self.refresh_chat(); } if counted { self.refresh_servers(); } self.studio_chat_changed(id, &message.target); } /// Messages the engine stored: added or updated by their local id. pub(crate) fn history_batch( &mut self, id: i64, target: &ChatTarget, messages: Vec, source: HistorySource, complete: bool, ) { let current = self.state.current == Some(id); let reading = self.reads_now(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.state.sessions.entry(id).or_default(); let author = messages.first().map_or("", |m| m.message.author_name.as_str()); let title = peer.unwrap_or_else(|| vm::chat::tab_title(&view.presence, target, author)); let index = Self::tab_for(view, target, || title); let seen = reading && view.current_tab == index; let own_client = view.state.own_client; let tab = &mut view.tabs[index]; if source == HistorySource::Gateway { tab.synced = true; } if source != HistorySource::Live { tab.loading = false; tab.complete = tab.complete || complete; } // Without a marker, what the tab holds was read. if tab.read.is_none() { tab.read = tab.newest(); } for message in messages { match tab.messages.iter().position(|m| m.message.id == message.id) { Some(i) => tab.messages[i].message = message, None => { let key = tab.take_key(); tab.messages.push(Msg { key, message }); } } } tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); // ...and so is a first stored page; a first live message is new. if tab.read.is_none() { tab.read = match source { HistorySource::Live => tab .messages .first() .map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))), _ => tab.newest(), }; } let unread = tab.unread; let own = |m: &ChatMessage| crate::social::own_message(&self.social.own_uids, own_client, m); if seen && source == HistorySource::Live { tab.catch_up(); } else { tab.count_unread(own); // What came while away (a stored or gateway page) gets the // divider also when its chat is on screen already. if seen { tab.enter(own); } } let counted = tab.unread != unread; if current { self.fetch_previews(id); self.refresh_chat(); } if counted { self.refresh_servers(); } self.studio_chat_changed(id, target); } /// The page of messages before the oldest one shown. pub(crate) fn load_older(&mut self) { let Some(id) = self.state.current else { return }; let Some(view) = self.state.sessions.get_mut(&id) else { return }; let tab = &mut view.tabs[view.current_tab]; if tab.loading || tab.complete { return; } tab.loading = true; let target = tab.target.clone(); let oldest = tab.messages.first().map(|m| &m.message); if self.demo_ui { // No engine answers in demo mode. crate::dev::answer_older(id, target, oldest.cloned()); } else { let before = oldest.map(|m| m.id); self.engine.send(Command::LoadOlderHistory { session: id as u64, target, before }); } self.refresh_chat(); } /// The lines of a tab's messages (`main`) or of its open topic, grouped /// and with everything the row shows (also the stream chat of the /// Stream Studio, studio/). The server chat starts with what the /// server says to everyone who connects ([`Self::server_lines`]). pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec { let messages = if main { &tab.messages } else { &tab.topic_messages }; let gateway = view.gateway_has(feature::PINS) || view.gateway_has(feature::REACTIONS) || view.gateway_has(feature::TOPICS); // Pictures on the web show only while pictures are fetched and // shown. let shown = self.prefs.get(&CACHE_FETCH_IMAGES) && self.prefs.get(&UI_IMAGE_PREVIEW_KB) > 0; let pictures = shown.then_some(&view.pictures); let cache = main.then_some(&tab.cache); let mut previous: Option = None; 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)); let topic = m .message .topic_id .filter(|_| tab.topic.is_none()) .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), gateway, marked: tab.marked == Some(m.message.id), topic, downloads: self.downloads_of(view, m.key), previews, pictures, cache, unread_start: main && tab.divider == Some(m.message.id), }; lines.push(( m.message.message.ts_ms, vm::chat::history_line(&m.message, previous.as_ref(), &ctx), )); previous = Some(Previous::of(&m.message.message)); } if let Some(cache) = cache { let ids = messages.iter().map(|m| m.message.id).chain(SERVER_LINES); cache.keep(ids, messages.len()); } // Pokes of a private chat's peer show among its messages. if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.state.current) { lines.extend(self.poke_lines(session, uid)); lines.sort_by_key(|(ts, _)| *ts); } let server = if main && tab.target == ChatTarget::Server { Self::server_lines(view, pictures, cache) } else { Vec::new() }; server.into_iter().chain(lines.into_iter().map(|(_, line)| line)).collect() } /// What the server says to everyone who connects ([`server_texts`]) as /// the first lines of the server chat: by the server, without reactions /// or pins. fn server_lines( view: &SessionView, pictures: Option<&HashMap>, cache: Option<&LineCache>, ) -> Vec { let name = match view.presence.server_name.as_str() { "" => "Server", name => name, }; server_texts(&view.presence.server) .into_iter() .enumerate() .map(|(i, (text, id))| { let ctx = LineCtx { key: -1 - i as i32, pictures, cache, ..Default::default() }; vm::chat::server_line(name, text, id, i > 0, &ctx) }) .collect() } /// The file cards of a message that has downloads running. fn downloads_of(&self, view: &SessionView, key: i32) -> Vec<(usize, FileItem)> { view.downloads .values() .filter(|d| d.key == key) .map(|d| { let (detail, status, progress) = match &d.state { TransferState::Requested => ("Starting…".to_owned(), "running", 0.0), TransferState::Started { size, offset } => ( format!( "{} of {}", vm::chat::size_text(*offset), vm::chat::size_text(*size) ), "running", if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 }, ), TransferState::Progress { done, size } => ( format!("{} of {}", vm::chat::size_text(*done), vm::chat::size_text(*size)), "running", if *size > 0 { *done as f32 / *size as f32 } else { 0.0 }, ), TransferState::Done { size, .. } => { (format!("Downloaded · {}", vm::chat::size_text(*size)), "done", 1.0) } TransferState::Failed(e) => (e.clone(), "failed", 0.0), TransferState::Cancelled => ("Cancelled".to_owned(), "failed", 0.0), }; ( d.index, FileItem { name: d.name.clone().into(), detail: detail.into(), index: d.index as i32, state: status.into(), progress, ..Default::default() }, ) }) .collect() } /// Tabs and the shown tab's messages. pub(crate) fn refresh_chat(&self) { let Some(ui) = self.ui.upgrade() else { return }; let bridge = ui.global::(); let Some(view) = self.view() else { self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]); *self.models.strip.borrow_mut() = vec![0]; bridge.set_current_tab(0); bridge.set_current_chat(0); let empty = self.models.no_chat.model(); if bridge.get_messages() != empty { bridge.set_messages(empty); } bridge.set_unread_index(-1); return; }; // Private chats are on the messages page, not in the strip. let (strip, current) = vm::chat::strip(view.tabs.iter().map(|t| &t.target), view.current_tab); let tabs: Vec = strip .iter() .map(|&i| &view.tabs[i]) .map(|t| { let (last, time) = t .messages .last() .map(|m| vm::chat::preview(&m.message.message)) .unwrap_or_default(); (t, last, time) }) .map(|(t, last, time)| { let channel = match t.target { ChatTarget::Channel(cid) => view.presence.channels.get(&cid), _ => None, }; ChatTab { last: last.into(), time: time.into(), title: t.title.clone().into(), name: vm::chat::tab_name(&t.title, &t.target).into(), kind: match t.target { ChatTarget::Server => 0, ChatTarget::Channel(_) => 1, ChatTarget::Private(_) => 2, }, id: match t.target { ChatTarget::Channel(cid) => cid as i32, _ => 0, }, unread: t.unread, topic: channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), banner: vm::tree::banner( &view.pictures, channel.and_then(|c| c.banner_gfx_url.as_deref()), ), banner_mode: channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)), } }) .collect(); self.models.tabs.sync(&tabs); *self.models.strip.borrow_mut() = strip; if bridge.get_current_tab() != current { bridge.set_current_tab(current); } bridge.set_current_chat(view.current_tab as i32); let tab = &view.tabs[view.current_tab]; // Sessions without stored history push their lines themselves. let mut divider = None; if view.has_history() { let lines = self.lines_of(view, tab, true); divider = lines.iter().position(|l| l.unread_start); tab.lines.sync(&lines); } let lines = tab.lines.model(); if bridge.get_messages() != lines { bridge.set_messages(lines); } // The "New" divider: how many came from there on, and when. let new = tab .divider .and_then(|d| tab.messages.iter().position(|m| m.message.id == d)) .map_or(&[][..], |i| &tab.messages[i..]); let session = self.state.current.unwrap_or_default(); let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count(); bridge.set_unread_index(divider.map_or(-1, |i| i as i32)); bridge.set_unread_count(count as i32); bridge.set_unread_since( new.first() .map(|m| vm::chat::since_time(m.message.message.ts_ms)) .unwrap_or_default() .into(), ); bridge.set_more_history(view.has_history() && !tab.complete); bridge.set_loading_history(tab.loading); bridge.set_local_history( view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY), ); bridge.set_has_pins(view.gateway_has(feature::PINS)); bridge.set_has_reactions(view.gateway_has(feature::REACTIONS)); bridge.set_has_topics(view.gateway_has(feature::TOPICS)); bridge.set_pins_loading(!tab.pins_loaded && view.gateway_has(feature::PINS)); bridge.set_topics_loading(!tab.topics_loaded && view.gateway_has(feature::TOPICS)); bridge.set_pins_count(vm::chat::known_count(tab.pins_loaded, tab.pins.len())); bridge.set_topics_count(vm::chat::known_count(tab.topics_loaded, tab.topics.len())); let pins: Vec = tab .pins .iter() .map(|p| { let avatar = p.message.message.author_uid.as_ref().and_then(|u| view.avatars.get(u)); let ctx = LineCtx { key: p.key, avatar: vm::avatar::image(avatar), gateway: true, ..Default::default() }; PinItem { line: vm::chat::history_line(&p.message, None, &ctx), by: format!("Pinned by {} · {}", p.by, vm::chat::time_of(p.ts_ms)).into(), } }) .collect(); self.models.pins.sync(&pins); let filter = self.state.topic_filter.trim().to_lowercase(); let now = chrono::Utc::now().timestamp_millis(); let topics: Vec = tab .topics .iter() .filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter)) .map(|t| vm::bridge::TopicItem { id: t.id as i32, title: t.title.clone().into(), creator: t.creator.name.clone().into(), detail: format!( "{} {} · by {}", t.message_count, if t.message_count == 1 { "message" } else { "messages" }, t.creator.name ) .into(), activity: format!("Last active {}", ago(t.last_activity_ms)).into(), recent: now - t.last_activity_ms < 3_600_000, archived: t.archived, }) .collect(); self.models.topics.sync(&topics); bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32)); bridge.set_topic_title( tab.topic .and_then(|t| tab.topics.iter().find(|i| i.id == t)) .map(|t| t.title.clone()) .unwrap_or_default() .into(), ); self.models.topic_messages.sync(&self.lines_of(view, tab, false)); } /// A link in a message was clicked (`masked`: its text shows something /// else, [`vm::bbcode::is_masked`]). A page on the web opens in the /// browser, a masked one once the user saw where it goes (Nav.link-open); /// a TeamSpeak link in Voelin ([`App::open_link`]). pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) { match vm::bbcode::classify_link(link) { LinkKind::Web(url) if masked => { if let Some(ui) = self.ui.upgrade() { let nav = ui.global::