The ui-vm gate's minor "server_tint falls back to black" was closed by a fallback in App::conversation_item, `.unwrap_or_else(|| vm::avatar::tint(&title))`, that no test could fail: replacing it with `.unwrap_or_default()` (opaque black) left cargo test -p voelin-ui -p voelin-ui-vm green. The choice of (kind, session) -> colour is now a pure function in voelin-ui-vm, servers::logic::conversation_tint(state, kind, session, title), and messages.rs calls it. A test pins the three cases: a server chat of a server in the list takes the rail's colour, a server chat whose server is gone takes the colour of its title, and a channel's or a person's chat (with or without a known server) takes the colour of its title. The titles are chosen so that the title's colour differs from the server's, and the test asserts that. App::server_tint, whose only caller this was, is removed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
456 lines
16 KiB
Rust
456 lines
16 KiB
Rust
//! 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
|
|
/// `/<id>`, 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<String>,
|
|
channel_password: Option<String>,
|
|
token: Option<String>,
|
|
) -> 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(voelin_core::ts::identity::to_blob(&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::ts::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<String>, 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(voelin_core::ts::identity::to_blob(
|
|
&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(voelin_core::ts::identity::to_blob(
|
|
&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_core::QueryTransport::Raw,
|
|
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
|
|
QueryTransport::Http => voelin_core::QueryTransport::Http,
|
|
};
|
|
let connect = voelin_core::QueryLogin {
|
|
transport,
|
|
address: format!("{}:{}", q.host, q.port),
|
|
user: q.user.clone(),
|
|
secret,
|
|
server_port: q.server_port,
|
|
server_id: None,
|
|
allowlisted: false,
|
|
};
|
|
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<i64> {
|
|
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())
|
|
}
|
|
}
|
|
|
|
/// 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::<Bridge>();
|
|
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::<Bridge>();
|
|
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::<Bridge>().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<String>) {
|
|
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::ts::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"
|
|
);
|
|
}
|
|
}
|