diff --git a/crates/voelin-ui-vm/src/servers/logic.rs b/crates/voelin-ui-vm/src/servers/logic.rs new file mode 100644 index 0000000..b0c729b --- /dev/null +++ b/crates/voelin-ui-vm/src/servers/logic.rs @@ -0,0 +1,903 @@ +//! Servers: what the rail, the server card and the channel tree show, which +//! server is shown and how it is observed, the gateway found for it, and +//! joining a channel. The functions change the +//! [`AppState`](crate::state::AppState) and say in the +//! [`Cx`](crate::host::Cx)'s update what to draw and send; the store, the +//! secrets, the identity and the sockets are the front end's. + +use voelin_core::identity::LaunchImport; +use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState}; +use voelin_model::{ChannelId, ChatTarget}; +use voelin_store::{Bookmark, QueryConfig}; + +use super::{JoinStep, item, join_password, tints}; +use crate::bridge::{BookmarkForm, MemberItem, ServerItem, TreeItem}; +use crate::chat::logic::{open_chat, prefetch_counts, save_reads, track_reading}; +use crate::host::{Cx, Persist}; +use crate::image::ImageRef; +use crate::state::{AppState, Lines, SessionView}; + +/// The name of the identity the app creates when it has none. +pub const CREATED_IDENTITY: &str = "Default"; + +/// What to tell the user about the identities imported from the official +/// clients at start ([`voelin_core::identity::import_new`]), if anything. +pub fn imported_status(report: &LaunchImport) -> Option { + let n = report.added.len(); + let names = report.added.iter().map(|f| f.nickname.as_str()).collect::>().join(", "); + let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() }; + Some(match &report.default { + Some(f) if report.replaced => format!( + "You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}", + f.nickname + ), + Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname), + None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"), + None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"), + None => return None, + }) +} + +/// The bookmark the form describes, over `old` (what the form does not show, +/// like the identity, the default channel or the client version, stays; a +/// new server has none of it). Only the address is needed: the name is the +/// address until the server tells its own, the nickname `default_nickname`, +/// the gateway is looked up in DNS. A new address drops the gateway and the +/// query login found or set for the old one. +pub fn bookmark_from_form( + old: Option<&Bookmark>, + form: &BookmarkForm, + default_nickname: impl FnOnce() -> String, +) -> Bookmark { + let mut bookmark = old.cloned().unwrap_or_default(); + bookmark.id = form.id as i64; + bookmark.address = form.address.trim().to_string(); + if old.is_some_and(|old| old.address != bookmark.address) { + bookmark.cached_server_icon = None; + bookmark.gateway_url = None; + bookmark.gateway_urls.clear(); + bookmark.query = None; + } + bookmark.name = match form.name.trim() { + "" => bookmark.address.clone(), + name => name.to_string(), + }; + bookmark.nickname = match form.nickname.trim() { + "" => default_nickname(), + nickname => nickname.to_string(), + }; + bookmark +} + +/// Whether observing goes on as it is when discovery changed the gateways +/// kept from `previous` to `found`: the same ones (an older version kept +/// only the one in use), or logged in through `in_use`, still published. +/// What was found is kept for the next start, without a new login now. +pub fn observing_stays( + previous: &[String], + found: &[String], + in_use: Option<&str>, + observe: ObserveState, +) -> bool { + found == previous + || (observe == ObserveState::Observing + && in_use.is_some_and(|url| found.iter().any(|u| u == url))) +} + +/// The options of a voice connection to `bookmark`, into `channel` (a path, +/// or `/`, with its password) if given, with a privilege key if given; +/// the reason when the bookmark's client version is not one. The identity, +/// the server's password and the stream peer are the front end's to add. +pub fn voice_options( + bookmark: &Bookmark, + channel: Option, + channel_password: Option, + token: Option, +) -> Result { + let mut options = VoiceOptions::new(&bookmark.address, &bookmark.nickname); + if let Some(spec) = &bookmark.client_version { + match voelin_core::versions::resolve(spec) { + Ok(version) => options.client_version = version, + Err(error) => return Err(format!("Invalid client compatibility version: {error}")), + } + } + options.channel = channel; + options.channel_password = channel_password; + options.token = token; + options.audio = true; + Ok(options) +} + +// Which server is shown, and how it is observed. + +/// Show a server (the front end then observes it). +pub fn select_server(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + state.current = Some(id); + prefetch_counts(state, cx); + track_reading(state, cx); + let r = &mut cx.update.refresh; + (r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true); +} + +/// A server was removed from the list (the store has the rest now): its +/// session goes, and the first server is shown. +pub fn forget_server( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + bookmarks: Vec, +) { + save_reads(state, cx, id); + state.sessions.remove(&id); + state.gateways_looked_up.remove(&id); + state.bookmarks = bookmarks; + state.current = state.bookmarks.first().map(|b| b.id); + prefetch_counts(state, cx); + track_reading(state, cx); + let r = &mut cx.update.refresh; + (r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true); +} + +/// What observing a server invisibly comes to ([`observe_plan`]). +#[derive(Clone, Debug, PartialEq)] +pub enum ObservePlan { + /// Nothing to do: it is observed already, or there is no server. + Nothing, + /// The gateway is still being connected to: the engine tries it again + /// now. + Retry(Vec), + /// Observe through these gateways (best first), and look the gateway up + /// again; the status line says so. + Gateway(Vec), + /// Observe through the server's own query login; the status line says so. + Query(QueryConfig), + /// There is neither: the gateway is looked up, and observing starts + /// when it is found. + Discover, +} + +/// How to observe server `id` invisibly, unless it is already: through its +/// gateway, else its own query login. Without either the gateway is looked +/// up first, and observing starts when it is found. Asked while still +/// connecting, the engine tries the gateway again sooner. +pub fn observe_plan(state: &AppState, cx: &Cx<'_>, id: i64) -> ObservePlan { + let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else { return ObservePlan::Nothing }; + if cx.host.demo_ui() { + return ObservePlan::Nothing; + } + let observing = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default(); + let urls = b.gateways(); + match observing { + ObserveState::Observing => return ObservePlan::Nothing, + // The engine decides: the same gateways are not started over, at most + // tried again now. + ObserveState::Connecting => { + return if urls.is_empty() { ObservePlan::Nothing } else { ObservePlan::Retry(urls) }; + } + ObserveState::Off => {} + } + if !urls.is_empty() { + ObservePlan::Gateway(urls) + } else if let Some(q) = &b.query { + ObservePlan::Query(q.clone()) + } else { + ObservePlan::Discover + } +} + +/// The address of server `id` to look the gateway up for, once a run (not +/// for the sample sessions). +pub fn discover_wanted(state: &mut AppState, cx: &Cx<'_>, id: i64) -> Option { + if cx.host.demo_ui() || !state.gateways_looked_up.insert(id) { + return None; + } + state.bookmarks.iter().find(|b| b.id == id).map(|b| b.address.clone()) +} + +/// What finding the gateways of a server comes to. +#[derive(Clone, Debug, PartialEq)] +pub enum GatewayFound { + /// Nothing changed, or the server is another one now. + Same, + /// Kept, and observing goes on as it is; `observe` when the server on + /// screen is not observed yet. + Kept { + /// Observe the server now. + observe: bool, + }, + /// Kept, and the old ones are left: observing was through them. The + /// server on screen is observed through the new ones. + Changed { + /// The gateways observed through before (the engine stops them). + stop: bool, + /// Observe the server now. + observe: bool, + /// Every URL the server publishes, best first, for the log. + urls: Vec, + }, +} + +/// Gateways were found for the server at `address` (best first); they are +/// kept unless the server changed meanwhile. Users never hear of them +/// (logged only). +pub fn gateway_found( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + address: &str, + urls: Vec, +) -> GatewayFound { + let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else { + return GatewayFound::Same; + }; + let previous = b.gateways(); + let in_use = b.gateway_url.clone(); + if !b.set_gateways(urls) { + return GatewayFound::Same; + } + cx.persist(Persist::Bookmark { id, what: "gateway found" }); + let found = b.gateways(); + let observe = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default(); + let kept = observing_stays(&previous, &found, in_use.as_deref(), observe); + cx.update.refresh.toolbar = true; + let current = state.current == Some(id); + if kept { + return GatewayFound::Kept { observe: current && observe == ObserveState::Off }; + } + // Observed through the old ones: through these now. + let stop = !previous.is_empty(); + if stop && let Some(view) = state.sessions.get_mut(&id) { + view.state.observe = ObserveState::Off; + } + GatewayFound::Changed { stop, observe: current, urls: found } +} + +// Joining a channel. + +/// Join a channel of a session (a double-click in the tree, joining a +/// friend): move there with voice, or the password to connect into it with +/// when there is no voice on that server. A locked channel asks for its +/// password first, unless it was given this connection. +pub fn join_channel( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + channel: ChannelId, +) -> Option> { + let view = state.sessions.get(&session)?; + let info = view.presence.channels.get(&channel)?; + let remembered = view.channel_passwords.get(&channel).map(String::as_str); + match join_password(info, remembered) { + JoinStep::Send(password) => enter_channel(state, cx, session, channel, password), + JoinStep::Ask => { + crate::events::ask_password(state, cx, session, channel, false); + None + } + } +} + +/// The password dialog's Join: the same, with that password. +pub fn join_with_password( + state: &mut AppState, + cx: &mut Cx<'_>, + password: String, +) -> Option<(i64, ChannelId, Option)> { + let (session, channel) = state.join_target.take()?; + if password.is_empty() { + return None; + } + if let Some(view) = state.sessions.get_mut(&session) { + view.channel_passwords.insert(channel, password.clone()); + } + enter_channel(state, cx, session, channel, Some(password)).map(|p| (session, channel, p)) +} + +/// Move into a channel; without voice on its server the front end connects +/// into it, with the password returned. +pub fn enter_channel( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + channel: ChannelId, + password: Option, +) -> Option> { + let view = state.sessions.get_mut(&session)?; + if view.state.voice != VoiceState::Disconnected { + // Chosen while connecting: no longer the one to join after. + view.join_after_connect = None; + cx.send_real(Command::MoveToChannel { session: session as u64, channel, password }); + return None; + } + Some(password) +} + +/// Voice is being connected into `channel` of session `session`: once +/// connected, it is joined again if the server put us elsewhere. +pub fn join_after_connect(state: &mut AppState, session: i64, channel: ChannelId) { + if let Some(view) = state.sessions.get_mut(&session) { + view.join_after_connect = Some(channel); + } +} + +/// Fold or unfold a channel of the current session. +pub fn toggle_collapse(state: &mut AppState, cx: &mut Cx<'_>, channel: ChannelId) { + if let Some(id) = state.current { + let view = state.sessions.entry(id).or_default(); + if !view.collapsed.remove(&channel) { + view.collapsed.insert(channel); + } + } + cx.update.refresh.tree = true; +} + +/// The members panel's search. +pub fn search_members(state: &mut AppState, cx: &mut Cx<'_>, text: String) { + if state.member_filter != text { + state.member_filter = text; + cx.update.refresh.tree = true; + } +} + +/// The voice channel view was opened or closed: its chat is our channel's, +/// and its people lead the members panel. +pub fn show_voice_view(state: &mut AppState, cx: &mut Cx<'_>, on: bool) { + state.voice_view = on; + let channel = + state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| v.state.own_channel); + if on && let Some(channel) = channel { + open_chat(state, cx, ChatTarget::Channel(channel), true); + } + cx.update.refresh.tree = true; +} + +/// A link to the voice channel we are in, for the Invite button (which +/// copies it, and the copy's toast names the channel); the reason without +/// one. +pub fn invite_link(state: &mut AppState) -> Result { + let address = state + .current + .and_then(|id| state.bookmarks.iter().find(|b| b.id == id)) + .map(|b| b.address.clone()); + let path = state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| { + let cid = v.state.own_channel?; + let own = v.presence.channels.get(&cid)?; + // The link names the channels as the server has them; the toast as + // the tree shows them. + Some(( + crate::tree::channel_path(&v.presence, cid), + crate::tree::channel_title(own).0.to_owned(), + )) + }); + let (Some(address), Some((path, title))) = (address, path) else { + return Err("Join a voice channel to invite others to it"); + }; + let path: Vec<&str> = path.iter().map(String::as_str).collect(); + let link = super::invite_link(&address, &path); + state.copy_note = Some(format!("Copied an invite to {title}: {link}")); + Ok(link) +} + +// What is shown. + +/// The rail: servers with their state, unread count (without private chats) +/// and streams. `icon` gives a server's icon (what its session fetched, else +/// what was cached). +pub fn rail(state: &AppState, icon: impl Fn(&Bookmark) -> ImageRef) -> Vec { + state + .bookmarks + .iter() + .zip(tints(&state.bookmarks)) + .map(|(b, tint)| { + let view = state.sessions.get(&b.id); + let session = view.map(|v| v.state.clone()).unwrap_or_default(); + let unread = view.map_or(0, SessionView::channel_unread); + let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty()); + let detail = view + .filter(|v| !v.presence.channels.is_empty()) + .map(|v| crate::tree::stats(&v.presence)) + .unwrap_or_default(); + let product = view.map(|v| v.extra.product.clone()).unwrap_or_default(); + item(b, &session, unread, live, detail, product, icon(b), tint) + }) + .collect() +} + +/// A server's colour, as the rail shows it; none for a server that is not +/// in the list (a chat that outlived its bookmark). +pub fn server_tint(state: &AppState, id: i64) -> Option { + let position = state.bookmarks.iter().position(|b| b.id == id)?; + Some(tints(&state.bookmarks)[position]) +} + +/// The server card, the voice controls and who we are. +pub struct ToolbarView { + /// The server's icon. + pub server_icon: ImageRef, + /// Its name. + pub server_title: String, + /// "9 online · 7 channels", once its presence is known. + pub server_stats: String, + /// Our nickname there. + pub nickname: String, + /// Our avatar. + pub own_avatar: ImageRef, + /// The server's banner. + pub server_banner: ImageRef, + /// How it is drawn. + pub server_banner_mode: i32, + /// The channel we are in. + pub own_channel: String, + /// Its topic. + pub own_channel_topic: String, + /// Its banner. + pub own_channel_banner: ImageRef, + /// How it is drawn. + pub own_channel_banner_mode: i32, + /// Its client limit, -1 without one. + pub own_channel_limit: i32, + /// Voice is connected. + pub voice_connected: bool, + /// Voice is connecting. + pub voice_connecting: bool, + /// The server is observed. + pub observing: bool, + /// Our microphone is muted. + pub input_muted: bool, + /// Our sound is muted. + pub output_muted: bool, + /// Voice is transmitted. + pub transmitting: bool, + /// Where the presence comes from, for people to read. + pub presence_source: &'static str, +} + +/// The server card for the current server; `icon` is its icon. +pub fn toolbar(state: &AppState, icon: impl Fn(&Bookmark) -> ImageRef) -> ToolbarView { + let bookmark = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id)); + let view = state.current.and_then(|id| state.sessions.get(&id)); + let session = view.map(|v| v.state.clone()).unwrap_or_default(); + let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty()) + && (session.voice == VoiceState::Connected || session.observe == ObserveState::Observing); + let own = view.zip(session.own_client).and_then(|(v, c)| v.avatar(c)); + let banner = + |url: Option<&str>| view.map(|v| crate::tree::banner(&v.pictures, url)).unwrap_or_default(); + let details = view.map(|v| &v.presence.server); + let own_channel = + view.and_then(|v| session.own_channel.and_then(|c| v.presence.channels.get(&c))); + ToolbarView { + server_icon: bookmark.map(&icon).unwrap_or_default(), + server_title: bookmark.map_or("No server selected".into(), |b| b.name.clone()), + server_stats: view + .filter(|_| has_presence) + .map(|v| crate::tree::stats(&v.presence)) + .unwrap_or_default(), + nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default(), + own_avatar: crate::avatar::image(own), + server_banner: banner(details.map(|d| d.banner_gfx_url.as_str())), + server_banner_mode: details.map_or(0, |d| crate::tree::banner_mode(d.banner_mode)), + own_channel: own_channel + .map(|c| crate::tree::channel_title(c).0.to_owned()) + .unwrap_or_default(), + own_channel_topic: own_channel.and_then(|c| c.topic.clone()).unwrap_or_default(), + own_channel_banner: banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref())), + own_channel_banner_mode: own_channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)), + own_channel_limit: own_channel + .and_then(|c| c.max_clients) + .filter(|m| *m >= 0) + .unwrap_or(-1), + voice_connected: session.voice == VoiceState::Connected, + voice_connecting: session.voice == VoiceState::Connecting, + observing: session.observe != ObserveState::Off, + input_muted: session.input_muted, + output_muted: session.output_muted, + transmitting: session.transmitting, + presence_source: match session.presence_source { + Some(Source::Voice) => "live (voice)", + Some(Source::Gateway) => "invisible (gateway)", + Some(Source::Query) => "invisible (query)", + None => "", + }, + } +} + +/// The channel tree and the members. +pub struct TreeView { + /// The channels and clients, as the tree lists them. + pub rows: Vec, + /// The members of our channel (while voice is connected). + pub members: Vec, + /// Everyone on the server, filtered by the panel's search. + pub server_members: Vec, + /// How many are on the server (without query clients). + pub member_total: i32, +} + +/// The channel tree, the members of our channel and everyone on the server; +/// none when no server is shown. `popped_out`: the stream plays in a window +/// of its own. +pub fn tree_view(state: &AppState, popped_out: bool) -> Option { + let view = state.current.and_then(|id| state.sessions.get(&id))?; + let input = crate::tree::TreeInput { + presence: &view.presence, + collapsed: &view.collapsed, + talking: &view.talking, + playback: &state.playback, + own_channel: view.state.own_channel, + own_client: view.state.own_client, + filter: "", + avatars: &view.avatars, + icons: &view.icons, + pictures: &view.pictures, + groups: &view.server_groups, + channel_groups: &view.channel_groups, + }; + let rows = crate::tree::rows(&input); + let connected = view.state.voice == VoiceState::Connected; + let members = if connected { crate::tree::members(&input) } else { Vec::new() }; + // The people in our channel first while their view is shown (not while + // the stream plays in a window of its own). + let watching = state.watch.as_ref().is_some_and(|w| w.shown) && !popped_out; + let voice_first = connected && (state.voice_view || watching); + let everyone = crate::tree::server_members(&input, voice_first); + let filter = state.member_filter.trim().to_lowercase(); + let server_members = + if filter.is_empty() { everyone } else { crate::tree::matching(everyone, &filter) }; + Some(TreeView { + rows, + members, + server_members, + member_total: view.presence.clients.values().filter(|c| !c.is_query).count() as i32, + }) +} + +#[cfg(test)] +mod tests { + use voelin_core::SessionState; + use voelin_model::ChannelInfo; + + use super::*; + use crate::host::testing::{Fake, State, presence, session, state}; + + fn bookmark(id: i64, name: &str, address: &str) -> Bookmark { + Bookmark { id, name: name.into(), address: address.into(), ..Default::default() } + } + + #[test] + fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() { + use crate::events::apply_server_icon; + let path = std::env::temp_dir() + .join(format!("voelin-server-icon-edited-{}.svg", std::process::id())); + std::fs::write(&path, r#""#).unwrap(); + let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() }; + let mut view = SessionView::<()>::default(); + view.icons.insert(1234, path.clone()); + assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234)); + assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4); + + bookmark = bookmark_from_form( + Some(&bookmark), + &BookmarkForm { address: "b.test".into(), ..Default::default() }, + || "Me".into(), + ); + // Connecting does not retag received imagery. A failed B connection + // must not make A's image appear under B's name. + for state in [VoiceState::Connecting, VoiceState::Disconnected] { + view.state.voice = state; + assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0); + } + assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321)); + assert_eq!(view.server_icon, 1234); + assert_eq!(view.icon_address.as_deref(), Some("a.test")); + assert!(bookmark.server_icon_id().is_none()); + + // Equal icon IDs on the next server still need new provenance. + assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234)); + assert_eq!(bookmark.server_icon_id(), Some(1234)); + assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4); + assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0)); + assert_eq!(bookmark.server_icon_id(), Some(1234)); + assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0)); + assert!(bookmark.server_icon_id().is_none()); + assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn the_address_alone_makes_a_server() { + let form = + BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() }; + let b = bookmark_from_form(None, &form, || "Nick".into()); + assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test")); + assert_eq!(b.nickname, "Nick"); + assert_eq!( + (b.gateway_url, b.query, b.identity, b.default_channel), + (None, None, None, None) + ); + } + + #[test] + fn editing_keeps_what_the_form_does_not_show() { + let old = Bookmark { + id: 7, + name: "Old".into(), + address: "old.example.test".into(), + nickname: "Me".into(), + identity: Some(2), + default_channel: Some("Lobby/Sub".into()), + gateway_url: Some("ws://gw.example.test:7788/v1".into()), + gateway_urls: vec!["ws://gw.example.test:7788/v1".into()], + query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }), + client_version: Some("linux".into()), + cached_server_icon: Some(voelin_store::CachedServerIcon { + address: "old.example.test".into(), + id: 1234, + }), + }; + // Same address: the gateway found and the query login stay. + let same = BookmarkForm { + id: 7, + name: "Mine".into(), + address: "old.example.test".into(), + nickname: "Other".into(), + ..Default::default() + }; + let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given")); + assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other")); + assert_eq!(b.gateway_url, old.gateway_url); + assert_eq!(b.query, old.query); + assert_eq!(b.cached_server_icon, old.cached_server_icon); + // Another address: looked up again, for the new server. + let form = BookmarkForm { address: "new.example.test:9988".into(), ..same }; + let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given")); + assert_eq!(b.address, "new.example.test:9988"); + assert!(b.cached_server_icon.is_none()); + assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into()))); + assert_eq!(b.client_version.as_deref(), Some("linux")); + assert_eq!((b.gateway_url, b.query), (None, None)); + assert!(b.gateway_urls.is_empty()); + } + + #[test] + fn a_gateway_found_again_is_not_logged_in_again() { + let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1"); + let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::>(); + let stays = |previous: &[&str], found: &[&str], observe| { + observing_stays(&urls(previous), &urls(found), Some(plain), observe) + }; + // The same ones (an older version kept only the one in use). + assert!(stays(&[plain], &[plain], ObserveState::Connecting)); + assert!(stays(&[plain], &[plain], ObserveState::Observing)); + // Logged in through one still published. + assert!(stays(&[plain], &[tls, plain], ObserveState::Observing)); + // Not logged in yet: through the new ones. + assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting)); + // The one in use is no longer published. + assert!(!stays(&[plain], &[tls], ObserveState::Observing)); + assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off)); + } + /// How a server is observed: through its gateway, its query login, or + /// after the gateway was looked up; not twice, not for sample servers. + #[test] + fn a_server_is_observed_through_what_it_has() { + let mut st = state(); + let host = Fake::default(); + let cx = Cx::new(&host); + assert_eq!(observe_plan(&st, &cx, 9), ObservePlan::Nothing, "no such server"); + assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Discover); + st.bookmarks[0].query = Some(QueryConfig::default()); + assert!(matches!(observe_plan(&st, &cx, 1), ObservePlan::Query(_))); + st.bookmarks[0].gateway_urls = vec!["wss://gw/v1".into()]; + assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Gateway(vec!["wss://gw/v1".into()])); + let view = st.sessions.entry(1).or_default(); + view.state.observe = ObserveState::Connecting; + assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Retry(vec!["wss://gw/v1".into()])); + st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing; + assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Nothing); + let demo = Fake { demo: true, ..Default::default() }; + assert_eq!(observe_plan(&st, &Cx::new(&demo), 1), ObservePlan::Nothing); + // The gateway is looked up once a run. + assert_eq!(discover_wanted(&mut st, &cx, 1).as_deref(), Some("ts.example")); + assert_eq!(discover_wanted(&mut st, &cx, 1), None); + } + + /// What finding the gateways does to a server. + #[test] + fn found_gateways_are_kept_and_observed_through() { + let mut st = state(); + let host = Fake::default(); + let found = |st: &mut State, urls: &[&str], address: &str| { + let mut cx = Cx::new(&host); + let result = gateway_found( + st, + &mut cx, + 1, + address, + urls.iter().map(|s| s.to_string()).collect(), + ); + (result, cx.update.persist.len(), cx.update.refresh.toolbar) + }; + // Another address now: nothing. + assert_eq!(found(&mut st, &["wss://gw/v1"], "other.example").0, GatewayFound::Same); + // First found, the server is shown and not observed: observe. + let (result, kept, toolbar) = found(&mut st, &["wss://gw/v1"], "ts.example"); + assert_eq!( + result, + GatewayFound::Changed { stop: false, observe: true, urls: vec!["wss://gw/v1".into()] } + ); + assert!(kept == 1 && toolbar); + // The same again: nothing changed. + assert_eq!(found(&mut st, &["wss://gw/v1"], "ts.example").0, GatewayFound::Same); + // Observing through the old: a different gateway list leaves them. + st.sessions.entry(1).or_default().state.observe = ObserveState::Observing; + let (result, ..) = found(&mut st, &["wss://new/v1"], "ts.example"); + assert_eq!( + result, + GatewayFound::Changed { stop: true, observe: true, urls: vec!["wss://new/v1".into()] } + ); + assert_eq!(st.sessions[&1].state.observe, ObserveState::Off); + // One that still lists the one in use keeps observing. + st.bookmarks[0].gateway_url = Some("wss://new/v1".into()); + st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing; + let (result, ..) = found(&mut st, &["wss://new/v1", "wss://more/v1"], "ts.example"); + assert_eq!(result, GatewayFound::Kept { observe: false }); + } + + /// Joining a channel: a free one at once (or connecting into it), a locked + /// one asks, the password dialog's Join goes on. + #[test] + fn joining_a_channel_moves_asks_or_connects() { + let mut st = state(); + let host = Fake::default(); + let mut locked = ChannelInfo { id: 3, name: "Vault".into(), ..Default::default() }; + locked.has_password = true; + let mut p = (*presence()).clone(); + p.channels.insert(3, locked); + st.sessions.entry(1).or_default().presence = std::sync::Arc::new(p); + // Connected: moving. + st.sessions.get_mut(&1).unwrap().state = session(VoiceState::Connected, Some(2)); + let mut cx = Cx::new(&host); + assert_eq!(join_channel(&mut st, &mut cx, 1, 1), None); + assert!(matches!( + cx.update.commands.as_slice(), + [Command::MoveToChannel { session: 1, channel: 1, password: None }] + )); + // A locked one asks. + let mut cx = Cx::new(&host); + assert_eq!(join_channel(&mut st, &mut cx, 1, 3), None); + assert_eq!(cx.update.password.as_ref().map(|p| p.name.as_str()), Some("Vault")); + assert_eq!(st.join_target, Some((1, 3))); + let mut cx = Cx::new(&host); + assert_eq!(join_with_password(&mut st, &mut cx, "".into()), None); + st.join_target = Some((1, 3)); + assert_eq!(join_with_password(&mut st, &mut cx, "pw".into()), None); + assert_eq!(st.sessions[&1].channel_passwords.get(&3).map(String::as_str), Some("pw")); + assert!(matches!( + cx.update.commands.as_slice(), + [Command::MoveToChannel { channel: 3, password: Some(p), .. }] if p == "pw" + )); + // Not connected: the front end connects into it. + st.sessions.get_mut(&1).unwrap().state = SessionState::default(); + let mut cx = Cx::new(&host); + assert_eq!(join_channel(&mut st, &mut cx, 1, 1), Some(None)); + join_after_connect(&mut st, 1, 1); + assert_eq!(st.sessions[&1].join_after_connect, Some(1)); + assert!(cx.update.commands.is_empty()); + } + + /// The server card, the rail and the tree for the server shown. + #[test] + fn the_rail_the_card_and_the_tree() { + let mut st = state(); + let no_icon = |_: &Bookmark| ImageRef::default(); + // Nothing connected yet. + let rail_rows = rail(&st, no_icon); + assert_eq!(rail_rows.len(), 1); + assert_eq!((&*rail_rows[0].status, &*rail_rows[0].detail), ("offline", "ts.example")); + let card = toolbar(&st, no_icon); + assert_eq!((card.server_title.as_str(), card.nickname.as_str()), ("ts.example", "Me")); + assert!(!card.voice_connected && card.presence_source.is_empty()); + assert!(tree_view(&st, false).is_none(), "no session yet"); + // Connected into Games. + let host = Fake::default(); + for event in [ + voelin_core::Event::Presence { session: 1, presence: presence() }, + voelin_core::Event::State { + session: 1, + state: session(VoiceState::Connected, Some(2)), + }, + ] { + crate::events::apply(&mut st, &host, event); + } + let rail_rows = rail(&st, no_icon); + assert_eq!( + (&*rail_rows[0].status, &*rail_rows[0].detail), + ("connected", "2 online · 2 channels") + ); + assert_eq!(server_tint(&st, 1), Some(tints(&st.bookmarks)[0])); + assert_eq!(server_tint(&st, 9), None); + let card = toolbar(&st, no_icon); + assert!(card.voice_connected && card.own_channel == "Games"); + assert_eq!(card.presence_source, "live (voice)"); + assert_eq!(card.own_channel_limit, -1); + let tree = tree_view(&st, false).unwrap(); + assert_eq!(tree.rows.len(), 4, "two channels and their clients"); + assert_eq!(tree.members.len(), 2); + assert_eq!(tree.member_total, 2); + // The members' search filters the server's people only. + let mut cx = Cx::new(&host); + search_members(&mut st, &mut cx, "ali".into()); + assert!(cx.update.refresh.tree); + let tree = tree_view(&st, false).unwrap(); + assert_eq!( + tree.server_members + .iter() + .filter(|m| !m.group.is_empty() && &*m.name == "Alice") + .count(), + 1 + ); + assert!(tree.server_members.iter().all(|m| &*m.name != "Me")); + // Folding a channel; the tree is drawn again. + let mut cx = Cx::new(&host); + toggle_collapse(&mut st, &mut cx, 1); + assert!(st.sessions[&1].collapsed.contains(&1) && cx.update.refresh.tree); + toggle_collapse(&mut st, &mut cx, 1); + assert!(st.sessions[&1].collapsed.is_empty()); + } + + /// The Invite button's link and note; the voice view's chat. + #[test] + fn invite_and_voice_view() { + let mut st = state(); + let host = Fake::default(); + assert_eq!(invite_link(&mut st), Err("Join a voice channel to invite others to it")); + for event in [ + voelin_core::Event::Presence { session: 1, presence: presence() }, + voelin_core::Event::State { + session: 1, + state: session(VoiceState::Connected, Some(2)), + }, + ] { + crate::events::apply(&mut st, &host, event); + } + let link = invite_link(&mut st).unwrap(); + assert!(link.contains("ts.example") && link.contains("Games"), "{link}"); + assert_eq!(st.copy_note.as_deref(), Some(&*format!("Copied an invite to Games: {link}"))); + let mut cx = Cx::new(&host); + show_voice_view(&mut st, &mut cx, true); + assert!(st.voice_view && cx.update.refresh.tree && cx.update.refresh.chat); + } + + /// A server leaves the list; the first one that is left is shown. + #[test] + fn forgetting_a_server_shows_the_first_left() { + let mut st = state(); + st.bookmarks.push(bookmark(2, "Other", "other.example")); + let host = Fake::default(); + st.sessions.entry(1).or_default(); + st.gateways_looked_up.insert(1); + let mut cx = Cx::new(&host); + forget_server(&mut st, &mut cx, 1, vec![bookmark(2, "Other", "other.example")]); + assert_eq!(st.current, Some(2)); + assert!(st.sessions.is_empty() && st.gateways_looked_up.is_empty()); + let r = cx.update.refresh; + assert!(r.servers && r.toolbar && r.tree && r.chat && r.streams); + let mut cx = Cx::new(&host); + select_server(&mut st, &mut cx, 2); + assert_eq!(st.current, Some(2)); + } + + #[test] + fn the_voice_options_follow_the_bookmark() { + let mut b = bookmark(1, "G", "ts.example"); + b.nickname = "Me".into(); + let options = + voice_options(&b, Some("/5".into()), Some("pw".into()), Some("key".into())).unwrap(); + assert_eq!(options.channel.as_deref(), Some("/5")); + assert_eq!(options.channel_password.as_deref(), Some("pw")); + assert_eq!(options.token.as_deref(), Some("key")); + assert!(options.audio); + b.client_version = Some("no such version".into()); + let error = voice_options(&b, None, None, None).err().unwrap(); + assert!(error.starts_with("Invalid client compatibility version"), "{error}"); + } +} diff --git a/crates/voelin-ui-vm/src/servers.rs b/crates/voelin-ui-vm/src/servers/mod.rs similarity index 99% rename from crates/voelin-ui-vm/src/servers.rs rename to crates/voelin-ui-vm/src/servers/mod.rs index 598cc5d..e0cee6f 100644 --- a/crates/voelin-ui-vm/src/servers.rs +++ b/crates/voelin-ui-vm/src/servers/mod.rs @@ -1,4 +1,8 @@ -//! The server rail, the server dialog, and joining a channel. +//! The server rail, the server dialog, and joining a channel; [`logic`] has +//! which server is shown, how it is observed, and the rail, the server card +//! and the channel tree as plain data. + +pub mod logic; use std::sync::Arc; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index b6e5c85..f020e98 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -389,7 +389,7 @@ pub fn run(options: RunOptions) -> Result<()> { // Creating an identity takes a moment (security level 8). let identity = tsclientlib::Identity::create(); let origin = voelin_store::IdentityOrigin::Created; - store.add_identity(crate::servers::CREATED_IDENTITY, &identity, origin)?; + store.add_identity(vm::servers::logic::CREATED_IDENTITY, &identity, origin)?; identity } }; @@ -476,7 +476,7 @@ pub fn run(options: RunOptions) -> Result<()> { if app.demo { app.start_demo(); } - if let Some(text) = crate::servers::imported_status(&imported) { + if let Some(text) = vm::servers::logic::imported_status(&imported) { app.set_status(text); } }); diff --git a/crates/voelin-ui/src/chat/bind.rs b/crates/voelin-ui/src/chat/bind.rs index c6d18e0..ca172ae 100644 --- a/crates/voelin-ui/src/chat/bind.rs +++ b/crates/voelin-ui/src/chat/bind.rs @@ -170,14 +170,6 @@ impl App { // What is read. - /// After anything that can change which chat is on screen (a tab, a - /// server, the page, the window's focus): the chat left is stored and - /// loses its divider; the one on screen, in the focused window, is read. - /// `true` if a tab changed ([`logic::track_reading`]). - pub(crate) fn track_reading(&mut self) -> bool { - self.transition(logic::track_reading) - } - /// The current chat came on screen or left it (`Nav.chat-shown`). pub(crate) fn chat_shown_changed(&mut self) { self.transition(logic::chat_shown_changed); diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs deleted file mode 100644 index 89ff997..0000000 --- a/crates/voelin-ui/src/servers.rs +++ /dev/null @@ -1,813 +0,0 @@ -//! Servers: bookmarks, connecting and observing, the rail, the sidebar's -//! server card and the channel tree. - -use std::time::Instant; - -use slint::ComponentHandle; -use tracing::{debug, info, warn}; -use voelin_core::identity::LaunchImport; -use voelin_core::{Command, JoinFailure, ObserveState, Source, VoiceOptions, VoiceState}; -use voelin_model::ChannelId; -use voelin_store::{Bookmark, QueryTransport}; - -use crate::app::{App, Bridge, SessionView, later}; -use crate::bind::convert; -use crate::vm; -use crate::vm::bridge::BookmarkForm; -use crate::vm::servers::JoinStep; - -/// The name of the identity the app creates when it has none. -pub(crate) const CREATED_IDENTITY: &str = "Default"; - -/// What to tell the user about the identities imported from the official -/// clients at start ([`voelin_core::identity::import_new`]), if anything. -pub(crate) fn imported_status(report: &LaunchImport) -> Option { - let n = report.added.len(); - let names = report.added.iter().map(|f| f.nickname.as_str()).collect::>().join(", "); - let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() }; - Some(match &report.default { - Some(f) if report.replaced => format!( - "You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}", - f.nickname - ), - Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname), - None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"), - None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"), - None => return None, - }) -} - -/// The bookmark the form describes, over `old` (what the form does not show, -/// like the identity, the default channel or the client version, stays; a -/// new server has none of it). Only the address is needed: the name is the -/// address until the server tells its own (`adopt_server_name`), the -/// nickname `default_nickname`, the gateway is looked up in DNS -/// (`discover_gateway`). A new address drops the gateway and the query -/// login found or set for the old one. -fn bookmark_from_form( - old: Option<&Bookmark>, - form: &BookmarkForm, - default_nickname: impl FnOnce() -> String, -) -> Bookmark { - let mut bookmark = old.cloned().unwrap_or_default(); - bookmark.id = form.id as i64; - bookmark.address = form.address.trim().to_string(); - if old.is_some_and(|old| old.address != bookmark.address) { - bookmark.cached_server_icon = None; - bookmark.gateway_url = None; - bookmark.gateway_urls.clear(); - bookmark.query = None; - } - bookmark.name = match form.name.trim() { - "" => bookmark.address.clone(), - name => name.to_string(), - }; - bookmark.nickname = match form.nickname.trim() { - "" => default_nickname(), - nickname => nickname.to_string(), - }; - bookmark -} - -/// Whether observing goes on as it is when discovery changed the gateways -/// kept from `previous` to `found`: the same ones (an older version kept -/// only the one in use), or logged in through `in_use`, still published. -/// What was found is kept for the next start, without a new login now. -fn observing_stays( - previous: &[String], - found: &[String], - in_use: Option<&str>, - observe: ObserveState, -) -> bool { - found == previous - || (observe == ObserveState::Observing - && in_use.is_some_and(|url| found.iter().any(|u| u == url))) -} - -impl App { - pub(crate) fn connect_voice(&mut self) { - let channel = self - .state - .current - .and_then(|id| self.bookmark(id)) - .and_then(|b| b.default_channel.clone()); - self.connect_voice_to(channel, None, None); - } - - /// Connect the current server with voice, into `channel` (a path, or - /// `/`, with its password) if given, with a privilege key if given; - /// whether it was asked for. - pub(crate) fn connect_voice_to( - &mut self, - channel: Option, - channel_password: Option, - token: Option, - ) -> bool { - let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else { - return false; - }; - if self.demo_ui { - return false; - } - let mut options = VoiceOptions::new(&b.address, &b.nickname); - if let Some(spec) = &b.client_version { - match voelin_core::versions::resolve(spec) { - Ok(version) => options.client_version = version, - Err(error) => { - self.set_status(format!("Invalid client compatibility version: {error}")); - return false; - } - } - } - options.identity = Some(self.identity_for(Some(b.id))); - options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten(); - options.channel = channel; - options.channel_password = channel_password; - options.token = token; - options.audio = true; - options.stream_peer = self.video.peer_config(options.stream_peer); - self.engine - .send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) }); - self.set_status(format!("Connecting to {}…", b.address)); - // The admin may have published the gateway since it was added. - self.discover_gateway(b.id); - true - } - - /// The nickname a new server gets: the default identity's (one imported - /// from TeamSpeak keeps the nickname used there), else the system user's. - pub(crate) fn default_nickname(&self) -> String { - self.store - .default_identity() - .ok() - .flatten() - .map(|identity| identity.name) - .filter(|name| { - ![CREATED_IDENTITY, voelin_core::identity::DEFAULT_NICKNAME] - .contains(&name.as_str()) - }) - .or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok()) - // Servers refuse an empty nickname (Android has no user name). - .filter(|name| !name.trim().is_empty()) - .unwrap_or_else(|| "Voelin user".to_owned()) - } - - /// Look up the gateway of a server ([`voelin_core::discover`]), once a - /// run: every one the server publishes is kept, best first, and tried in - /// turn; they take the place of a stored one that is no longer published - /// (a gateway that moved, or one typed into an older version, which - /// showed the field). Nothing found keeps what is stored. - pub(crate) fn discover_gateway(&mut self, id: i64) { - if self.demo_ui || !self.state.gateways_looked_up.insert(id) { - return; - } - let Some(b) = self.bookmark(id) else { return }; - let address = b.address.clone(); - self.engine.runtime().spawn(async move { - let started = Instant::now(); - let urls = voelin_core::discover::gateways(&address).await; - let elapsed_ms = started.elapsed().as_millis() as u64; - if urls.is_empty() { - info!(server = %address, elapsed_ms, "no gateway published"); - } else { - later(move |app| app.gateway_found(id, &address, urls, elapsed_ms)); - } - }); - } - - /// Gateways were found for the server at `address` (best first); they - /// are kept unless the server changed meanwhile, and the server is - /// observed through them if it is the one shown. Users never hear of - /// them (logged only). - fn gateway_found(&mut self, id: i64, address: &str, urls: Vec, elapsed_ms: u64) { - let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) - else { - return; - }; - let previous = b.gateways(); - let in_use = b.gateway_url.clone(); - if !b.set_gateways(urls) { - debug!(server = %b.address, urls = ?b.gateway_urls, elapsed_ms, "gateway found, as kept"); - return; - } - if let Err(e) = self.store.update_bookmark(b) { - warn!(%e, "could not keep the gateway found"); - return; - } - let observe = self.state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default(); - let kept = observing_stays(&previous, &b.gateways(), in_use.as_deref(), observe); - info!(server = %b.address, urls = ?b.gateway_urls, ?previous, kept, elapsed_ms, "gateway found"); - self.refresh_toolbar(); - if kept { - if self.state.current == Some(id) && observe == ObserveState::Off { - self.observe(id); - } - return; - } - // Observed through the old ones: through these now. - if !previous.is_empty() { - self.engine.send(Command::StopObserving { session: id as u64 }); - if let Some(view) = self.state.sessions.get_mut(&id) { - view.state.observe = ObserveState::Off; - } - } - if self.state.current == Some(id) { - self.observe(id); - } - } - - /// Observe the server invisibly, unless it is already: through its - /// gateway, else its own query login. Without either the gateway is - /// looked up first, and observing starts when it is found - /// (`gateway_found`). Asked while still connecting, the engine tries - /// the gateway again sooner. - pub(crate) fn observe(&mut self, id: i64) { - let Some(b) = self.bookmark(id).cloned() else { return }; - if self.demo_ui { - return; - } - let session = b.id as u64; - let state = self.state.sessions.get(&b.id).map(|v| v.state.observe).unwrap_or_default(); - let urls = b.gateways(); - match state { - ObserveState::Observing => return, - // The engine decides: the same gateways are not started over, - // at most tried again now. - ObserveState::Connecting => { - if !urls.is_empty() { - debug!(server = %b.address, "still connecting to the gateway: try now"); - self.engine.send(Command::ObserveGateway { - session, - urls, - identity: Box::new(self.identity_for(Some(b.id))), - }); - } - return; - } - ObserveState::Off => {} - } - if !urls.is_empty() { - info!(server = %b.address, ?urls, "observing through the gateway"); - self.engine.send(Command::ObserveGateway { - session, - urls, - identity: Box::new(self.identity_for(Some(b.id))), - }); - // Still the one the server publishes? - self.discover_gateway(b.id); - } else if let Some(q) = &b.query { - let secret = self.secrets.get(&b.query_password_key()).ok().flatten(); - let transport = match q.transport { - QueryTransport::Raw => voelin_query::Transport::Raw, - QueryTransport::Ssh => voelin_query::Transport::Ssh, - QueryTransport::Http => voelin_query::Transport::Http, - }; - let connect = voelin_query::Connect { - transport, - addr: format!("{}:{}", q.host, q.port), - user: q.user.clone(), - secret, - server_port: q.server_port, - server_id: None, - line: Default::default(), - }; - self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) }); - } else { - self.discover_gateway(b.id); - return; - } - self.set_status("Observing invisibly…"); - } - - /// Show a server, and observe it. - pub(crate) fn select_server(&mut self, id: i64) { - self.state.current = Some(id); - self.prefetch_counts(); - self.track_reading(); - self.refresh_all(); - self.observe(id); - } - - pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm { - let Some(b) = self.bookmark(id) else { - return BookmarkForm { - id: -1, - nickname: self.default_nickname().into(), - ..Default::default() - }; - }; - let password = self.secrets.get(&b.server_password_key()).ok().flatten(); - let state = self.state.sessions.get(&b.id).map(|view| &view.state); - vm::servers::form(b, state, password.as_deref().unwrap_or_default()) - } - - /// Save the server dialog's server, and show it; its id, none when it - /// could not be saved (the toast says why). - pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option { - let old = self.bookmark(form.id as i64).cloned(); - let mut bookmark = bookmark_from_form(old.as_ref(), form, || self.default_nickname()); - let result = if bookmark.id < 0 { - self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id) - } else { - self.store.update_bookmark(&bookmark) - }; - if let Err(e) = result { - self.set_status(format!("Could not save: {e}")); - return None; - } - let key = bookmark.server_password_key(); - let result = if form.server_password.is_empty() { - self.secrets.delete(&key) - } else { - self.secrets.set(&key, &form.server_password) - }; - if let Err(e) = result { - warn!(%e, "could not store secret"); - } - // Another server: what was observed is the old one's, and its - // gateway is looked up anew. - if let Some(old) = old.filter(|old| old.address != bookmark.address) { - if old.query.is_some() { - let _ = self.secrets.delete(&old.query_password_key()); - } - self.state.gateways_looked_up.remove(&bookmark.id); - self.engine.send(Command::StopObserving { session: bookmark.id as u64 }); - if let Some(view) = self.state.sessions.get_mut(&bookmark.id) { - view.state.observe = ObserveState::Off; - } - } - self.state.bookmarks = self.store.bookmarks().unwrap_or_default(); - self.select_server(bookmark.id); - Some(bookmark.id) - } - - /// The server dialog's Connect: save the server, then connect it with - /// voice, into the channel of the link that filled the form if one did - /// ([`vm::servers::connect_to`]). Only once saved: connecting what is - /// shown after a failed save would connect the server shown before. - /// Whether it was saved. - pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool { - let saved = self.save_bookmark(form); - let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else { - return false; - }; - self.connect_voice_to(to.channel, to.channel_password, to.token); - true - } - - pub(crate) fn delete_bookmark(&mut self, id: i64) { - self.engine.send(Command::CloseSession { session: id as u64 }); - if let Some(b) = self.bookmark(id).cloned() { - let _ = self.secrets.delete(&b.server_password_key()); - let _ = self.secrets.delete(&b.query_password_key()); - } - let _ = self.store.delete_bookmark(id); - self.save_reads(id); - self.state.sessions.remove(&id); - self.state.gateways_looked_up.remove(&id); - self.state.bookmarks = self.store.bookmarks().unwrap_or_default(); - self.state.current = self.state.bookmarks.first().map(|b| b.id); - self.prefetch_counts(); - self.track_reading(); - self.refresh_all(); - } - - pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef { - let current = self - .state - .sessions - .get(&bookmark.id) - .map(|view| view.server_icon_for(&bookmark.address)) - .unwrap_or_default(); - if current.size().width > 0 { - current - } else { - vm::servers::cached_icon(bookmark, &self.engine.cache()) - } - } - - /// A server's colour, as the rail shows it ([`vm::servers::tints`]); none - /// for a server that is not in the list (a chat that outlived its - /// bookmark), where the caller picks a colour of its own. - pub(crate) fn server_tint(&self, id: i64) -> Option { - let tints = vm::servers::tints(&self.state.bookmarks); - self.state.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]) - } - - /// The rail: servers with their state, unread count (without private - /// chats) and streams; what the chat strip and the private chats have - /// unread. - pub(crate) fn refresh_servers(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let tints = vm::servers::tints(&self.state.bookmarks); - let items: Vec<_> = self - .state - .bookmarks - .iter() - .zip(tints) - .map(|(b, tint)| { - let view = self.state.sessions.get(&b.id); - let state = view.map(|v| v.state.clone()).unwrap_or_default(); - let unread = view.map_or(0, SessionView::channel_unread); - let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty()); - let detail = view - .filter(|v| !v.presence.channels.is_empty()) - .map(|v| vm::tree::stats(&v.presence)) - .unwrap_or_default(); - let product = view.map(|v| v.extra.product.clone()).unwrap_or_default(); - let icon = self.server_list_icon(b); - vm::servers::item(b, &state, unread, live, detail, product, icon, tint) - }) - .collect(); - self.models.servers.sync(&items); - bridge.set_last_place(self.last_place(&items).into()); - bridge.set_current_server(self.state.current.map_or(-1, |id| id as i32)); - // Private chats count on the messages page (and the phone's Home). - bridge.set_unread_total(self.view().map_or(0, SessionView::channel_unread)); - bridge.set_dm_unread(self.dm_unread()); - } - - /// The server card, the voice controls and who we are. - pub(crate) fn refresh_toolbar(&self) { - let Some(ui) = self.ui.upgrade() else { return }; - let bridge = ui.global::(); - let bookmark = self.state.current.and_then(|id| self.bookmark(id)); - let view = self.view(); - let state = view.map(|v| v.state.clone()).unwrap_or_default(); - bridge.set_server_icon(convert::image( - &bookmark.map(|b| self.server_list_icon(b)).unwrap_or_default(), - )); - bridge.set_server_title( - bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(), - ); - let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty()) - && (state.voice == VoiceState::Connected || state.observe == ObserveState::Observing); - bridge.set_server_stats( - view.filter(|_| has_presence) - .map(|v| vm::tree::stats(&v.presence)) - .unwrap_or_default() - .into(), - ); - bridge.set_nickname(bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into()); - let own = view.zip(state.own_client).and_then(|(v, c)| v.avatar(c)); - bridge.set_own_avatar(convert::image(&vm::avatar::image(own))); - let banner = |url: Option<&str>| { - view.map(|v| vm::tree::banner(&v.pictures, url)).unwrap_or_default() - }; - let details = view.map(|v| &v.presence.server); - bridge - .set_server_banner(convert::image(&banner(details.map(|d| d.banner_gfx_url.as_str())))); - bridge.set_server_banner_mode(details.map_or(0, |d| vm::tree::banner_mode(d.banner_mode))); - let own_channel = - view.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c))); - bridge.set_own_channel( - own_channel.map(|c| vm::tree::channel_title(c).0).unwrap_or_default().into(), - ); - bridge.set_own_channel_topic( - own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), - ); - bridge.set_own_channel_banner(convert::image(&banner( - own_channel.and_then(|c| c.banner_gfx_url.as_deref()), - ))); - bridge.set_own_channel_banner_mode( - own_channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)), - ); - bridge.set_own_channel_limit( - own_channel.and_then(|c| c.max_clients).filter(|m| *m >= 0).unwrap_or(-1), - ); - bridge.set_voice_connected(state.voice == VoiceState::Connected); - bridge.set_voice_connecting(state.voice == VoiceState::Connecting); - bridge.set_observing(state.observe != ObserveState::Off); - bridge.set_input_muted(state.input_muted); - bridge.set_output_muted(state.output_muted); - bridge.set_transmitting(state.transmitting); - bridge.set_presence_source( - match state.presence_source { - Some(Source::Voice) => "live (voice)", - Some(Source::Gateway) => "invisible (gateway)", - Some(Source::Query) => "invisible (query)", - None => "", - } - .into(), - ); - if state.voice != VoiceState::Connected { - bridge.set_input_level(-100.0); - bridge.set_input_sending(false); - } - } - - /// The channel tree, the members of our channel and everyone on the - /// server. - pub(crate) fn refresh_tree(&self) { - let Some(view) = self.view() else { - self.models.tree.sync(&[]); - self.models.members.sync(&[]); - self.models.server_members.sync(&[]); - return; - }; - let input = vm::tree::TreeInput { - presence: &view.presence, - collapsed: &view.collapsed, - talking: &view.talking, - playback: &self.state.playback, - own_channel: view.state.own_channel, - own_client: view.state.own_client, - filter: "", - avatars: &view.avatars, - icons: &view.icons, - pictures: &view.pictures, - groups: &view.server_groups, - channel_groups: &view.channel_groups, - }; - self.models.tree.sync(&vm::tree::rows(&input)); - let connected = view.state.voice == VoiceState::Connected; - let members = if connected { vm::tree::members(&input) } else { Vec::new() }; - self.models.members.sync(&members); - // The people in our channel first while their view is shown (not - // while the stream plays in a window of its own). - let watching = - self.state.watch.as_ref().is_some_and(|w| w.shown) && self.popout.window.is_none(); - let voice_first = connected && (self.state.voice_view || watching); - let everyone = vm::tree::server_members(&input, voice_first); - let filter = self.state.member_filter.trim().to_lowercase(); - let shown = - if filter.is_empty() { everyone } else { vm::tree::matching(everyone, &filter) }; - self.models.server_members.sync(&shown); - if let Some(ui) = self.ui.upgrade() { - let total = view.presence.clients.values().filter(|c| !c.is_query).count(); - ui.global::().set_member_total(total as i32); - } - } - - /// The members panel's search. - pub(crate) fn search_members(&mut self, text: String) { - if self.state.member_filter != text { - self.state.member_filter = text; - self.refresh_tree(); - } - } - - /// The voice channel view was opened or closed: its chat is our - /// channel's, and its people lead the members panel. - pub(crate) fn show_voice_view(&mut self, on: bool) { - self.state.voice_view = on; - if on && let Some(channel) = self.view().and_then(|v| v.state.own_channel) { - self.open_chat(voelin_model::ChatTarget::Channel(channel), true); - } - self.refresh_tree(); - } - - /// A link to the voice channel we are in, for the Invite button (which - /// copies it, and the copy's toast names the channel); empty, with a - /// note, without one. - pub(crate) fn invite_link(&mut self) -> String { - let bookmark = - self.state.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone()); - let path = self.view().and_then(|v| { - let cid = v.state.own_channel?; - let own = v.presence.channels.get(&cid)?; - // The link names the channels as the server has them; the - // toast as the tree shows them. - Some(( - vm::tree::channel_path(&v.presence, cid), - vm::tree::channel_title(own).0.to_owned(), - )) - }); - let (Some(address), Some((path, title))) = (bookmark, path) else { - self.set_status("Join a voice channel to invite others to it"); - return String::new(); - }; - let path: Vec<&str> = path.iter().map(String::as_str).collect(); - let link = vm::servers::invite_link(&address, &path); - self.state.copy_note = Some(format!("Copied an invite to {title}: {link}")); - link - } - - /// Join a channel of a session (a double-click in the tree, joining a - /// friend): move there with voice, or connect into it. A locked channel - /// asks for its password first, unless it was given this connection. - pub(crate) fn join_channel(&mut self, session: i64, channel: ChannelId) { - let Some(view) = self.state.sessions.get(&session) else { return }; - let Some(info) = view.presence.channels.get(&channel) else { return }; - let remembered = view.channel_passwords.get(&channel).map(String::as_str); - match vm::servers::join_password(info, remembered) { - JoinStep::Send(password) => self.enter_channel(session, channel, password), - JoinStep::Ask => self.ask_channel_password(session, channel, false), - } - } - - /// The password dialog's Join. - pub(crate) fn join_with_password(&mut self, password: String) { - let Some((session, channel)) = self.state.join_target.take() else { return }; - if password.is_empty() { - return; - } - if let Some(view) = self.state.sessions.get_mut(&session) { - view.channel_passwords.insert(channel, password.clone()); - } - self.enter_channel(session, channel, Some(password)); - } - - /// Move into a channel; without voice on its server, connect into it. - fn enter_channel(&mut self, session: i64, channel: ChannelId, password: Option) { - let Some(view) = self.state.sessions.get_mut(&session) else { return }; - if view.state.voice != VoiceState::Disconnected { - // Chosen while connecting: no longer the one to join after. - view.join_after_connect = None; - if !self.demo_ui { - self.engine.send(Command::MoveToChannel { - session: session as u64, - channel, - password, - }); - } - return; - } - if self.state.current != Some(session) { - self.select_server(session); - } - // By id: by its name the server finds only a top-level channel (a - // subchannel's name connects into the default channel). - if self.connect_voice_to(Some(format!("/{channel}")), password, None) - && let Some(view) = self.state.sessions.get_mut(&session) - { - view.join_after_connect = Some(channel); - } - } - - /// Open the password dialog for a locked channel; `wrong`: the one given - /// was refused. - fn ask_channel_password(&mut self, session: i64, channel: ChannelId, wrong: bool) { - self.transition(|state, cx| { - vm::events::ask_password(state, cx, session, channel, wrong); - }); - } - - /// The server refused a move ([`voelin_core::Event::JoinFailed`]): a - /// password asks again (the one given is forgotten), the rest is a - /// toast. - pub(crate) fn join_failed(&mut self, session: i64, channel: ChannelId, reason: JoinFailure) { - self.transition(|state, cx| vm::events::join_failed(state, cx, session, channel, reason)); - } - - pub(crate) fn toggle_collapse(&mut self, channel: u64) { - if let Some(view) = self.view_mut() - && !view.collapsed.remove(&channel) - { - view.collapsed.insert(channel); - } - self.refresh_tree(); - } -} - -#[cfg(test)] -mod tests { - use voelin_core::identity::Found; - - use super::*; - use crate::vm::events::apply_server_icon; - use voelin_store::QueryConfig; - - #[test] - fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() { - let path = std::env::temp_dir() - .join(format!("voelin-server-icon-provenance-{}.svg", std::process::id())); - std::fs::write(&path, r#""#).unwrap(); - let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() }; - let mut view = SessionView::default(); - view.icons.insert(1234, path.clone()); - assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234)); - assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4); - - bookmark = bookmark_from_form( - Some(&bookmark), - &BookmarkForm { address: "b.test".into(), ..Default::default() }, - || "Me".into(), - ); - // Connecting does not retag received imagery. A failed B connection - // must not make A's image appear under B's name. - for state in [VoiceState::Connecting, VoiceState::Disconnected] { - view.state.voice = state; - assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0); - } - assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321)); - assert_eq!(view.server_icon, 1234); - assert_eq!(view.icon_address.as_deref(), Some("a.test")); - assert!(bookmark.server_icon_id().is_none()); - - // Equal icon IDs on the next server still need new provenance. - assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234)); - assert_eq!(bookmark.server_icon_id(), Some(1234)); - assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4); - assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0)); - assert_eq!(bookmark.server_icon_id(), Some(1234)); - assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0)); - assert!(bookmark.server_icon_id().is_none()); - assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn the_address_alone_makes_a_server() { - let form = - BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() }; - let b = bookmark_from_form(None, &form, || "Nick".into()); - assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test")); - assert_eq!(b.nickname, "Nick"); - assert_eq!( - (b.gateway_url, b.query, b.identity, b.default_channel), - (None, None, None, None) - ); - } - - #[test] - fn editing_keeps_what_the_form_does_not_show() { - let old = Bookmark { - id: 7, - name: "Old".into(), - address: "old.example.test".into(), - nickname: "Me".into(), - identity: Some(2), - default_channel: Some("Lobby/Sub".into()), - gateway_url: Some("ws://gw.example.test:7788/v1".into()), - gateway_urls: vec!["ws://gw.example.test:7788/v1".into()], - query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }), - client_version: Some("linux".into()), - cached_server_icon: Some(voelin_store::CachedServerIcon { - address: "old.example.test".into(), - id: 1234, - }), - }; - // Same address: the gateway found and the query login stay. - let same = BookmarkForm { - id: 7, - name: "Mine".into(), - address: "old.example.test".into(), - nickname: "Other".into(), - ..Default::default() - }; - let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given")); - assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other")); - assert_eq!(b.gateway_url, old.gateway_url); - assert_eq!(b.query, old.query); - assert_eq!(b.cached_server_icon, old.cached_server_icon); - // Another address: looked up again, for the new server. - let form = BookmarkForm { address: "new.example.test:9988".into(), ..same }; - let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given")); - assert_eq!(b.address, "new.example.test:9988"); - assert!(b.cached_server_icon.is_none()); - assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into()))); - assert_eq!(b.client_version.as_deref(), Some("linux")); - assert_eq!((b.gateway_url, b.query), (None, None)); - assert!(b.gateway_urls.is_empty()); - } - - #[test] - fn the_import_is_told_by_nickname() { - let found = |nickname: &str| Found { - nickname: nickname.into(), - identity: tsclientlib::Identity::create(), - source: "settings.db".into(), - selected: false, - }; - let report = |added: &[&str], default: Option<&str>, replaced| LaunchImport { - added: added.iter().map(|n| found(n)).collect(), - default: default.map(found), - replaced, - }; - assert_eq!(imported_status(&report(&[], None, false)), None); - assert_eq!( - imported_status(&report(&["Main"], Some("Main"), false)).unwrap(), - "Using your TeamSpeak identity \u{201c}Main\u{201d}" - ); - assert_eq!( - imported_status(&report(&["Main", "Alt"], None, false)).unwrap(), - "Imported 2 identities from TeamSpeak: Main, Alt" - ); - // Imported earlier, now ours instead of the one the app made. - assert_eq!( - imported_status(&report(&[], Some("Main"), true)).unwrap(), - "You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept" - ); - } - - #[test] - fn a_gateway_found_again_is_not_logged_in_again() { - let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1"); - let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::>(); - let stays = |previous: &[&str], found: &[&str], observe| { - observing_stays(&urls(previous), &urls(found), Some(plain), observe) - }; - // The same ones (an older version kept only the one in use). - assert!(stays(&[plain], &[plain], ObserveState::Connecting)); - assert!(stays(&[plain], &[plain], ObserveState::Observing)); - // Logged in through one still published. - assert!(stays(&[plain], &[tls, plain], ObserveState::Observing)); - // Not logged in yet: through the new ones. - assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting)); - // The one in use is no longer published. - assert!(!stays(&[plain], &[tls], ObserveState::Observing)); - assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off)); - } -} diff --git a/crates/voelin-ui/src/servers/bind.rs b/crates/voelin-ui/src/servers/bind.rs new file mode 100644 index 0000000..0d1d3b2 --- /dev/null +++ b/crates/voelin-ui/src/servers/bind.rs @@ -0,0 +1,458 @@ +//! The Slint side of the servers: connecting and observing (the store, the +//! secrets, the engine), the Bridge writes of the rail, the server card and +//! the channel tree, and the callbacks' ways into the transitions of +//! `voelin_ui_vm::servers::logic`. + +use std::time::Instant; + +use slint::ComponentHandle; +use tracing::{debug, info, warn}; +use voelin_core::{Command, JoinFailure, ObserveState}; +use voelin_model::ChannelId; +use voelin_store::{Bookmark, QueryTransport}; + +use crate::app::{App, Bridge, later}; +use crate::bind::convert; +use crate::vm; +use crate::vm::bridge::BookmarkForm; +use crate::vm::servers::logic::{self as logic, GatewayFound, ObservePlan}; + +impl App { + pub(crate) fn connect_voice(&mut self) { + let channel = self + .state + .current + .and_then(|id| self.bookmark(id)) + .and_then(|b| b.default_channel.clone()); + self.connect_voice_to(channel, None, None); + } + + /// Connect the current server with voice, into `channel` (a path, or + /// `/`, with its password) if given, with a privilege key if given; + /// whether it was asked for. + pub(crate) fn connect_voice_to( + &mut self, + channel: Option, + channel_password: Option, + token: Option, + ) -> bool { + let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else { + return false; + }; + if self.demo_ui { + return false; + } + let mut options = match logic::voice_options(&b, channel, channel_password, token) { + Ok(options) => options, + Err(error) => { + self.set_status(error); + return false; + } + }; + options.identity = Some(self.identity_for(Some(b.id))); + options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten(); + options.stream_peer = self.video.peer_config(options.stream_peer); + self.engine + .send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) }); + self.set_status(format!("Connecting to {}…", b.address)); + // The admin may have published the gateway since it was added. + self.discover_gateway(b.id); + true + } + + /// The nickname a new server gets: the default identity's (one imported + /// from TeamSpeak keeps the nickname used there), else the system user's. + pub(crate) fn default_nickname(&self) -> String { + self.store + .default_identity() + .ok() + .flatten() + .map(|identity| identity.name) + .filter(|name| { + ![logic::CREATED_IDENTITY, voelin_core::identity::DEFAULT_NICKNAME] + .contains(&name.as_str()) + }) + .or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok()) + // Servers refuse an empty nickname (Android has no user name). + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| "Voelin user".to_owned()) + } + + /// Look up the gateway of a server ([`voelin_core::discover`]), once a + /// run ([`logic::discover_wanted`]): every one the server publishes is + /// kept, best first, and tried in turn; they take the place of a stored + /// one that is no longer published (a gateway that moved, or one typed + /// into an older version, which showed the field). Nothing found keeps + /// what is stored. + pub(crate) fn discover_gateway(&mut self, id: i64) { + let Some(address) = self.transition(|state, cx| logic::discover_wanted(state, cx, id)) + else { + return; + }; + self.engine.runtime().spawn(async move { + let started = Instant::now(); + let urls = voelin_core::discover::gateways(&address).await; + let elapsed_ms = started.elapsed().as_millis() as u64; + if urls.is_empty() { + info!(server = %address, elapsed_ms, "no gateway published"); + } else { + later(move |app| app.gateway_found(id, &address, urls, elapsed_ms)); + } + }); + } + + /// Gateways were found for the server at `address` (best first); they + /// are kept unless the server changed meanwhile ([`logic::gateway_found`]), + /// and the server is observed through them if it is the one shown. Users + /// never hear of them (logged only). + fn gateway_found(&mut self, id: i64, address: &str, urls: Vec, elapsed_ms: u64) { + let found = self.transition(|state, cx| logic::gateway_found(state, cx, id, address, urls)); + match found { + GatewayFound::Same => { + debug!(server = %address, elapsed_ms, "gateway found, as kept"); + } + GatewayFound::Kept { observe } => { + info!(server = %address, elapsed_ms, kept = true, "gateway found"); + if observe { + self.observe(id); + } + } + GatewayFound::Changed { stop, observe, urls } => { + info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found"); + if stop { + self.engine.send(Command::StopObserving { session: id as u64 }); + } + if observe { + self.observe(id); + } + } + } + } + + /// Observe the server invisibly ([`logic::observe_plan`]): through its + /// gateway, else its own query login. Without either the gateway is + /// looked up first, and observing starts when it is found + /// (`gateway_found`). + pub(crate) fn observe(&mut self, id: i64) { + let Some(b) = self.bookmark(id).cloned() else { return }; + let session = b.id as u64; + match self.transition(|state, cx| logic::observe_plan(state, cx, id)) { + ObservePlan::Nothing => return, + ObservePlan::Retry(urls) => { + debug!(server = %b.address, "still connecting to the gateway: try now"); + self.engine.send(Command::ObserveGateway { + session, + urls, + identity: Box::new(self.identity_for(Some(b.id))), + }); + return; + } + ObservePlan::Gateway(urls) => { + info!(server = %b.address, ?urls, "observing through the gateway"); + self.engine.send(Command::ObserveGateway { + session, + urls, + identity: Box::new(self.identity_for(Some(b.id))), + }); + // Still the one the server publishes? + self.discover_gateway(b.id); + } + ObservePlan::Query(q) => { + let secret = self.secrets.get(&b.query_password_key()).ok().flatten(); + let transport = match q.transport { + QueryTransport::Raw => voelin_query::Transport::Raw, + QueryTransport::Ssh => voelin_query::Transport::Ssh, + QueryTransport::Http => voelin_query::Transport::Http, + }; + let connect = voelin_query::Connect { + transport, + addr: format!("{}:{}", q.host, q.port), + user: q.user.clone(), + secret, + server_port: q.server_port, + server_id: None, + line: Default::default(), + }; + self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) }); + } + ObservePlan::Discover => { + self.discover_gateway(b.id); + return; + } + } + self.set_status("Observing invisibly…"); + } + + /// Show a server, and observe it. + pub(crate) fn select_server(&mut self, id: i64) { + self.transition(|state, cx| logic::select_server(state, cx, id)); + self.observe(id); + } + + pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm { + let Some(b) = self.bookmark(id) else { + return BookmarkForm { + id: -1, + nickname: self.default_nickname().into(), + ..Default::default() + }; + }; + let password = self.secrets.get(&b.server_password_key()).ok().flatten(); + let state = self.state.sessions.get(&b.id).map(|view| &view.state); + vm::servers::form(b, state, password.as_deref().unwrap_or_default()) + } + + /// Save the server dialog's server, and show it; its id, none when it + /// could not be saved (the toast says why). + pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option { + let old = self.bookmark(form.id as i64).cloned(); + let mut bookmark = + logic::bookmark_from_form(old.as_ref(), form, || self.default_nickname()); + let result = if bookmark.id < 0 { + self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id) + } else { + self.store.update_bookmark(&bookmark) + }; + if let Err(e) = result { + self.set_status(format!("Could not save: {e}")); + return None; + } + let key = bookmark.server_password_key(); + let result = if form.server_password.is_empty() { + self.secrets.delete(&key) + } else { + self.secrets.set(&key, &form.server_password) + }; + if let Err(e) = result { + warn!(%e, "could not store secret"); + } + // Another server: what was observed is the old one's, and its + // gateway is looked up anew. + if let Some(old) = old.filter(|old| old.address != bookmark.address) { + if old.query.is_some() { + let _ = self.secrets.delete(&old.query_password_key()); + } + self.state.gateways_looked_up.remove(&bookmark.id); + self.engine.send(Command::StopObserving { session: bookmark.id as u64 }); + if let Some(view) = self.state.sessions.get_mut(&bookmark.id) { + view.state.observe = ObserveState::Off; + } + } + self.state.bookmarks = self.store.bookmarks().unwrap_or_default(); + self.select_server(bookmark.id); + Some(bookmark.id) + } + + /// The server dialog's Connect: save the server, then connect it with + /// voice, into the channel of the link that filled the form if one did + /// ([`vm::servers::connect_to`]). Only once saved: connecting what is + /// shown after a failed save would connect the server shown before. + /// Whether it was saved. + pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool { + let saved = self.save_bookmark(form); + let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else { + return false; + }; + self.connect_voice_to(to.channel, to.channel_password, to.token); + true + } + + pub(crate) fn delete_bookmark(&mut self, id: i64) { + self.engine.send(Command::CloseSession { session: id as u64 }); + if let Some(b) = self.bookmark(id).cloned() { + let _ = self.secrets.delete(&b.server_password_key()); + let _ = self.secrets.delete(&b.query_password_key()); + } + let _ = self.store.delete_bookmark(id); + let bookmarks = self.store.bookmarks().unwrap_or_default(); + self.transition(|state, cx| logic::forget_server(state, cx, id, bookmarks)); + } + + pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef { + let current = self + .state + .sessions + .get(&bookmark.id) + .map(|view| view.server_icon_for(&bookmark.address)) + .unwrap_or_default(); + if current.size().width > 0 { + current + } else { + vm::servers::cached_icon(bookmark, &self.engine.cache()) + } + } + + /// A server's colour, as the rail shows it ([`logic::server_tint`]); + /// none for a server that is not in the list (a chat that outlived its + /// bookmark), where the caller picks a colour of its own. + pub(crate) fn server_tint(&self, id: i64) -> Option { + logic::server_tint(&self.state, id) + } + + /// The rail: servers with their state, unread count (without private + /// chats) and streams; what the chat strip and the private chats have + /// unread. + pub(crate) fn refresh_servers(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let items = logic::rail(&self.state, |b| self.server_list_icon(b)); + self.models.servers.sync(&items); + bridge.set_last_place(self.last_place(&items).into()); + bridge.set_current_server(self.state.current.map_or(-1, |id| id as i32)); + // Private chats count on the messages page (and the phone's Home). + bridge.set_unread_total(self.view().map_or(0, crate::app::SessionView::channel_unread)); + bridge.set_dm_unread(self.dm_unread()); + } + + /// The server card, the voice controls and who we are + /// ([`logic::toolbar`]). + pub(crate) fn refresh_toolbar(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let card = logic::toolbar(&self.state, |b| self.server_list_icon(b)); + bridge.set_server_icon(convert::image(&card.server_icon)); + bridge.set_server_title(card.server_title.into()); + bridge.set_server_stats(card.server_stats.into()); + bridge.set_nickname(card.nickname.into()); + bridge.set_own_avatar(convert::image(&card.own_avatar)); + bridge.set_server_banner(convert::image(&card.server_banner)); + bridge.set_server_banner_mode(card.server_banner_mode); + bridge.set_own_channel(card.own_channel.into()); + bridge.set_own_channel_topic(card.own_channel_topic.into()); + bridge.set_own_channel_banner(convert::image(&card.own_channel_banner)); + bridge.set_own_channel_banner_mode(card.own_channel_banner_mode); + bridge.set_own_channel_limit(card.own_channel_limit); + bridge.set_voice_connected(card.voice_connected); + bridge.set_voice_connecting(card.voice_connecting); + bridge.set_observing(card.observing); + bridge.set_input_muted(card.input_muted); + bridge.set_output_muted(card.output_muted); + bridge.set_transmitting(card.transmitting); + bridge.set_presence_source(card.presence_source.into()); + if !card.voice_connected { + bridge.set_input_level(-100.0); + bridge.set_input_sending(false); + } + } + + /// The channel tree, the members of our channel and everyone on the + /// server ([`logic::tree_view`]). + pub(crate) fn refresh_tree(&self) { + let Some(tree) = logic::tree_view(&self.state, self.popout.window.is_some()) else { + self.models.tree.sync(&[]); + self.models.members.sync(&[]); + self.models.server_members.sync(&[]); + return; + }; + self.models.tree.sync(&tree.rows); + self.models.members.sync(&tree.members); + self.models.server_members.sync(&tree.server_members); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_member_total(tree.member_total); + } + } + + /// The members panel's search. + pub(crate) fn search_members(&mut self, text: String) { + self.transition(|state, cx| logic::search_members(state, cx, text)); + } + + /// The voice channel view was opened or closed. + pub(crate) fn show_voice_view(&mut self, on: bool) { + self.transition(|state, cx| logic::show_voice_view(state, cx, on)); + } + + /// A link to the voice channel we are in, for the Invite button; empty, + /// with a note, without one ([`logic::invite_link`]). + pub(crate) fn invite_link(&mut self) -> String { + match logic::invite_link(&mut self.state) { + Ok(link) => link, + Err(why) => { + self.set_status(why); + String::new() + } + } + } + + /// Join a channel of a session ([`logic::join_channel`]): the transition + /// moves there with voice or asks for the password; without voice on that + /// server we connect into it. + pub(crate) fn join_channel(&mut self, session: i64, channel: ChannelId) { + if let Some(password) = + self.transition(|state, cx| logic::join_channel(state, cx, session, channel)) + { + self.connect_into(session, channel, password); + } + } + + /// The password dialog's Join. + pub(crate) fn join_with_password(&mut self, password: String) { + if let Some((session, channel, password)) = + self.transition(|state, cx| logic::join_with_password(state, cx, password)) + { + self.connect_into(session, channel, password); + } + } + + /// Connect voice into a channel of a server that has none. + fn connect_into(&mut self, session: i64, channel: ChannelId, password: Option) { + if self.state.current != Some(session) { + self.select_server(session); + } + // By id: by its name the server finds only a top-level channel (a + // subchannel's name connects into the default channel). + if self.connect_voice_to(Some(format!("/{channel}")), password, None) { + logic::join_after_connect(&mut self.state, session, channel); + } + } + + /// The server refused a move ([`voelin_core::Event::JoinFailed`]): a + /// password asks again (the one given is forgotten), the rest is a + /// toast. + pub(crate) fn join_failed(&mut self, session: i64, channel: ChannelId, reason: JoinFailure) { + self.transition(|state, cx| vm::events::join_failed(state, cx, session, channel, reason)); + } + + pub(crate) fn toggle_collapse(&mut self, channel: u64) { + self.transition(|state, cx| logic::toggle_collapse(state, cx, channel)); + } +} + +#[cfg(test)] +mod tests { + use voelin_core::identity::{Found, LaunchImport}; + + use super::*; + + /// The report is the engine's ([`LaunchImport`], with identities of + /// `tsclientlib`, which the view model crate does not have). + #[test] + fn the_import_is_told_by_nickname() { + let found = |nickname: &str| Found { + nickname: nickname.into(), + identity: tsclientlib::Identity::create(), + source: "settings.db".into(), + selected: false, + }; + let report = |added: &[&str], default: Option<&str>, replaced| LaunchImport { + added: added.iter().map(|n| found(n)).collect(), + default: default.map(found), + replaced, + }; + let told = logic::imported_status; + assert_eq!(told(&report(&[], None, false)), None); + assert_eq!( + told(&report(&["Main"], Some("Main"), false)).unwrap(), + "Using your TeamSpeak identity \u{201c}Main\u{201d}" + ); + assert_eq!( + told(&report(&["Main", "Alt"], None, false)).unwrap(), + "Imported 2 identities from TeamSpeak: Main, Alt" + ); + // Imported earlier, now ours instead of the one the app made. + assert_eq!( + told(&report(&[], Some("Main"), true)).unwrap(), + "You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept" + ); + } +} diff --git a/crates/voelin-ui/src/servers/mod.rs b/crates/voelin-ui/src/servers/mod.rs new file mode 100644 index 0000000..1cb23a4 --- /dev/null +++ b/crates/voelin-ui/src/servers/mod.rs @@ -0,0 +1,8 @@ +//! Servers: bookmarks, connecting and observing, the rail, the sidebar's +//! server card and the channel tree. What the state does (which server is +//! shown, how it is observed, the rail, the card and the tree as plain data, +//! joining a channel) is in `voelin_ui_vm::servers::logic`; `bind` has the +//! store and the secrets, the engine's commands and the Bridge and model +//! writes. + +mod bind; diff --git a/docs/ui.md b/docs/ui.md index c57d7df..ea7bb84 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -27,13 +27,15 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit events/ events::apply: what an engine event does to the AppState (mod.rs; gateway.rs: the gateway's events and directory) previews.rs pictures linked in chat: which to fetch, the transfers - servers.rs tree.rs chat/mod.rs social.rs home.rs streams/mod.rs avatar.rs studio/mod.rs + servers/mod.rs tree.rs chat/mod.rs social.rs home.rs streams/mod.rs avatar.rs studio/mod.rs pure view models (engine state → bridge structs), unit-tested chat/logic.rs chat tabs, messages and what is read, pins and topics, files; the chat view (tabs, lines, divider, drawers) and the user's moves streams/logic.rs the streams we share and watch: their state, the events and the user's choices, the streams panel's, the share card's and the viewer's rows and texts + servers/logic.rs which server is shown and how it is observed, joining a channel; + the rail, the server card and the channel tree as plain data settings.rs the UI's settings keys, the audio form settings_pages/logic.rs, studio/logic.rs the decisions of the settings pages and of the Stream Studio @@ -67,12 +69,14 @@ crates/voelin-ui/ the Slint front end a `voelin_ui_vm::state::AppState` and the window host.rs SlintHost (the answers the transitions ask for), `App::apply_event`, `transition` and `perform`: doing what an `Update` says - servers.rs members.rs settings_page.rs appearance.rs + members.rs settings_page.rs appearance.rs home.rs social.rs messages.rs events.rs previews.rs popout.rs the Slint side of each area (social.rs: contacts, the bell and the search; previews.rs: pictures in chat; popout.rs: the stream's own window) chat/ mod.rs, bind.rs: the chat view's Bridge writes and models + servers/ mod.rs, bind.rs: connecting and observing (store, secrets, engine), + the rail, the server card and the tree on the Bridge settings_pages/ mod.rs (Pages), bind.rs: the settings pages on the Bridge streams/ mod.rs (Share: the capture), bind.rs: the streams panel, the share dialog and the viewer on the Bridge, the capture and the decoder @@ -150,7 +154,7 @@ this file is `voelin_ui_vm::chat`. The boundary: settings service, the `AppState` and plain rows; they return rows, commands or messages for the status line, and write no Bridge) and `/bind.rs` in `voelin-ui` (the Bridge and model writes, windows, - timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams` and `chat`. + timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams`, `chat` and `servers`. The pure code is tested in `voelin-ui-vm` (`cargo test -p voelin-ui-vm`, no display); the Slint crate's tests are what needs the window types. @@ -172,7 +176,6 @@ the same shape as `settings_pages` and `studio`: move the decisions into | File | `.set_` calls | What it mixes | |---|---|---| | `app.rs` | 31 | setup, the status line, the toolbar and tree refreshes (the event dispatch is `vm::events::apply`) | -| `servers.rs` | 32 | the rail, the server dialog and the channel tree's refresh (the server's name, icon and gateway, joining again and the password are in `events`) | | `settings_page.rs` | 26 | the audio settings page and the devices | | `social.rs` | 23 | home's contacts, the bell and the search | | `dev.rs` | 23 | development switches and the sample data (the switches stay with the window; the sample rows can move) | @@ -187,7 +190,8 @@ and `settings_pages.rs` 52 (the two with the most, then `streams.rs` with 45; 62 was `studio.rs` once the view models had moved, two setters having gone with them). Their `bind.rs` files still show 58 and 51 (and `streams/bind.rs`, split from the 45 of `streams.rs`, 38, and -`chat/bind.rs`, from the 38 of `chat.rs`, 31): the Bridge and +`chat/bind.rs`, from the 38 of `chat.rs`, 31, and `servers/bind.rs`, from +the 32 of `servers.rs`, 31): the Bridge and model writes stay where the toolkit is, and what each write says now comes from `logic.rs`, which has tests of its own.