diff --git a/crates/voelin-ui-vm/src/chat/logic.rs b/crates/voelin-ui-vm/src/chat/logic.rs index 89ee50f..a67ba5c 100644 --- a/crates/voelin-ui-vm/src/chat/logic.rs +++ b/crates/voelin-ui-vm/src/chat/logic.rs @@ -16,20 +16,23 @@ //! those until it is left. use std::collections::HashMap; +use std::path::{Path, PathBuf}; use voelin_core::gateway::Pin; use voelin_core::{ - Command, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, TransferState, + Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, + TransferState, }; use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; use voelin_model::{ChatMessage, ChatTarget}; use voelin_store::ChatRead; -use super::{Previous, tab_title}; +use super::{LineCache, LineCtx, Previous, SERVER_LINES, server_texts, tab_title}; +use crate::bridge::{ChatLine, ChatTab, FileItem, PinItem, TopicItem}; use crate::host::Cx; -use crate::previews::{fetch_previews, preview_progress}; -use crate::social::{is_own, own_message, peer_name}; -use crate::state::{AppState, Lines, Msg, PinRow, SessionView, store_target}; +use crate::previews::{fetch_previews, image_of, preview_progress}; +use crate::social::{Poke, is_own, own_message, peer_name, poke_lines}; +use crate::state::{AppState, Download, Lines, Msg, PinRow, SessionView, Tab, store_target}; /// The index of `target`'s tab in session `id`, opened if new (the engine /// then sends its history). @@ -497,6 +500,636 @@ pub fn transfer_progress( } } +// What the user does. + +/// A request to the current session's gateway. +fn gateway(state: &AppState, cx: &mut Cx<'_>, request: GatewayRequest) { + if let Some(id) = state.current { + cx.gateway_to(id, request); + } +} + +/// The message with this handle in the current chat. +fn message_of(state: &AppState, key: i32) -> Option<&HistoryMessage> { + let view = state.sessions.get(&state.current?)?; + view.tabs.get(view.current_tab)?.message(key) +} + +/// Show tab `index` of the current session. +pub fn select_tab(state: &mut AppState, cx: &mut Cx<'_>, index: usize) { + if let Some(id) = state.current { + let view = state.sessions.entry(id).or_default(); + if index < view.tabs.len() { + view.set_current_tab(index); + view.tabs[index].topic = None; + } + fetch_previews(state, cx, id); + } + prefetch_counts(state, cx); + track_reading(state, cx); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// Close tab `index` of the current session (never the server's chat). +pub fn close_tab(state: &mut AppState, cx: &mut Cx<'_>, index: usize) { + let Some(id) = state.current else { return }; + let view = state.sessions.entry(id).or_default(); + if index == 0 || index >= view.tabs.len() { + return; + } + save_read(state, cx, id, index); + let tab = state.sessions.entry(id).or_default().remove_tab(index); + cx.send(Command::CloseChat { session: id as u64, target: tab.target }); + prefetch_counts(state, cx); + track_reading(state, cx); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// Say `text` in the current chat. +pub fn send_message(state: &AppState, cx: &mut Cx<'_>, text: String) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get(&id) else { return }; + let target = view.tabs[view.current_tab].target.clone(); + cx.send(Command::SendChat { session: id as u64, target, text }); +} + +/// What the sample data answers an older page with (no engine does). +pub struct SampleOlder { + /// The session. + pub session: i64, + /// The chat. + pub target: ChatTarget, + /// The oldest message shown now. + pub oldest: Option, +} + +/// The page of messages before the oldest one shown is asked for; the +/// sample data's is answered by the front end. +pub fn load_older(state: &mut AppState, cx: &mut Cx<'_>) -> Option { + let id = state.current?; + let view = state.sessions.get_mut(&id)?; + let tab = &mut view.tabs[view.current_tab]; + if tab.loading || tab.complete { + return None; + } + tab.loading = true; + let target = tab.target.clone(); + let oldest = tab.messages.first().map(|m| &m.message); + cx.update.refresh.chat = true; + if cx.host.demo_ui() { + return Some(SampleOlder { session: id, target, oldest: oldest.cloned() }); + } + let before = oldest.map(|m| m.id); + cx.send(Command::LoadOlderHistory { session: id as u64, target, before }); + None +} + +/// The current chat is read (the bar over its messages): the divider goes. +pub fn mark_read(state: &mut AppState, cx: &mut Cx<'_>) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get_mut(&id) else { return }; + let index = view.current_tab; + let tab = &mut view.tabs[index]; + tab.divider = None; + tab.catch_up(); + save_read(state, cx, id, index); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// The chat on screen may have changed (the page, the window's focus). +pub fn chat_shown_changed(state: &mut AppState, cx: &mut Cx<'_>) { + if track_reading(state, cx) { + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; + } +} + +/// The window gained or lost the focus. +pub fn window_focused(state: &mut AppState, cx: &mut Cx<'_>, focused: bool) { + state.focused = focused; + chat_shown_changed(state, cx); +} + +/// Add or remove our reaction to a message. +pub fn react(state: &AppState, cx: &mut Cx<'_>, key: i32, emoji: String) { + let Some(message) = message_of(state, key) else { return }; + let Some(message_id) = message.remote_id else { return }; + let had = message.reactions.iter().any(|r| r.emoji == emoji && r.me); + let request = if had { + GatewayRequest::Unreact { message_id, emoji } + } else { + GatewayRequest::React { message_id, emoji } + }; + gateway(state, cx, request); +} + +/// Pin or unpin a message. +pub fn pin(state: &AppState, cx: &mut Cx<'_>, key: i32, on: bool) { + let Some(message) = message_of(state, key) else { return }; + let Some(message_id) = message.remote_id else { return }; + let request = + if on { GatewayRequest::Pin { message_id } } else { GatewayRequest::Unpin { message_id } }; + gateway(state, cx, request); +} + +/// Open the pins of the current chat (loading them once). +pub fn open_pins(state: &AppState, cx: &mut Cx<'_>) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + if !tab.pins_loaded { + let target = tab.target.clone(); + gateway(state, cx, GatewayRequest::Pins { target }); + } + cx.update.refresh.chat = true; +} + +/// Highlight a pinned message in the chat; the row of the line to scroll to, +/// if the message is loaded. +pub fn jump_to_pin(state: &mut AppState, cx: &mut Cx<'_>, key: i32) -> Option { + let id = state.current?; + let view = state.sessions.entry(id).or_default(); + let tab = &mut view.tabs[view.current_tab]; + tab.marked = tab.pins.iter().find(|p| p.key == key).map(|p| p.message.id); + // The message is in the chat, not in an open topic. + if tab.topic.take().is_some() { + tab.topic_messages.clear(); + } + // Older than what is loaded: only highlighted once it is. The server + // chat's first lines are the server's. + let row = tab.marked.and_then(|id| tab.messages.iter().position(|m| m.message.id == id)); + let first = match tab.target { + ChatTarget::Server => server_texts(&view.presence.server).len(), + _ => 0, + }; + cx.update.refresh.chat = true; + row.map(|row| row + first) +} + +/// The topics drawer's search. +pub fn search_topics(state: &mut AppState, cx: &mut Cx<'_>, text: String) { + if state.topic_filter != text { + state.topic_filter = text; + cx.update.refresh.chat = true; + } +} + +/// Open the topics of the current chat (loading them once). +pub fn open_topics(state: &AppState, cx: &mut Cx<'_>) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + if !tab.topics_loaded { + let target = tab.target.clone(); + gateway(state, cx, GatewayRequest::Topics { target, include_archived: false }); + } + cx.update.refresh.chat = true; +} + +/// Show a topic's messages (`-1` goes back to the chat). +pub fn open_topic(state: &mut AppState, cx: &mut Cx<'_>, topic: i32) { + let Some(id) = state.current else { return }; + let view = state.sessions.entry(id).or_default(); + let tab = &mut view.tabs[view.current_tab]; + tab.topic_messages.clear(); + tab.topic = (topic >= 0).then_some(i64::from(topic)); + let target = tab.target.clone(); + if let Some(topic) = tab.topic { + gateway( + state, + cx, + GatewayRequest::TopicHistory { target, topic, before: None, limit: None }, + ); + } + cx.update.refresh.chat = true; +} + +/// Say `text` in the open topic. +pub fn send_topic_message(state: &AppState, cx: &mut Cx<'_>, text: String) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + let (Some(topic), target) = (tab.topic, tab.target.clone()) else { return }; + gateway(state, cx, GatewayRequest::Post { target, text, topic: Some(topic) }); +} + +/// Start a topic from a message (`key` < 0: a standalone topic). +pub fn create_topic(state: &AppState, cx: &mut Cx<'_>, key: i32, title: String) { + let Some(view) = current_view(state) else { return }; + let target = view.tabs[view.current_tab].target.clone(); + let message_id = message_of(state, key).and_then(|m| m.remote_id); + gateway(state, cx, GatewayRequest::CreateTopic { target, title, message_id }); +} + +/// The current session's view. +fn current_view(state: &AppState) -> Option<&SessionView> { + state.sessions.get(&state.current?) +} + +/// Download a file a message links, into `dir`. +pub fn download_file( + state: &mut AppState, + cx: &mut Cx<'_>, + key: i32, + index: i32, + dir: &Path, +) { + let Some(id) = state.current else { return }; + let index = index.max(0) as usize; + let Some(file) = + message_of(state, key).and_then(|m| m.message.file_refs().into_iter().nth(index)) + else { + return; + }; + let path = dir.join(&file.name); + let view = state.sessions.entry(id).or_default(); + let transfer = view.next_transfer; + view.next_transfer += 1; + view.downloads.insert( + transfer, + Download { key, index, name: file.name.clone(), state: TransferState::Requested }, + ); + cx.send(Command::DownloadChatFile { + session: id as u64, + transfer, + file, + password: None, + to: DownloadTo::Path { path, resume: false }, + }); + cx.update.refresh.chat = true; +} + +/// Where a file attached to the current chat goes: its session and +/// channel; the reason when the chat is not a channel's. +pub fn attach_target(state: &AppState) -> Result, &'static str> { + let Some(id) = state.current else { return Ok(None) }; + let Some(view) = state.sessions.get(&id) else { return Ok(None) }; + match view.tabs[view.current_tab].target { + ChatTarget::Channel(channel) => Ok(Some((id, channel))), + _ => Err("Files can be attached to a channel's chat."), + } +} + +/// Upload a file into a channel and link it in the chat once it is up. +pub fn upload( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + channel: u64, + from: PathBuf, +) { + let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; + let view = state.sessions.entry(id).or_default(); + let transfer = view.next_transfer; + view.next_transfer += 1; + state.uploads.insert(transfer, (id, channel, name.clone())); + cx.send(Command::UploadFile { + session: id as u64, + transfer, + channel, + password: None, + path: format!("/{name}"), + from, + overwrite: true, + resume: false, + }); + cx.status(format!("Uploading {name}…")); +} + +// What is shown. + +/// What the lines of a chat need besides the state. +pub struct LinesFacts<'a> { + /// Pictures on the web show: they are fetched and previews are on. + pub pictures_shown: bool, + /// The pokes we got (they show among a private chat's messages). + pub pokes: &'a [Poke], +} + +/// 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). +/// The server chat starts with what the server says to everyone who +/// connects ([`server_lines`]). +pub fn lines_of( + state: &AppState, + view: &SessionView, + tab: &Tab, + main: bool, + facts: &LinesFacts<'_>, +) -> 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 pictures = facts.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)| image_of(view, f).map(|image| (i, image))) + .collect(); + let ctx = LineCtx { + key: m.key, + avatar: crate::avatar::image(avatar), + gateway, + marked: tab.marked == Some(m.message.id), + topic, + downloads: downloads_of(view, m.key), + previews, + pictures, + cache, + unread_start: main && tab.divider == Some(m.message.id), + }; + lines.push(( + m.message.message.ts_ms, + super::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, state.current) { + lines.extend(poke_lines(state, facts.pokes, session, uid)); + lines.sort_by_key(|(ts, _)| *ts); + } + let server = if main && tab.target == ChatTarget::Server { + 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() }; + super::server_line(name, text, id, i > 0, &ctx) + }) + .collect() +} + +/// The file cards of a message that has downloads running. +fn downloads_of(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 {}", super::size_text(*offset), super::size_text(*size)), + "running", + if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 }, + ), + TransferState::Progress { done, size } => ( + format!("{} of {}", super::size_text(*done), super::size_text(*size)), + "running", + if *size > 0 { *done as f32 / *size as f32 } else { 0.0 }, + ), + TransferState::Done { size, .. } => { + (format!("Downloaded · {}", super::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() +} + +/// "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(), + } +} + +/// What the chat view shows of the current session. +pub struct ChatView { + /// The chat strip's tabs (without private chats). + pub tabs: Vec, + /// Which of the session's tabs each of `tabs` is. + pub strip: Vec, + /// The strip's current tab (-1: the current tab is not in it). + pub current: i32, + /// The session's current tab. + pub current_chat: i32, + /// The lines of the current tab, built from its messages; none for a + /// session without stored history, whose tabs hold the lines they were + /// pushed. + pub lines: Option>, + /// The row of the "New" divider, -1 without one. + pub unread_index: i32, + /// How many came from there on. + pub unread_count: i32, + /// And since when. + pub unread_since: String, + /// Older messages can be asked for. + pub more_history: bool, + /// An older page was asked for. + pub loading_history: bool, + /// The chat is only what this device saw, though the gateway has history. + pub local_history: bool, + /// The gateway takes pins. + pub has_pins: bool, + /// The gateway takes reactions. + pub has_reactions: bool, + /// The gateway has topics. + pub has_topics: bool, + /// The pins were asked for and are not there yet. + pub pins_loading: bool, + /// The topics were asked for and are not there yet. + pub topics_loading: bool, + /// The header's pins count, -1 while unknown. + pub pins_count: i32, + /// The header's topics count, -1 while unknown. + pub topics_count: i32, + /// The pins drawer's rows. + pub pins: Vec, + /// The topics drawer's rows. + pub topics: Vec, + /// The open topic, -1 without one. + pub current_topic: i32, + /// Its title. + pub topic_title: String, + /// Its messages. + pub topic_lines: Vec, +} + +/// The tabs, the lines and the drawers of the current session's chat; +/// none when no server is shown. +pub fn chat_view(state: &AppState, facts: &LinesFacts<'_>) -> Option { + let view = current_view(state)?; + // Private chats are on the messages page, not in the strip. + let (strip, current) = super::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| super::preview(&m.message.message)).unwrap_or_default(); + 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: super::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: crate::tree::banner( + &view.pictures, + channel.and_then(|c| c.banner_gfx_url.as_deref()), + ), + banner_mode: channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)), + } + }) + .collect(); + let tab = &view.tabs[view.current_tab]; + // Sessions without stored history push their lines themselves. + let lines = view.has_history().then(|| lines_of(state, view, tab, true, facts)); + let divider = lines.as_ref().and_then(|l| l.iter().position(|l| l.unread_start)); + // 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 = state.current.unwrap_or_default(); + let count = new.iter().filter(|m| !is_own(state, session, &m.message.message)).count(); + 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: crate::avatar::image(avatar), + gateway: true, + ..Default::default() + }; + PinItem { + line: super::history_line(&p.message, None, &ctx), + by: format!("Pinned by {} · {}", p.by, super::time_of(p.ts_ms)).into(), + } + }) + .collect(); + let filter = 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| 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(); + Some(ChatView { + tabs, + strip, + current, + current_chat: view.current_tab as i32, + lines, + unread_index: divider.map_or(-1, |i| i as i32), + unread_count: count as i32, + unread_since: new + .first() + .map(|m| super::since_time(m.message.message.ts_ms)) + .unwrap_or_default(), + more_history: view.has_history() && !tab.complete, + loading_history: tab.loading, + local_history: view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY), + has_pins: view.gateway_has(feature::PINS), + has_reactions: view.gateway_has(feature::REACTIONS), + has_topics: view.gateway_has(feature::TOPICS), + pins_loading: !tab.pins_loaded && view.gateway_has(feature::PINS), + topics_loading: !tab.topics_loaded && view.gateway_has(feature::TOPICS), + pins_count: super::known_count(tab.pins_loaded, tab.pins.len()), + topics_count: super::known_count(tab.topics_loaded, tab.topics.len()), + pins, + topics, + current_topic: tab.topic.map_or(-1, |t| t as i32), + topic_title: tab + .topic + .and_then(|t| tab.topics.iter().find(|i| i.id == t)) + .map(|t| t.title.clone()) + .unwrap_or_default(), + topic_lines: lines_of(state, view, tab, false, facts), + }) +} + /// What a failed gateway request tells the user. What the app asked for by /// itself (history, lists, subscriptions) fails quietly; what the user did /// says so in plain words, never the gateway's; the gateway's own @@ -549,7 +1182,21 @@ fn upsert_topic(topics: &mut Vec, topic: TopicInfo) { #[cfg(test)] mod tests { + use voelin_core::Event; + use super::*; + use crate::events::apply; + use crate::host::testing::{Fake, State, presence, said, session, state}; + use voelin_core::VoiceState; + + #[test] + fn relative_times() { + let now = chrono::Utc::now().timestamp_millis(); + assert_eq!(ago(now), "just now"); + assert_eq!(ago(now - 3 * 60_000), "3 min ago"); + assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago"); + assert_eq!(ago(now - 36 * 3_600_000), "yesterday"); + } #[test] fn failures_say_what_the_user_did_never_the_gateway() { @@ -571,4 +1218,317 @@ mod tests { Some("config_set: bad value") ); } + + /// Server 1 connected into Games with its chat (messages 6 and 7 of + /// Alice, a gateway with pins, reactions and topics), the Games tab + /// shown. + fn games() -> (State, Fake) { + let mut st = state(); + let host = Fake::default(); + for event in [ + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(6, 190, false, "hi"), said(7, 200, false, "there")], + source: HistorySource::Local, + complete: false, + }, + ] { + apply(&mut st, &host, event); + } + st.sessions.get_mut(&1).unwrap().gateway_caps = + [feature::PINS, feature::REACTIONS, feature::TOPICS].map(String::from).into(); + (st, host) + } + + fn commands<'a>(cx: &'a Cx<'_>) -> Vec<&'a Command> { + cx.update.commands.iter().collect() + } + + /// Tabs open, are selected and closed (never the server's), and a message + /// goes to the chat on screen. + #[test] + fn tabs_open_are_selected_and_closed() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + open_chat(&mut st, &mut cx, ChatTarget::Channel(1), true); + let view = &st.sessions[&1]; + assert_eq!(view.tabs.len(), 3); + assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(1)); + assert!( + matches!(commands(&cx).as_slice(), [Command::OpenChat { session: 1, target }, ..] if target == &ChatTarget::Channel(1)) + ); + // The gateway's pins and topics of the chat are asked for once. + assert!(commands(&cx).iter().any(|c| matches!( + c, + Command::Gateway { + request: GatewayRequest::Pins { target: ChatTarget::Channel(1) }, + .. + } + ))); + let mut cx = Cx::new(&host); + send_message(&st, &mut cx, "hello".into()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::SendChat { session: 1, target: ChatTarget::Channel(1), text }] if text == "hello" + )); + // Back to Games; a topic that was open is closed with the move. + st.sessions.get_mut(&1).unwrap().tabs[1].topic = Some(3); + let mut cx = Cx::new(&host); + select_tab(&mut st, &mut cx, 1); + assert_eq!(st.sessions[&1].current_tab, 1); + assert_eq!(st.sessions[&1].tabs[1].topic, None); + assert!(cx.update.refresh.chat && cx.update.refresh.servers); + // The server's chat stays; the Lobby's goes, and the chat on screen with it. + let mut cx = Cx::new(&host); + close_tab(&mut st, &mut cx, 0); + assert_eq!(st.sessions[&1].tabs.len(), 3); + st.sessions.get_mut(&1).unwrap().set_current_tab(2); + close_tab(&mut st, &mut cx, 2); + assert_eq!(st.sessions[&1].tabs.len(), 2); + assert!(matches!( + commands(&cx).first(), + Some(Command::CloseChat { session: 1, target: ChatTarget::Channel(1) }) + )); + assert_eq!( + st.sessions[&1].tabs[st.sessions[&1].current_tab].target, + ChatTarget::Channel(2) + ); + } + + /// What the chat view shows: the strip, the lines, the divider and the + /// drawers' counts. + #[test] + fn the_chat_view_has_the_strip_the_divider_and_the_counts() { + let (mut st, host) = games(); + let facts = LinesFacts { pictures_shown: false, pokes: &[] }; + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!(chat.strip, [0, 1]); + assert_eq!(chat.tabs.iter().map(|t| &*t.title).collect::>(), ["Server", "Games"]); + assert_eq!((chat.current, chat.current_chat), (1, 1)); + assert_eq!(chat.tabs[1].last.as_ref(), "Alice: there"); + // The stored page has the engine's history: its lines are rebuilt from + // the messages (and the server chat starts with the server's own). + assert_eq!(chat.lines.as_ref().map(Vec::len), Some(2)); + assert!(chat.has_pins && chat.has_reactions && chat.has_topics); + assert_eq!((chat.pins_count, chat.topics_count), (-1, -1)); + assert!(chat.pins_loading && chat.topics_loading); + assert_eq!((chat.unread_index, chat.unread_count), (-1, 0)); + assert!(chat.more_history && !chat.loading_history); + + // A message while away is new; on screen it gets the divider. + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(8, 300, false, "new")], + source: HistorySource::Live, + complete: false, + }, + ); + host.shown.set(true); + let mut cx = Cx::new(&host); + assert!(track_reading(&mut st, &mut cx)); + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!((chat.unread_index, chat.unread_count), (2, 1)); + assert!(!chat.unread_since.is_empty()); + assert!(chat.lines.as_ref().unwrap()[2].unread_start); + // Marked read: the divider goes and the position is kept. + let mut cx = Cx::new(&host); + mark_read(&mut st, &mut cx); + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!((chat.unread_index, chat.unread_count), (-1, 0)); + assert_eq!(host.written.borrow().last().map(|w| (w.2.ts_ms, w.2.id)), Some((300, 8))); + + // Nothing on screen without a server. + st.current = None; + assert!(chat_view(&st, &facts).is_none()); + } + + /// Pins and topics: asked for when opened, the topic's messages, the + /// highlight of a pinned message, reactions. + #[test] + fn pins_topics_and_reactions() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + open_pins(&st, &mut cx); + open_topics(&st, &mut cx); + assert!(matches!( + commands(&cx).as_slice(), + [ + Command::Gateway { request: GatewayRequest::Pins { .. }, .. }, + Command::Gateway { + request: GatewayRequest::Topics { include_archived: false, .. }, + .. + }, + ] + )); + assert!(cx.update.refresh.chat); + // A pin to jump to. + let pinned = Pin { + message: said(6, 190, false, "hi"), + by: voelin_gateway_proto::UserRef { uid: "alice=".into(), name: "Alice".into() }, + ts_ms: 10, + }; + let mut cx = Cx::new(&host); + gateway_update( + &mut st, + &mut cx, + 1, + GatewayUpdate::Pins { target: ChatTarget::Channel(2), pins: vec![pinned] }, + ); + let key = st.sessions[&1].tabs[1].pins[0].key; + let mut cx = Cx::new(&host); + assert_eq!(jump_to_pin(&mut st, &mut cx, key), Some(0)); + assert_eq!(st.sessions[&1].tabs[1].marked, Some(6)); + // A pin of a message that is not loaded is highlighted once it is. + assert_eq!(jump_to_pin(&mut st, &mut cx, 999), None); + assert_eq!(st.sessions[&1].tabs[1].marked, None); + // A topic: its history is asked for, going back closes it. + let mut cx = Cx::new(&host); + open_topic(&mut st, &mut cx, 5); + assert_eq!(st.sessions[&1].tabs[1].topic, Some(5)); + assert!(matches!( + commands(&cx).as_slice(), + [Command::Gateway { request: GatewayRequest::TopicHistory { topic: 5, .. }, .. }] + )); + let mut cx = Cx::new(&host); + send_topic_message(&st, &mut cx, "in the topic".into()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::Gateway { request: GatewayRequest::Post { topic: Some(5), .. }, .. }] + )); + open_topic(&mut st, &mut cx, -1); + assert_eq!(st.sessions[&1].tabs[1].topic, None); + // The search of the drawer redraws only when the text changes. + let mut cx = Cx::new(&host); + search_topics(&mut st, &mut cx, "ban".into()); + search_topics(&mut st, &mut cx, "ban".into()); + assert_eq!(st.topic_filter, "ban"); + // Reactions and pins go by the gateway's id of the message. + let mut cx = Cx::new(&host); + let key = st.sessions[&1].tabs[1].messages[0].key; + react(&st, &mut cx, key, "👍".into()); + pin(&st, &mut cx, key, true); + create_topic(&st, &mut cx, key, "Plans".into()); + assert!(matches!( + commands(&cx).as_slice(), + [ + Command::Gateway { request: GatewayRequest::React { message_id: 1006, .. }, .. }, + Command::Gateway { request: GatewayRequest::Pin { message_id: 1006 }, .. }, + Command::Gateway { + request: GatewayRequest::CreateTopic { message_id: Some(1006), .. }, + .. + }, + ] + )); + // The sample sessions have no gateway to ask. + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + react(&st, &mut cx, key, "👍".into()); + assert!(cx.update.commands.is_empty()); + } + + /// Older pages are asked for once; files are downloaded into a folder and + /// uploaded from the composer. + #[test] + fn older_pages_and_files() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + assert!(load_older(&mut st, &mut cx).is_none()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::LoadOlderHistory { session: 1, before: Some(6), .. }] + )); + assert!(st.sessions[&1].tabs[1].loading); + // Asked: not again before the answer. + let mut cx = Cx::new(&host); + assert!(load_older(&mut st, &mut cx).is_none() && cx.update.commands.is_empty()); + // The sample data answers itself. + st.sessions.get_mut(&1).unwrap().tabs[1].loading = false; + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + let sample = load_older(&mut st, &mut cx).unwrap(); + assert_eq!((sample.session, sample.oldest.map(|m| m.id)), (1, Some(6))); + assert!(cx.update.commands.is_empty()); + + // A file the message links: downloaded into the folder, shown as it runs. + let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]"; + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(9, 400, false, link)], + source: HistorySource::Live, + complete: false, + }, + ); + let key = st.sessions[&1].tabs[1].messages.last().unwrap().key; + let mut cx = Cx::new(&host); + download_file(&mut st, &mut cx, key, 0, Path::new("/home/me/Downloads")); + assert!(matches!( + commands(&cx).as_slice(), + [Command::DownloadChatFile { session: 1, transfer: 1, to: DownloadTo::Path { path, .. }, .. }] + if path == Path::new("/home/me/Downloads/a.png") + )); + let facts = LinesFacts { pictures_shown: false, pokes: &[] }; + let chat = chat_view(&st, &facts).unwrap(); + let line = chat.lines.unwrap().pop().unwrap(); + assert_eq!(line.files.len(), 1); + assert_eq!((&*line.files[0].state, &*line.files[0].detail), ("running", "Starting…")); + // Attaching: a channel's chat takes files, the server's does not. + assert_eq!(attach_target(&st), Ok(Some((1, 2)))); + st.sessions.get_mut(&1).unwrap().set_current_tab(0); + assert!(attach_target(&st).is_err()); + let mut cx = Cx::new(&host); + upload(&mut st, &mut cx, 1, 2, PathBuf::from("/tmp/notes.txt")); + assert!(matches!( + commands(&cx).as_slice(), + [Command::UploadFile { session: 1, channel: 2, path, .. }] if path == "/notes.txt" + )); + assert_eq!(cx.update.status.as_deref(), Some("Uploading notes.txt…")); + assert_eq!(st.uploads.len(), 1); + } + + /// A private chat shows the pokes of its peer among its messages. + #[test] + fn a_private_chat_has_the_pokes_of_its_peer() { + let (mut st, host) = games(); + let direct = said(20, 1000, false, "psst"); + let mut direct_message = direct.clone(); + direct_message.message.target = ChatTarget::Private("alice=".into()); + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Private("alice=".into()), + messages: vec![direct_message], + source: HistorySource::Local, + complete: true, + }, + ); + let pokes = [Poke { + session: 1, + uid: Some("alice=".into()), + name: "Alice".into(), + message: "hey".into(), + ts_ms: 500, + }]; + let view = &st.sessions[&1]; + let tab = view.tabs.iter().find(|t| t.is_private()).unwrap(); + let facts = LinesFacts { pictures_shown: false, pokes: &pokes }; + let lines = lines_of(&st, view, tab, true, &facts); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0].key, -1_000_000, "the poke came first"); + let none = + lines_of(&st, view, tab, true, &LinesFacts { pictures_shown: false, pokes: &[] }); + assert_eq!(none.len(), 1); + } } diff --git a/crates/voelin-ui-vm/src/events/tests.rs b/crates/voelin-ui-vm/src/events/tests.rs index 41fc7c3..0cb5e7e 100644 --- a/crates/voelin-ui-vm/src/events/tests.rs +++ b/crates/voelin-ui-vm/src/events/tests.rs @@ -9,97 +9,19 @@ use voelin_core::StreamState; use voelin_core::gateway::Pin; use voelin_core::stream::StreamInfo; use voelin_core::{ - AudioSettings, BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, - HistorySource, JoinFailure, ObserveState, SessionState, Source, TransferState, VoiceState, + BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, + JoinFailure, TransferState, VoiceState, }; use voelin_gateway_proto::{UserRef, feature}; -use voelin_model::{ - Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails, -}; -use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, MessageSource}; +use voelin_model::{Capabilities, ChatMessage, ChatTarget}; +use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget}; use super::*; -use crate::bridge::ChatLine; use crate::host::Refresh; use crate::host::testing::Fake; -use crate::settings::{ClientPlayback, ClientPlaybackMap, LastVoice, UiSettings}; +use crate::settings::{ClientPlayback, LastVoice}; -type State = AppState>; - -fn state() -> State { - let bookmark = Bookmark { - id: 1, - name: "ts.example".into(), - address: "ts.example".into(), - nickname: "Me".into(), - ..Default::default() - }; - AppState::new( - vec![bookmark], - UiSettings::default(), - AudioSettings::default(), - ClientPlaybackMap::new(), - ) -} - -fn session(voice: VoiceState, own_channel: Option) -> SessionState { - let connected = voice == VoiceState::Connected; - SessionState { - voice, - observe: ObserveState::Off, - presence_source: connected.then_some(Source::Voice), - own_channel, - own_client: connected.then_some(10), - server_uid: connected.then(|| "srv=".to_owned()), - ..Default::default() - } -} - -/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in -/// Games). -fn presence() -> Arc { - let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() }; - for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] { - p.channels.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() }); - } - for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] { - p.clients.insert( - id, - ClientInfo { - id, - channel: 2, - nickname: name.into(), - uid: Some(uid.into()), - ..Default::default() - }, - ); - } - p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() }; - Arc::new(p) -} - -/// A message of Games, by Alice unless `mine`. -fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage { - HistoryMessage { - id, - message: ChatMessage { - target: ChatTarget::Channel(2), - author_name: if mine { "Me" } else { "Alice" }.into(), - author_uid: Some(if mine { "me=" } else { "alice=" }.into()), - author_id: Some(if mine { 10 } else { 11 }), - text: text.into(), - ts_ms, - via_relay: false, - blocked: false, - }, - source: MessageSource::Voice, - remote_id: Some(id + 1000), - topic_id: None, - reactions: Vec::new(), - pinned: false, - rev: 0, - } -} +use crate::host::testing::{State, presence, said, session, state}; fn games(messages: Vec, source: HistorySource) -> Event { Event::ChatHistory { diff --git a/crates/voelin-ui-vm/src/host.rs b/crates/voelin-ui-vm/src/host.rs index 04775c4..0f99c3a 100644 --- a/crates/voelin-ui-vm/src/host.rs +++ b/crates/voelin-ui-vm/src/host.rs @@ -252,6 +252,18 @@ pub(crate) mod testing { use super::Host; + use std::sync::Arc; + + use voelin_core::{ + AudioSettings, HistoryMessage, ObserveState, SessionState, Source, VoiceState, + }; + use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails}; + use voelin_store::{Bookmark, MessageSource}; + + use crate::bridge::ChatLine; + use crate::settings::{ClientPlaybackMap, UiSettings}; + use crate::state::AppState; + /// The front end of the tests: answers what the transitions ask and keeps /// what they store. #[derive(Default)] @@ -312,4 +324,82 @@ pub(crate) mod testing { Ok(()) } } + + pub(crate) type State = AppState>; + + pub(crate) fn state() -> State { + let bookmark = Bookmark { + id: 1, + name: "ts.example".into(), + address: "ts.example".into(), + nickname: "Me".into(), + ..Default::default() + }; + AppState::new( + vec![bookmark], + UiSettings::default(), + AudioSettings::default(), + ClientPlaybackMap::new(), + ) + } + + pub(crate) fn session(voice: VoiceState, own_channel: Option) -> SessionState { + let connected = voice == VoiceState::Connected; + SessionState { + voice, + observe: ObserveState::Off, + presence_source: connected.then_some(Source::Voice), + own_channel, + own_client: connected.then_some(10), + server_uid: connected.then(|| "srv=".to_owned()), + ..Default::default() + } + } + + /// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in + /// Games). + pub(crate) fn presence() -> Arc { + let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() }; + for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] { + p.channels + .insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() }); + } + for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] { + p.clients.insert( + id, + ClientInfo { + id, + channel: 2, + nickname: name.into(), + uid: Some(uid.into()), + ..Default::default() + }, + ); + } + p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() }; + Arc::new(p) + } + + /// A message of Games, by Alice unless `mine`. + pub(crate) fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage { + HistoryMessage { + id, + message: ChatMessage { + target: ChatTarget::Channel(2), + author_name: if mine { "Me" } else { "Alice" }.into(), + author_uid: Some(if mine { "me=" } else { "alice=" }.into()), + author_id: Some(if mine { 10 } else { 11 }), + text: text.into(), + ts_ms, + via_relay: false, + blocked: false, + }, + source: MessageSource::Voice, + remote_id: Some(id + 1000), + topic_id: None, + reactions: Vec::new(), + pinned: false, + rev: 0, + } + } } diff --git a/crates/voelin-ui-vm/src/social.rs b/crates/voelin-ui-vm/src/social.rs index 208bf27..1ff85dd 100644 --- a/crates/voelin-ui-vm/src/social.rs +++ b/crates/voelin-ui-vm/src/social.rs @@ -81,6 +81,62 @@ pub fn own_message( || (own_client.is_some() && message.author_id == own_client) } +/// A poke we got. +#[derive(Clone, Debug, PartialEq)] +pub struct Poke { + /// The session it came in. + pub session: i64, + /// Who poked, by unique id, when known. + pub uid: Option, + /// Who poked, by name. + pub name: String, + /// What they wrote with it. + pub message: String, + /// When, in milliseconds since the epoch. + pub ts_ms: i64, +} + +/// The avatar picture of someone by unique id, from any session. +pub fn avatar_of(state: &AppState, uid: &str) -> crate::image::ImageRef { + crate::avatar::image(state.sessions.values().find_map(|v| v.avatars.get(uid))) +} + +/// Pokes from `uid` as lines of their private chat, among its messages +/// (with the time of each, oldest first). +pub fn poke_lines( + state: &AppState, + pokes: &[Poke], + session: i64, + uid: &str, +) -> Vec<(i64, crate::bridge::ChatLine)> { + pokes + .iter() + .enumerate() + .filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid)) + .map(|(i, p)| { + let text = if p.message.is_empty() { + "👋 poked you".to_owned() + } else { + format!("👋 poked you: {}", p.message) + }; + let message = ChatMessage { + target: ChatTarget::Private(uid.to_owned()), + author_name: p.name.clone(), + author_uid: p.uid.clone(), + author_id: None, + text, + ts_ms: p.ts_ms, + via_relay: false, + blocked: false, + }; + let mut line = crate::chat::line(&message, None); + line.key = -1_000_000 - i as i32; + line.avatar = avatar_of(state, uid); + (p.ts_ms, line) + }) + .collect() +} + /// Whether a message of a session is ours. pub fn is_own(state: &AppState, session: i64, message: &ChatMessage) -> bool { let own_client = state.sessions.get(&session).and_then(|v| v.state.own_client); diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs deleted file mode 100644 index b85ffe0..0000000 --- a/crates/voelin-ui/src/chat.rs +++ /dev/null @@ -1,730 +0,0 @@ -//! 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::settings::CACHE_FETCH_IMAGES; -use voelin_core::{ - Command, DownloadTo, GatewayRequest, HistoryMessage, HistorySource, TransferState, -}; -use voelin_gateway_proto::feature; -use voelin_model::{ChatMessage, ChatTarget}; - -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; - -/// "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 { - /// Open the chat `target` of the current session, and with `focus` show - /// it ([`vm::chat::logic::open_chat`]). - pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) { - self.transition(|state, cx| vm::chat::logic::open_chat(state, cx, target, focus)); - } - - /// 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 { - self.transition(|state, cx| vm::chat::logic::chat_tab(state, cx, id, target)) - } - - /// 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 }); - } - - /// A live message of a session without stored history. - pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) { - self.transition(|state, cx| vm::chat::logic::add_message(state, cx, id, message)); - } - - /// 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, - ) { - self.transition(|state, cx| { - vm::chat::logic::history_batch(state, cx, id, target, messages, source, complete); - }); - } - - /// 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)| vm::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(vm::chat::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, - }; - vm::chat::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::