voelin-ui-vm: the server sequences both front ends ran twice are one

The GPUI shell repeated the Slint crate's connect, observe, gateway lookup,
save and remove of a server, its default nickname, its FallbackSecrets and its
settings opening and key registration. They now live once and both front ends
call them:

- voelin_ui_vm::servers::sequence: connect_voice(_to), observe,
  discover_gateway, gateway_found, select_server, save_bookmark,
  save_and_connect, delete_bookmark, bookmark_form and default_nickname, as
  transitions over the state, the Cx and a Backing (the store, the secrets,
  the identity a connection uses). The commands, the status line and what to
  keep go out through the Update as for every other transition; a new field,
  Update::discover, asks the front end to look a gateway up (the thread hop
  stays with each front end: Later in GPUI, later() in Slint). stream_peer is
  the one input a front end gives (Slint's codecs; GPUI passes none).
- voelin_ui_vm::settings::open_settings and register_keys; a front end adds
  its own key (ui.window, studio.ui) through a function it passes, so Slint's
  settings page still lists what it listed.
- voelin_store::FallbackSecrets (feature keyring) and Store::identity_for.
- voelin-ui: the methods of servers/bind.rs, open_settings and default_secrets
  call them, so their call sites are unchanged; host.rs gets transition_with
  and the discover arm of perform. voelin-gpui: AppState's methods and the
  Backend call them. What cannot move is named in docs/ui.md.

voelin-ui-vm now depends on tracing (the sequences log as the copies did): one
line of Cargo.lock, THIRD_PARTY_NOTICES.md unchanged (scripts/notices.sh
--check clean), cargo deny check clean. The sequences have ten tests over a
fake front end (commands, status, store, secrets, gateways), open_settings and
Store::identity_for one each; the GPUI and Slint suites pass unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-27 20:05:46 +03:00
1 parent 01bf128c58
commit a77ccc0415
15 files changed
+1148 -578

No files matched your search

Generated
+1
View File
@@ -12790,6 +12790,7 @@ dependencies = [
"roxmltree 0.21.1", "roxmltree 0.21.1",
"serde", "serde",
"serde_json", "serde_json",
"tracing",
"unicode-segmentation", "unicode-segmentation",
"voelin-audio", "voelin-audio",
"voelin-core", "voelin-core",
+89 -194
View File
@@ -29,19 +29,20 @@
//! streams' capture and decoder are for the slices that have those parts. //! streams' capture and decoder are for the slices that have those parts.
use std::task::Poll; use std::task::Poll;
use std::time::{Duration, Instant}; use std::time::Duration;
use gpui_kit::{ClipboardItem, Context}; use gpui_kit::{ClipboardItem, Context};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tracing::{debug, info, warn}; use tracing::{debug, warn};
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings}; use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
use voelin_core::{Command, Engine, Event, ObserveState, VoiceState}; use voelin_core::{Command, Engine, Event, VoiceState};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, QueryTransport, Store}; use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, Store};
use voelin_ui_vm::bridge::{BookmarkForm, ChatLine}; use voelin_ui_vm::bridge::{BookmarkForm, ChatLine};
use voelin_ui_vm::events; use voelin_ui_vm::events;
use voelin_ui_vm::host::{Cx, Host, Persist, Update}; use voelin_ui_vm::host::{Cx, Host, Persist, Update};
use voelin_ui_vm::image::ImageRef; use voelin_ui_vm::image::ImageRef;
use voelin_ui_vm::servers::logic::{self, GatewayFound, ObservePlan}; use voelin_ui_vm::servers::logic;
use voelin_ui_vm::servers::sequence::{self, Backing};
use voelin_ui_vm::settings::{ use voelin_ui_vm::settings::{
CLIENT_PLAYBACK, ThemeChoice, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, UI_WINDOW, CLIENT_PLAYBACK, ThemeChoice, UI, UI_FONT_SCALE, UI_IMAGE_PREVIEW_KB, UI_THEME, UI_WINDOW,
WindowState, WindowState,
@@ -390,14 +391,31 @@ impl AppState {
&mut self, &mut self,
cx: &mut Context<Self>, cx: &mut Context<Self>,
f: impl FnOnce(&mut VmState, &mut Cx<'_>) -> R, f: impl FnOnce(&mut VmState, &mut Cx<'_>) -> R,
) -> R {
self.transition_with(cx, |state, transition, _| f(state, transition))
}
/// Like [`AppState::transition`], for a sequence that also reads and writes
/// the store and the secrets and picks the identity
/// (`voelin_ui_vm::servers::sequence`): the [`Backing`] is the backend's.
fn transition_with<R>(
&mut self,
cx: &mut Context<Self>,
f: impl FnOnce(&mut VmState, &mut Cx<'_>, &Backing<'_>) -> R,
) -> R { ) -> R {
let host = ShellHost { let host = ShellHost {
demo_ui: self.switches.demo_ui, demo_ui: self.switches.demo_ui,
store: &self.backend.store, store: &self.backend.store,
prefs: &self.backend.prefs, prefs: &self.backend.prefs,
}; };
let identity = |named| self.backend.identity_blob(named);
let backing = Backing {
store: &self.backend.store,
secrets: &*self.backend.secrets,
identity: &identity,
};
let mut transition = Cx::new(&host); let mut transition = Cx::new(&host);
let result = f(&mut self.vm, &mut transition); let result = f(&mut self.vm, &mut transition, &backing);
let update = transition.update; let update = transition.update;
self.perform(update, cx); self.perform(update, cx);
result result
@@ -437,11 +455,14 @@ impl AppState {
/// Do what an update asks that this front end has the parts for. /// Do what an update asks that this front end has the parts for.
fn perform(&mut self, update: Update, cx: &mut Context<Self>) { fn perform(&mut self, update: Update, cx: &mut Context<Self>) {
let Update { status, commands, persist, warnings, rest, password, .. } = update; let Update { status, commands, persist, warnings, rest, password, discover, .. } = update;
self.log_warnings(warnings); self.log_warnings(warnings);
for command in commands { for command in commands {
self.send(command); self.send(command);
} }
for (id, address) in discover {
self.look_up_gateway(id, address);
}
if let Some(text) = status { if let Some(text) = status {
self.set_status(text); self.set_status(text);
} }
@@ -616,19 +637,25 @@ impl AppState {
} }
// The callbacks of `bind/servers.rs` that the shell has: what the // The callbacks of `bind/servers.rs` that the shell has: what the
// actions of `crate::shell` do. // actions of `crate::shell` do. The ones that read or write the store, the
// secrets or the engine's commands are the sequences of
// `voelin_ui_vm::servers::sequence`, the Slint front end's too.
/// Show a server, and observe it. /// Show a server, and observe it.
pub fn select_server(&mut self, id: i64, cx: &mut Context<Self>) { pub fn select_server(&mut self, id: i64, cx: &mut Context<Self>) {
self.transition(cx, |state, cx| logic::select_server(state, cx, id)); self.transition_with(cx, |state, cx, backing| {
self.observe(id, cx); sequence::select_server(state, cx, backing, id)
});
cx.notify(); cx.notify();
} }
/// Connect the server on screen with voice, into its default channel. /// Connect the server on screen with voice, into its default channel.
pub fn connect_voice(&mut self, cx: &mut Context<Self>) { pub fn connect_voice(&mut self, cx: &mut Context<Self>) {
let channel = self.current_bookmark().and_then(|b| b.default_channel.clone()); // `stream_peer` stays the engine's default: what this front end can
self.connect_voice_to(channel, None, None, cx); // decode is for the slice with the stream viewer to say.
self.transition_with(cx, |state, cx, backing| {
sequence::connect_voice(state, cx, backing, None)
});
cx.notify(); cx.notify();
} }
@@ -642,27 +669,9 @@ impl AppState {
token: Option<String>, token: Option<String>,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> bool { ) -> bool {
let Some(b) = self.current_bookmark().cloned() else { return false }; self.transition_with(cx, |state, cx, backing| {
if self.switches.demo_ui { sequence::connect_voice_to(state, cx, backing, channel, channel_password, token, None)
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.backend.identity_for(Some(&b))));
options.server_password = self.backend.secrets.get(&b.server_password_key()).ok().flatten();
// `options.stream_peer` stays the engine's default: what this front
// end can decode is for the slice with the stream viewer to say.
self.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, cx);
true
} }
/// Leave voice on the server on screen. /// Leave voice on the server on screen.
@@ -709,69 +718,34 @@ impl AppState {
/// The server dialog's form for a server (id -1: a new one). /// The server dialog's form for a server (id -1: a new one).
pub fn bookmark_form(&self, id: i64) -> BookmarkForm { pub fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id) else { sequence::bookmark_form(&self.vm, &self.backend.store, &*self.backend.secrets, id)
return BookmarkForm { }
id: -1,
nickname: self.backend.default_nickname().into(), /// Why a form is not saved here, if it is not: the sample servers are not
..Default::default() /// kept, and a server needs an address.
}; fn save_refused(&self, form: &BookmarkForm) -> Option<&'static str> {
}; if self.switches.demo_ui {
let password = self.backend.secrets.get(&b.server_password_key()).ok().flatten(); Some("The sample servers are not kept")
let state = self.vm.sessions.get(&b.id).map(|view| &view.state); } else if form.address.trim().is_empty() {
voelin_ui_vm::servers::form(b, state, password.as_deref().unwrap_or_default()) Some("A server needs an address")
} else {
None
}
} }
/// Save the server the form describes, and show it: its id, none when it /// Save the server the form describes, and show it: its id, none when it
/// could not be saved (the status line says why). /// could not be saved (the status line says why).
pub fn save_bookmark(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> Option<i64> { pub fn save_bookmark(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> Option<i64> {
if self.switches.demo_ui { if let Some(why) = self.save_refused(form) {
self.set_status("The sample servers are not kept"); self.set_status(why);
cx.notify(); cx.notify();
return None; return None;
} }
let old = self.vm.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned(); let saved = self.transition_with(cx, |state, cx, backing| {
let mut bookmark = sequence::save_bookmark(state, cx, backing, form)
logic::bookmark_from_form(old.as_ref(), form, || self.backend.default_nickname()); });
if bookmark.address.is_empty() { cx.notify();
self.set_status("A server needs an address"); saved
cx.notify();
return None;
}
let result = if bookmark.id < 0 {
self.backend.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.backend.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
cx.notify();
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.backend.secrets.delete(&key)
} else {
self.backend.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.backend.secrets.delete(&old.query_password_key());
}
self.vm.gateways_looked_up.remove(&bookmark.id);
self.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.vm.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.vm.bookmarks = self.backend.store.bookmarks().unwrap_or_default();
let id = bookmark.id;
self.select_server(id, cx);
Some(id)
} }
/// The server dialog's Connect: save the server, then connect it with /// The server dialog's Connect: save the server, then connect it with
@@ -779,12 +753,16 @@ impl AppState {
/// Only once saved: connecting what is shown after a failed save would /// Only once saved: connecting what is shown after a failed save would
/// connect the server shown before. Whether it was saved. /// connect the server shown before. Whether it was saved.
pub fn save_and_connect(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> bool { pub fn save_and_connect(&mut self, form: &BookmarkForm, cx: &mut Context<Self>) -> bool {
let saved = self.save_bookmark(form, cx); if let Some(why) = self.save_refused(form) {
let bookmark = saved.and_then(|id| self.vm.bookmarks.iter().find(|b| b.id == id)); self.set_status(why);
let Some(to) = voelin_ui_vm::servers::connect_to(form, bookmark) else { return false }; cx.notify();
self.connect_voice_to(to.channel, to.channel_password, to.token, cx); return false;
}
let saved = self.transition_with(cx, |state, cx, backing| {
sequence::save_and_connect(state, cx, backing, form, None)
});
cx.notify(); cx.notify();
true saved
} }
/// Remove a server: its session is closed, its passwords and the bookmark /// Remove a server: its session is closed, its passwords and the bookmark
@@ -795,95 +773,29 @@ impl AppState {
cx.notify(); cx.notify();
return; return;
} }
self.send(Command::CloseSession { session: id as u64 }); self.transition_with(cx, |state, cx, backing| {
if let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() { sequence::delete_bookmark(state, cx, backing, id)
let _ = self.backend.secrets.delete(&b.server_password_key()); });
let _ = self.backend.secrets.delete(&b.query_password_key());
}
let _ = self.backend.store.delete_bookmark(id);
let bookmarks = self.backend.store.bookmarks().unwrap_or_default();
self.transition(cx, |state, cx| logic::forget_server(state, cx, id, bookmarks));
cx.notify(); cx.notify();
} }
/// Observe the server invisibly ([`logic::observe_plan`]): through its /// Look the gateway of a server up ([`sequence::find_gateways`]) on the
/// gateway, else its own query login. Without either the gateway is looked /// engine's runtime, as `Update::discover` asks; what is found comes back
/// up first, and observing starts when it is found. /// through [`Later`].
fn observe(&mut self, id: i64, cx: &mut Context<Self>) { fn look_up_gateway(&self, id: i64, address: String) {
let Some(b) = self.vm.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
let session = b.id as u64;
let gateway = |app: &Self, urls| Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&app.backend.identity_for(Some(&b)),
)),
};
match self.transition(cx, |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.send(gateway(self, urls));
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
self.send(gateway(self, urls));
// Still the one the server publishes?
self.discover_gateway(b.id, cx);
}
ObservePlan::Query(q) => {
let secret = self.backend.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.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
self.discover_gateway(b.id, cx);
return;
}
}
self.set_status("Observing invisibly…");
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a run
/// ([`logic::discover_wanted`]), on the engine's runtime; what is found
/// comes back through [`Later`].
fn discover_gateway(&mut self, id: i64, cx: &mut Context<Self>) {
let Some(address) = self.transition(cx, |state, cx| logic::discover_wanted(state, cx, id))
else {
return;
};
let Some(engine) = &self.engine else { return }; let Some(engine) = &self.engine else { return };
let later = self.later(); let later = self.later();
engine.runtime().spawn(async move { engine.runtime().spawn(async move {
let started = Instant::now(); if let Some(found) = sequence::find_gateways(&address).await {
let urls = voelin_core::discover::gateways(&address).await; later.run(move |app, cx| {
let elapsed_ms = started.elapsed().as_millis() as u64; app.gateway_found(id, &address, found.urls, found.elapsed_ms, cx)
if urls.is_empty() { });
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later.run(move |app, cx| app.gateway_found(id, &address, urls, elapsed_ms, cx));
} }
}); });
} }
/// Gateways were found for the server at `address` (best first); they are /// Gateways were found for the server at `address`
/// kept unless the server changed meanwhile ([`logic::gateway_found`]), and /// ([`sequence::gateway_found`]).
/// the server is observed through them if it is the one shown. Users never
/// hear of them (logged only).
fn gateway_found( fn gateway_found(
&mut self, &mut self,
id: i64, id: i64,
@@ -892,26 +804,9 @@ impl AppState {
elapsed_ms: u64, elapsed_ms: u64,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
let found = self.transition_with(cx, |state, cx, backing| {
self.transition(cx, |state, cx| logic::gateway_found(state, cx, id, address, urls)); sequence::gateway_found(state, cx, backing, id, address, urls, elapsed_ms)
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, cx);
}
}
GatewayFound::Changed { stop, observe, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
self.send(Command::StopObserving { session: id as u64 });
}
if observe {
self.observe(id, cx);
}
}
}
} }
/// Leave the servers properly, so no ghost client stays behind until it /// Leave the servers properly, so no ghost client stays behind until it
@@ -941,11 +836,11 @@ impl AppState {
mod tests { mod tests {
use std::cell::Cell; use std::cell::Cell;
use std::rc::Rc; use std::rc::Rc;
use std::time::Duration; use std::time::{Duration, Instant};
use gpui::TestAppContext; use gpui::TestAppContext;
use gpui_kit::{AppContext as _, Entity, Subscription, WindowAppearance}; use gpui_kit::{AppContext as _, Entity, Subscription, WindowAppearance};
use voelin_core::{Backends, Command, Event, SessionState, VoiceState}; use voelin_core::{Backends, Command, Event, ObserveState, SessionState, VoiceState};
use voelin_store::MemorySecrets; use voelin_store::MemorySecrets;
use voelin_ui_vm::dev::logic as sample; use voelin_ui_vm::dev::logic as sample;
+38 -94
View File
@@ -18,12 +18,10 @@ use anyhow::{Context as _, Result};
use tracing::warn; use tracing::warn;
use tsclientlib::Identity; use tsclientlib::Identity;
use voelin_core::settings::{AUDIO, Settings}; use voelin_core::settings::{AUDIO, Settings};
use voelin_core::{AudioSettings, Command, Engine, History}; use voelin_core::{AudioSettings, Command, Engine, History, IdentityBlob};
use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store}; use voelin_store::{Bookmark, IdentityOrigin, MemorySecrets, Secrets, Store};
use voelin_ui_vm::servers::logic::CREATED_IDENTITY; use voelin_ui_vm::servers::logic::CREATED_IDENTITY;
use voelin_ui_vm::settings::{ use voelin_ui_vm::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings};
CLIENT_PLAYBACK, ClientPlaybackMap, UI, UI_WINDOW, UiSettings, appearance_keys, page_keys,
};
/// The client's database, its settings and its secrets. /// The client's database, its settings and its secrets.
pub struct Backend { pub struct Backend {
@@ -59,42 +57,20 @@ pub fn data_dir() -> PathBuf {
voelin_platform::paths::data_dir() voelin_platform::paths::data_dir()
} }
/// The settings service on the client database in `dir`: the UI's keys /// The settings service on the client database in `dir`
/// registered, then a config file (`VOELIN_CONFIG`, else `<dir>/config.toml` /// ([`voelin_ui_vm::settings::open_settings`], which the Slint front end opens
/// if it exists) and `VOELIN_SETTING_*` variables below the stored values. /// the same way): the UI's keys and this front end's own, then a config file
/// Without the database the settings live in memory. /// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists) and
/// `VOELIN_SETTING_*` variables below the stored values. Without the database
/// the settings live in memory.
fn open_settings(dir: &Path) -> Settings { fn open_settings(dir: &Path) -> Settings {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| { voelin_ui_vm::settings::open_settings(dir, &[], register_own_keys)
warn!(%e, "settings are not stored this time");
Settings::in_memory()
});
register_keys(&prefs);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
} }
/// Make the keys this front end reads known to `prefs`. /// The key that only this front end uses: where the window was
fn register_keys(prefs: &Settings) { /// (`ui.window`).
prefs.register(&UI); fn register_own_keys(prefs: &Settings) {
prefs.register(&CLIENT_PLAYBACK);
prefs.register(&UI_WINDOW); prefs.register(&UI_WINDOW);
for key in appearance_keys() {
prefs.register(key);
}
for key in page_keys() {
prefs.register(key);
}
} }
impl Backend { impl Backend {
@@ -120,7 +96,8 @@ impl Backend {
/// fresh identity: the tests', and the sample data's. /// fresh identity: the tests', and the sample data's.
pub fn in_memory() -> Result<Self> { pub fn in_memory() -> Result<Self> {
let prefs = Settings::in_memory(); let prefs = Settings::in_memory();
register_keys(&prefs); voelin_ui_vm::settings::register_keys(&prefs);
register_own_keys(&prefs);
Ok(Self { Ok(Self {
store: Store::open_in_memory()?, store: Store::open_in_memory()?,
prefs, prefs,
@@ -159,32 +136,15 @@ impl Backend {
/// The identity a connection to the bookmark `bookmark` uses: its own if /// The identity a connection to the bookmark `bookmark` uses: its own if
/// it names one the store has, else the store's default, else the one made /// it names one the store has, else the store's default, else the one made
/// at start. /// at start ([`Store::identity_for`]).
pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity { pub fn identity_for(&self, bookmark: Option<&Bookmark>) -> Identity {
let entries = self.store.identities().unwrap_or_default(); self.store.identity_for(bookmark.and_then(|b| b.identity), &self.identity)
let id = bookmark
.and_then(|b| b.identity)
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| self.store.default_identity().ok().flatten().map(|e| e.id));
id.and_then(|id| self.store.identity(id).ok()).unwrap_or_else(|| self.identity.clone())
} }
/// The nickname a new server gets: the default identity's (one imported /// The identity of [`Backend::identity_for`] as the engine takes it, for a
/// from TeamSpeak keeps the nickname used there), else the system user's. /// bookmark that names the identity `named`.
pub fn default_nickname(&self) -> String { pub fn identity_blob(&self, named: Option<i64>) -> IdentityBlob {
self.store voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![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.
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
} }
/// Write what the settings service holds to the database. /// Write what the settings service holds to the database.
@@ -202,40 +162,7 @@ pub fn default_secrets(demo: bool) -> Box<dyn Secrets> {
if demo { if demo {
Box::new(MemorySecrets::default()) Box::new(MemorySecrets::default())
} else { } else {
Box::new(FallbackSecrets { Box::new(voelin_store::FallbackSecrets::new("voelin"))
keyring: voelin_store::KeyringSecrets::new("voelin"),
memory: MemorySecrets::default(),
})
}
}
/// The keyring first, memory when it cannot keep a secret (the Slint front
/// end's `FallbackSecrets`, repeated: both go into `voelin-store` when the
/// Slint front end is retired).
struct FallbackSecrets {
keyring: voelin_store::KeyringSecrets,
memory: MemorySecrets,
}
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> {
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
} }
} }
@@ -301,6 +228,23 @@ mod tests {
assert!(dir.0.join("client.db").is_file(), "the database is in the directory given"); assert!(dir.0.join("client.db").is_file(), "the database is in the directory given");
} }
/// A new server's nickname is the default identity's (one imported from
/// TeamSpeak keeps the nickname used there), not the name the app gave the
/// identity it made.
#[test]
fn a_new_servers_nickname_is_the_default_identitys_unless_the_app_named_it() {
use voelin_ui_vm::servers::sequence::default_nickname;
let backend = Backend::in_memory().unwrap();
let made = Identity::create();
backend.store.add_identity(CREATED_IDENTITY, &made, IdentityOrigin::Created).unwrap();
let nickname = default_nickname(&backend.store);
assert!(nickname != CREATED_IDENTITY && !nickname.trim().is_empty(), "{nickname}");
let imported =
backend.store.add_identity("Nova", &Identity::create(), IdentityOrigin::Imported);
backend.store.set_default_identity(imported.unwrap(), false).unwrap();
assert_eq!(default_nickname(&backend.store), "Nova");
}
#[test] #[test]
fn a_server_names_its_identity_and_the_default_serves_the_rest() { fn a_server_names_its_identity_and_the_default_serves_the_rest() {
let backend = Backend::in_memory().unwrap(); let backend = Backend::in_memory().unwrap();
+1 -1
View File
@@ -27,7 +27,7 @@ pub use chat::{
pub use contacts::{Contact, ContactSeen, Relation}; pub use contacts::{Contact, ContactSeen, Relation};
pub use keystore::SqliteKeyStore; pub use keystore::SqliteKeyStore;
#[cfg(feature = "keyring")] #[cfg(feature = "keyring")]
pub use secrets::KeyringSecrets; pub use secrets::{FallbackSecrets, KeyringSecrets};
pub use secrets::{MemorySecrets, Secrets}; pub use secrets::{MemorySecrets, Secrets};
pub use store::{ pub use store::{
Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store, Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store,
+41
View File
@@ -74,6 +74,47 @@ impl Secrets for KeyringSecrets {
} }
} }
/// The keyring first, memory when the keyring cannot keep a secret (no Secret
/// Service on a headless Linux): what the desktop front ends keep the servers'
/// passwords in. A secret the keyring refused is kept for this run only.
#[cfg(feature = "keyring")]
pub struct FallbackSecrets {
keyring: KeyringSecrets,
memory: MemorySecrets,
}
#[cfg(feature = "keyring")]
impl FallbackSecrets {
/// Secrets in the keyring entries of `service` (the app's name), with
/// memory behind them.
pub fn new(service: impl Into<String>) -> Self {
Self { keyring: KeyringSecrets::new(service), memory: MemorySecrets::default() }
}
}
#[cfg(feature = "keyring")]
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> Result<()> {
if let Err(error) = self.keyring.set(key, value) {
tracing::warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+40
View File
@@ -407,6 +407,24 @@ impl Store {
Ok(()) Ok(())
} }
/// The identity entry a connection uses: `named` (the identity a
/// bookmark names) if the store still has it, else the default identity's.
/// None when the store has no identity.
pub fn identity_id_for(&self, named: Option<i64>) -> Option<i64> {
let entries = self.identities().unwrap_or_default();
named
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| entries.iter().find(|e| e.is_default).or(entries.first()).map(|e| e.id))
}
/// The identity a connection uses ([`Store::identity_id_for`]); `fallback`
/// when the store has none it can read.
pub fn identity_for(&self, named: Option<i64>, fallback: &Identity) -> Identity {
self.identity_id_for(named)
.and_then(|id| self.identity(id).ok())
.unwrap_or_else(|| fallback.clone())
}
pub fn identity(&self, id: i64) -> Result<Identity> { pub fn identity(&self, id: i64) -> Result<Identity> {
let data: Option<String> = self let data: Option<String> = self
.db .db
@@ -718,6 +736,28 @@ mod tests {
assert_eq!(store.default_identity().unwrap().unwrap().id, made); assert_eq!(store.default_identity().unwrap().unwrap().id, made);
} }
/// A bookmark's own identity if the store has it, else the default one,
/// else the fallback.
#[test]
fn a_connection_uses_the_named_identity_else_the_default_else_the_fallback() {
let store = Store::open_in_memory().unwrap();
let uid = |identity: &Identity| identity.key().to_pub().get_uid();
let fallback = Identity::create();
assert_eq!(store.identity_id_for(Some(1)), None);
assert_eq!(uid(&store.identity_for(None, &fallback)), uid(&fallback), "no identity at all");
let (default, alt) = (Identity::create(), Identity::create());
let default_id = store.add_identity("Default", &default, IdentityOrigin::Created).unwrap();
let alt_id = store.add_identity("Alt", &alt, IdentityOrigin::Created).unwrap();
assert_eq!(uid(&store.identity_for(None, &fallback)), uid(&default), "the default");
assert_eq!(store.identity_id_for(Some(alt_id)), Some(alt_id));
assert_eq!(uid(&store.identity_for(Some(alt_id), &fallback)), uid(&alt), "the named one");
let gone = alt_id + 100;
assert_eq!(store.identity_id_for(Some(gone)), Some(default_id), "one that is gone");
assert_eq!(uid(&store.identity_for(Some(gone), &fallback)), uid(&default));
store.set_default_identity(alt_id, false).unwrap();
assert_eq!(store.identity_id_for(None), Some(alt_id), "the default moved");
}
/// A database of version 3 learns where its identities came from: the /// A database of version 3 learns where its identities came from: the
/// first one, named `Default`, is the one the app made; the others were /// first one, named `Default`, is the one the app made; the others were
/// imported; the first stays the default. /// imported; the first stays the default.
+3
View File
@@ -31,6 +31,9 @@ miniz_oxide = "0.8"
unicode-segmentation = "1.13" unicode-segmentation = "1.13"
# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests. # The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests.
png = "0.18" png = "0.18"
# What the shared server sequences (`servers::sequence`) log, as both front
# ends log it.
tracing = "0.1.44"
voelin-audio = { path = "../voelin-audio", default-features = false } voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] } voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" } voelin-gateway-proto = { path = "../voelin-gateway-proto" }
+6
View File
@@ -179,6 +179,12 @@ pub struct Update {
/// Pictures the engine wrote again: a front end drops what it decoded /// Pictures the engine wrote again: a front end drops what it decoded
/// of them. /// of them.
pub reloaded: Vec<PathBuf>, pub reloaded: Vec<PathBuf>,
/// Servers whose gateway is to be looked up in DNS (bookmark id and
/// address; [`crate::servers::logic::discover_wanted`] said so): the front
/// end runs [`crate::servers::sequence::find_gateways`] on the engine's
/// runtime and, when it finds some, calls
/// [`crate::servers::sequence::gateway_found`] on its own thread.
pub discover: Vec<(i64, String)>,
/// The microphone meter: level in dBFS, and whether voice is sent. /// The microphone meter: level in dBFS, and whether voice is sent.
pub input_level: Option<(f32, bool)>, pub input_level: Option<(f32, bool)>,
/// Open the password dialog. /// Open the password dialog.
+1
View File
@@ -3,6 +3,7 @@
//! and the channel tree as plain data. //! and the channel tree as plain data.
pub mod logic; pub mod logic;
pub mod sequence;
use std::sync::Arc; use std::sync::Arc;
+683
View File
@@ -0,0 +1,683 @@
//! What both front ends do for a server that is more than a state change: the
//! sequences over the store, the secrets and the engine.
//!
//! [`logic`](super::logic) has the transitions that touch the state alone;
//! these also read and write the client's store and its secrets (a
//! bookmark and its passwords), pick the identity a connection is made with
//! and build the engine's commands, and they were written twice, once for
//! each front end, before they were one. Each is a transition: it takes the
//! state, the transition's [`Cx`] and the [`Backing`], changes the state and
//! the store, and says what the front end is to do through the `Cx`
//! (commands for the engine, the status line, what to keep, which gateways to
//! look up), so that a front end carries it out with its own `perform` and
//! tests it as it tests the others: in the GPUI front end the commands of a
//! test are the ones its `perform` was handed, and a sample server's are
//! dropped there.
//!
//! What stays with each front end is what needs its toolkit or its runtime:
//! the thread hop of a gateway lookup (it runs [`find_gateways`] on the
//! engine's runtime and calls [`gateway_found`] when something is found, as
//! `Update::discover` asks), the clipboard, the toast, and what it adds to a
//! connect (the stream codecs the Slint front end can decode).
use std::time::Instant;
use tracing::{debug, info, warn};
use voelin_core::stream::PeerConfig;
use voelin_core::{Command, IdentityBlob, ObserveState};
use voelin_store::{Bookmark, QueryTransport, Secrets, Store};
use super::logic::{self, CREATED_IDENTITY, GatewayFound, ObservePlan};
use crate::bridge::BookmarkForm;
use crate::host::Cx;
use crate::state::{AppState, Lines};
/// What the sequences read and write besides the state: the client's store, its
/// secrets and the identity a connection is made with.
pub struct Backing<'a> {
/// The bookmarks, the identities and the chats' read marks.
pub store: &'a Store,
/// The servers' passwords.
pub secrets: &'a dyn Secrets,
/// The identity a connection to a server whose bookmark names `named` is
/// made with, as the engine takes it ([`Store::identity_for`]: the named
/// one if the store has it, else the default one, else the front end's).
pub identity: &'a dyn Fn(Option<i64>) -> IdentityBlob,
}
/// 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 fn default_nickname(store: &Store) -> String {
store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![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())
}
/// The server dialog's form for server `id` (-1: a new one), with its
/// password from the secrets and its session's state.
pub fn bookmark_form<L>(
state: &AppState<L>,
store: &Store,
secrets: &dyn Secrets,
id: i64,
) -> BookmarkForm {
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else {
return BookmarkForm {
id: -1,
nickname: default_nickname(store).into(),
..Default::default()
};
};
let password = secrets.get(&b.server_password_key()).ok().flatten();
let session = state.sessions.get(&b.id).map(|view| &view.state);
super::form(b, session, password.as_deref().unwrap_or_default())
}
/// Show a server, and observe it.
pub fn select_server<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
id: i64,
) {
logic::select_server(state, cx, id);
observe(state, cx, backing, id);
}
/// Connect the server on screen with voice, into its default channel.
pub fn connect_voice<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
stream_peer: Option<PeerConfig>,
) -> bool {
let channel = state
.current
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
.and_then(|b| b.default_channel.clone());
connect_voice_to(state, cx, backing, channel, None, None, stream_peer)
}
/// Connect the server on screen with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for. `stream_peer`: what the front end can decode
/// of a stream, if it says (the engine's default otherwise).
pub fn connect_voice_to<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
stream_peer: Option<PeerConfig>,
) -> bool {
let Some(b) = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id)).cloned()
else {
return false;
};
if cx.host.demo_ui() {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
cx.status(error);
return false;
}
};
options.identity = Some((backing.identity)(b.identity));
options.server_password = backing.secrets.get(&b.server_password_key()).ok().flatten();
if let Some(peer) = stream_peer {
options.stream_peer = peer;
}
cx.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
cx.status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
discover_gateway(state, cx, b.id);
true
}
/// Ask for the gateway of a server to be looked up ([`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. The front end looks it up (`Update::discover`).
pub fn discover_gateway<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
if let Some(address) = logic::discover_wanted(state, cx, id) {
cx.update.discover.push((id, address));
}
}
/// What looking up the gateways of a server found.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Found {
/// Every URL the server publishes, best first.
pub urls: Vec<String>,
/// How long the lookup took.
pub elapsed_ms: u64,
}
/// Look the gateways of the server at `address` up in DNS; none when the
/// server publishes none (logged). Runs on the engine's runtime; what it
/// finds goes to [`gateway_found`] on the front end's own thread.
pub async fn find_gateways(address: &str) -> Option<Found> {
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");
None
} else {
Some(Found { 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).
pub fn gateway_found<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
id: i64,
address: &str,
urls: Vec<String>,
elapsed_ms: u64,
) {
match logic::gateway_found(state, cx, id, address, urls) {
GatewayFound::Same => debug!(server = %address, elapsed_ms, "gateway found, as kept"),
GatewayFound::Kept { observe: now } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if now {
observe(state, cx, backing, id);
}
}
GatewayFound::Changed { stop, observe: now, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
cx.send(Command::StopObserving { session: id as u64 });
}
if now {
observe(state, cx, backing, 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 fn observe<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, backing: &Backing<'_>, id: i64) {
let Some(b) = state.bookmarks.iter().find(|b| b.id == id).cloned() else { return };
let session = b.id as u64;
let gateway = |urls| Command::ObserveGateway {
session,
urls,
identity: Box::new((backing.identity)(b.identity)),
};
match logic::observe_plan(state, cx, id) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
cx.send(gateway(urls));
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
cx.send(gateway(urls));
// Still the one the server publishes?
discover_gateway(state, cx, b.id);
}
ObservePlan::Query(q) => {
let secret = backing.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,
};
cx.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
discover_gateway(state, cx, b.id);
return;
}
}
cx.status("Observing invisibly…");
}
/// Save the server the form describes in the store and the secrets, and show
/// it: its id, none when it could not be saved (the status line says why). A
/// new address stops what was observed at the old one.
pub fn save_bookmark<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
form: &BookmarkForm,
) -> Option<i64> {
let old = state.bookmarks.iter().find(|b| b.id == i64::from(form.id)).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || default_nickname(backing.store));
let result = if bookmark.id < 0 {
backing.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
backing.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
cx.status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
backing.secrets.delete(&key)
} else {
backing.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 _ = backing.secrets.delete(&old.query_password_key());
}
state.gateways_looked_up.remove(&bookmark.id);
cx.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
state.bookmarks = backing.store.bookmarks().unwrap_or_default();
select_server(state, cx, backing, 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
/// ([`super::connect_to`]). Only once saved: connecting what is shown after a
/// failed save would connect the server shown before. Whether it was saved.
pub fn save_and_connect<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
form: &BookmarkForm,
stream_peer: Option<PeerConfig>,
) -> bool {
let saved = save_bookmark(state, cx, backing, form);
let to = super::connect_to(
form,
saved.and_then(|id| state.bookmarks.iter().find(|b: &&Bookmark| b.id == id)),
);
let Some(to) = to else { return false };
connect_voice_to(state, cx, backing, to.channel, to.channel_password, to.token, stream_peer);
true
}
/// Remove a server: its session is closed, its passwords and the bookmark go,
/// and the first server is shown.
pub fn delete_bookmark<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
backing: &Backing<'_>,
id: i64,
) {
cx.send(Command::CloseSession { session: id as u64 });
if let Some(b) = state.bookmarks.iter().find(|b| b.id == id) {
let _ = backing.secrets.delete(&b.server_password_key());
let _ = backing.secrets.delete(&b.query_password_key());
}
let _ = backing.store.delete_bookmark(id);
let bookmarks = backing.store.bookmarks().unwrap_or_default();
logic::forget_server(state, cx, id, bookmarks);
}
#[cfg(test)]
mod tests {
use voelin_store::{MemorySecrets, QueryConfig};
use super::*;
use crate::host::Update;
use crate::host::testing::{Fake, State};
/// A store, secrets and a front end of the tests' own.
struct Rig {
store: Store,
secrets: MemorySecrets,
host: Fake,
}
impl Rig {
fn new() -> Self {
Self {
store: Store::open_in_memory().unwrap(),
secrets: MemorySecrets::default(),
host: Fake::default(),
}
}
/// A state with these servers saved, the first on screen.
fn state(&self, servers: &[(&str, &str)]) -> State {
for (name, address) in servers {
let bookmark = Bookmark {
name: (*name).into(),
address: (*address).into(),
nickname: "Nova".into(),
..Default::default()
};
self.store.add_bookmark(&bookmark).unwrap();
}
let bookmarks = self.store.bookmarks().unwrap();
let mut state = State::new(
bookmarks.clone(),
Default::default(),
Default::default(),
Default::default(),
);
state.current = bookmarks.first().map(|b| b.id);
state
}
/// Run a sequence, and what it asks of the front end.
fn run<R>(
&self,
state: &mut State,
f: impl FnOnce(&mut State, &mut Cx<'_>, &Backing<'_>) -> R,
) -> (R, Update) {
let identity = |named: Option<i64>| {
IdentityBlob::teamspeak(format!("identity-{}", named.unwrap_or(-1)), 8, "{}")
};
let backing =
Backing { store: &self.store, secrets: &self.secrets, identity: &identity };
let mut cx = Cx::new(&self.host);
let result = f(state, &mut cx, &backing);
(result, cx.update)
}
}
fn form(address: &str) -> BookmarkForm {
BookmarkForm { id: -1, address: address.into(), ..Default::default() }
}
#[test]
fn a_server_with_no_identity_to_name_it_gets_the_users_name_or_a_fallback() {
let nickname = default_nickname(&Store::open_in_memory().unwrap());
assert!(!nickname.trim().is_empty(), "servers refuse an empty nickname");
assert!(nickname != CREATED_IDENTITY && nickname != "imported");
}
/// A connect names the server on screen, its nickname and channel, the
/// identity it is made with and the password the secrets keep; it says so
/// in the status line and asks for the gateway to be looked up, once.
#[test]
fn a_connect_asks_the_engine_with_what_the_store_and_the_secrets_know() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
rig.secrets.set(&state.bookmarks[0].server_password_key(), "hunter2").unwrap();
let (asked, update) = rig.run(&mut state, |state, cx, backing| {
connect_voice_to(state, cx, backing, Some("Lobby".into()), None, None, None)
});
assert!(asked);
let [Command::ConnectVoice { session, options }] = &update.commands[..] else {
panic!("{:?}", update.commands.len())
};
assert_eq!(*session, id as u64);
assert_eq!((options.address.as_str(), options.nickname.as_str()), ("ts.example", "Nova"));
assert_eq!(options.channel.as_deref(), Some("Lobby"));
assert_eq!(options.server_password.as_deref(), Some("hunter2"));
assert_eq!(options.identity.as_ref().map(|i| i.uid.as_str()), Some("identity--1"));
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
// The second connect of a run does not look it up again.
let (_, update) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert_eq!(update.commands.len(), 1);
assert!(update.discover.is_empty());
}
/// The sample servers connect nothing, and a client version that is none
/// is refused in words.
#[test]
fn a_connect_that_cannot_be_made_asks_nothing() {
let mut rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
rig.host.demo = true;
let (asked, update) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert!(!asked && update.commands.is_empty() && update.status.is_none());
rig.host.demo = false;
state.bookmarks[0].client_version = Some("nonsense@0".into());
let (asked, update) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert!(!asked && update.commands.is_empty());
assert!(update.status.is_some_and(|s| s.starts_with("Invalid client compatibility")));
state.current = None;
let (asked, _) =
rig.run(&mut state, |state, cx, backing| connect_voice(state, cx, backing, None));
assert!(!asked, "no server on screen");
}
/// A new server is in the store with its password in the secrets, is the
/// one on screen, and has its gateway looked up (it has none to observe
/// through yet).
#[test]
fn saving_a_new_server_keeps_it_and_its_password_and_shows_it() {
let rig = Rig::new();
let mut state = rig.state(&[]);
let form = BookmarkForm { server_password: "hunter2".into(), ..form(" ts.example ") };
let (saved, update) =
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &form));
let id = saved.expect("saved");
let stored = rig.store.bookmarks().unwrap();
assert_eq!((stored.len(), stored[0].id), (1, id));
assert_eq!(
(stored[0].address.as_str(), stored[0].name.as_str()),
("ts.example", "ts.example")
);
assert!(!stored[0].nickname.is_empty(), "the default nickname");
assert_eq!(
rig.secrets.get(&stored[0].server_password_key()).unwrap().as_deref(),
Some("hunter2")
);
assert_eq!(state.current, Some(id));
assert_eq!(state.bookmarks, stored);
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
assert!(update.commands.is_empty());
// An empty password in the form removes it.
let edit = BookmarkForm { id: id as i32, ..form_of(&stored[0], "") };
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &edit));
assert_eq!(rig.secrets.get(&stored[0].server_password_key()).unwrap(), None);
}
fn form_of(bookmark: &Bookmark, password: &str) -> BookmarkForm {
crate::servers::form(bookmark, None, password)
}
/// Another address is another server: what was observed at the old one
/// stops, its query password goes, and the gateway is looked up anew.
#[test]
fn a_new_address_stops_what_was_observed_at_the_old_one() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let old = state.bookmarks[0].clone();
let id = old.id;
state.gateways_looked_up.insert(id);
rig.secrets.set(&old.query_password_key(), "query-secret").unwrap();
state.bookmarks[0].query = Some(QueryConfig::default());
rig.store.update_bookmark(&state.bookmarks[0]).unwrap();
state.sessions.entry(id).or_default().state.observe = ObserveState::Observing;
let moved = BookmarkForm { address: "ts.elsewhere".into(), ..form_of(&old, "") };
let (saved, update) =
rig.run(&mut state, |state, cx, backing| save_bookmark(state, cx, backing, &moved));
assert_eq!(saved, Some(id));
assert!(
matches!(&update.commands[..], [Command::StopObserving { session }] if *session == id as u64)
);
assert_eq!(rig.secrets.get(&old.query_password_key()).unwrap(), None);
assert_eq!(state.sessions[&id].state.observe, ObserveState::Off);
assert_eq!(update.discover, [(id, "ts.elsewhere".to_owned())]);
assert_eq!(state.bookmarks[0].address, "ts.elsewhere");
}
/// The form's Connect connects only what was saved.
#[test]
fn save_and_connect_connects_the_server_it_saved() {
let rig = Rig::new();
let mut state = rig.state(&[]);
let linked =
BookmarkForm { channel: "Games".into(), token: "key".into(), ..form("ts.example") };
let (done, update) = rig.run(&mut state, |state, cx, backing| {
save_and_connect(state, cx, backing, &linked, None)
});
assert!(done);
let [Command::ConnectVoice { options, .. }] = &update.commands[..] else {
panic!("{}", update.commands.len())
};
assert_eq!(
(options.channel.as_deref(), options.token.as_deref()),
(Some("Games"), Some("key"))
);
assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…"));
}
/// A server is removed with its session, its passwords and its row, and
/// the first of the others is shown.
#[test]
fn deleting_a_server_closes_its_session_and_forgets_its_secrets() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example"), ("Lounge", "lounge.example")]);
let [first, second] = [state.bookmarks[0].clone(), state.bookmarks[1].clone()];
rig.secrets.set(&first.server_password_key(), "hunter2").unwrap();
let (_, update) =
rig.run(&mut state, |state, cx, backing| delete_bookmark(state, cx, backing, first.id));
assert!(
matches!(&update.commands[..], [Command::CloseSession { session }] if *session == first.id as u64)
);
assert_eq!(rig.secrets.get(&first.server_password_key()).unwrap(), None);
assert_eq!(
rig.store.bookmarks().unwrap().iter().map(|b| b.id).collect::<Vec<_>>(),
[second.id]
);
assert_eq!((state.current, state.bookmarks.len()), (Some(second.id), 1));
}
/// Showing a server observes it: through its gateways if it has some (and
/// looks the gateway up again, in case it moved), else through its query
/// login with the password the secrets keep, else it looks the gateway up
/// and observes when it is found.
#[test]
fn showing_a_server_observes_it_the_way_it_can_be() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
let (_, update) =
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
assert!(
update.commands.is_empty() && update.status.is_none(),
"nothing to observe through yet"
);
assert_eq!(update.discover, [(id, "ts.example".to_owned())]);
state.bookmarks[0].query = Some(QueryConfig {
host: "query.example".into(),
port: 10022,
user: "serveradmin".into(),
..Default::default()
});
rig.secrets.set(&state.bookmarks[0].query_password_key(), "q").unwrap();
let (_, update) =
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
let [Command::ObserveQuery { session, connect }] = &update.commands[..] else {
panic!("{}", update.commands.len())
};
assert_eq!(*session, id as u64);
assert_eq!(connect.address, "query.example:10022");
assert_eq!((connect.user.as_str(), connect.secret.as_deref()), ("serveradmin", Some("q")));
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
state.bookmarks[0].set_gateways(vec!["ws://gw.example/".into()]);
let (_, update) =
rig.run(&mut state, |state, cx, backing| select_server(state, cx, backing, id));
let [Command::ObserveGateway { urls, identity, .. }] = &update.commands[..] else {
panic!("{}", update.commands.len())
};
assert_eq!(urls, &["ws://gw.example/".to_owned()]);
assert_eq!(identity.uid, format!("identity-{}", -1));
assert!(update.discover.is_empty(), "looked up once");
}
/// What a lookup found is kept for the next start, and the server on
/// screen is observed through it.
#[test]
fn a_found_gateway_is_kept_and_the_server_on_screen_is_observed_through_it() {
let rig = Rig::new();
let mut state = rig.state(&[("Nightfall", "ts.example")]);
let id = state.current.unwrap();
state.gateways_looked_up.insert(id);
let urls = vec!["ws://gw.example/".to_owned()];
let (_, update) = rig.run(&mut state, |state, cx, backing| {
gateway_found(state, cx, backing, id, "ts.example", urls.clone(), 12)
});
assert_eq!(state.bookmarks[0].gateways(), urls);
assert!(
update
.persist
.iter()
.any(|p| matches!(p, crate::host::Persist::Bookmark { id: i, .. } if *i == id))
);
assert!(matches!(&update.commands[..], [Command::ObserveGateway { .. }]));
assert_eq!(update.status.as_deref(), Some("Observing invisibly…"));
// For a server that changed meanwhile, nothing.
let (_, update) = rig.run(&mut state, |state, cx, backing| {
gateway_found(state, cx, backing, id, "another.example", urls.clone(), 12)
});
assert!(update.commands.is_empty() && update.persist.is_empty());
}
/// The dialog's form: a new server gets the default nickname, a saved one
/// its own with the password from the secrets.
#[test]
fn the_form_of_a_server_has_its_password_and_a_new_one_a_nickname() {
let rig = Rig::new();
let state = rig.state(&[("Nightfall", "ts.example")]);
let saved = &state.bookmarks[0];
rig.secrets.set(&saved.server_password_key(), "hunter2").unwrap();
let form = bookmark_form(&state, &rig.store, &rig.secrets, saved.id);
assert_eq!(
(form.address.as_ref(), form.server_password.as_ref()),
("ts.example", "hunter2")
);
assert_eq!(form.nickname.as_ref(), "Nova");
let new = bookmark_form(&state, &rig.store, &rig.secrets, -1);
assert_eq!((new.id, new.nickname.as_ref()), (-1, default_nickname(&rig.store).as_str()));
}
}
+89 -1
View File
@@ -3,10 +3,12 @@
//! the settings page. //! the settings page.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::warn;
use voelin_audio::process::NoiseLevel; use voelin_audio::process::NoiseLevel;
use voelin_core::settings::{Key, Kind}; use voelin_core::settings::{Key, Kind, Settings};
use voelin_core::{AudioSettings, TransmitMode}; use voelin_core::{AudioSettings, TransmitMode};
use crate::bridge::AudioForm; use crate::bridge::AudioForm;
@@ -320,6 +322,53 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
] ]
} }
/// The settings service on the client database in `dir` (`client.db`), the way
/// both front ends open it: the keys they read registered ([`UI`],
/// [`CLIENT_PLAYBACK`], [`appearance_keys`] and [`page_keys`]; `register` adds
/// the keys of one front end only, before anything is read), then a config file
/// (`VOELIN_CONFIG`, else `<dir>/config.toml` if it exists), the
/// `VOELIN_SETTING_*` variables and `overrides` (`--set key=value`) below the
/// stored values. Without the database the settings live in memory. What
/// cannot be applied is logged, not fatal.
pub fn open_settings(
dir: &Path,
overrides: &[String],
register: impl FnOnce(&Settings),
) -> Settings {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| {
warn!(%e, "settings are not stored this time");
Settings::in_memory()
});
register_keys(&prefs);
register(&prefs);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str)));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
}
/// Make the keys both front ends read known to `prefs`.
pub fn register_keys(prefs: &Settings) {
prefs.register(&UI);
prefs.register(&CLIENT_PLAYBACK);
for key in appearance_keys() {
prefs.register(key);
}
for key in page_keys() {
prefs.register(key);
}
}
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog /// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
/// offers, in the order of its lists (`dialogs.slint`); any other value can /// offers, in the order of its lists (`dialogs.slint`); any other value can
/// be typed in. /// be typed in.
@@ -662,6 +711,45 @@ mod tests {
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop); assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
} }
/// The settings both front ends open: the shared keys, the config file's
/// values, then `--set` over it, a front end's own key only when it
/// registers it, and a database in the directory given.
#[test]
fn the_settings_open_with_the_shared_keys_a_config_file_and_overrides() {
let dir =
std::env::temp_dir().join(format!("voelin-ui-vm-settings-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("config.toml"),
"\"ui.theme\" = \"light\"\n\"ui.members_width\" = 300\n",
)
.unwrap();
let overrides = ["ui.font_scale=1.5".to_owned(), "ui.members_width=320".to_owned()];
let prefs = open_settings(&dir, &overrides, |prefs| prefs.register(&UI_WINDOW));
assert_eq!(prefs.get(&UI_THEME), ThemeChoice::Light, "from the config file");
assert_eq!(prefs.get(&UI_FONT_SCALE), 1.5, "from --set");
assert_eq!(prefs.get(&UI_MEMBERS_WIDTH), 320, "--set over the file");
assert_eq!(prefs.get(&UI_WINDOW), None);
let names = |prefs: &Settings| prefs.keys().iter().map(|k| k.name()).collect::<Vec<_>>();
for shared in
["ui", "client_playback", "ui.theme", "notify.mentions", "ui.image_preview_kb"]
{
assert!(names(&prefs).contains(&shared), "{shared}");
}
assert!(names(&prefs).contains(&"ui.window"), "the front end's own key");
prefs.set(&UI_FONT_SCALE, 1.25).unwrap();
prefs.flush().unwrap();
drop(prefs);
assert!(dir.join("client.db").is_file(), "the database is in the directory given");
let plain = open_settings(&dir, &[], |_| {});
assert!(!names(&plain).contains(&"ui.window"), "not registered by this front end");
assert_eq!(plain.get(&UI_FONT_SCALE), 1.25, "what was stored wins over nothing");
drop(plain);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test] #[test]
fn voice_compact_key() { fn voice_compact_key() {
let settings = voelin_core::settings::Settings::in_memory(); let settings = voelin_core::settings::Settings::in_memory();
+12 -67
View File
@@ -37,83 +37,28 @@ use crate::vm;
slint::include_modules!(); slint::include_modules!();
/// The settings service on the client database: the UI's keys registered, /// The settings service on the client database
/// then a config file (`VOELIN_CONFIG`, else `<data dir>/config.toml` if it /// ([`vm::settings::open_settings`], which the GPUI front end opens the same
/// exists), `VOELIN_SETTING_*` variables and `overrides` below the stored /// way): the UI's keys registered, with the Stream Studio's, then a config
/// values. Without the database the settings live in memory. /// file (`VOELIN_CONFIG`, else `<data dir>/config.toml` if it exists),
/// `VOELIN_SETTING_*` variables and `overrides` below the stored values.
/// Without the database the settings live in memory.
fn open_settings(dir: &Path, overrides: &[String]) -> Settings { fn open_settings(dir: &Path, overrides: &[String]) -> Settings {
let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| { vm::settings::open_settings(dir, overrides, |prefs| {
warn!(%e, "settings are not stored this time"); prefs.register(&crate::vm::studio::logic::STUDIO_UI);
Settings::in_memory() })
});
prefs.register(&UI);
prefs.register(&CLIENT_PLAYBACK);
for key in appearance_keys() {
prefs.register(key);
}
for key in crate::settings::page_keys() {
prefs.register(key);
}
prefs.register(&crate::vm::studio::logic::STUDIO_UI);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
let mut errors = match config.map(|path| prefs.load_config_file(&path)) {
Some(Ok(errors)) => errors,
Some(Err(e)) => vec![e],
None => Vec::new(),
};
errors.extend(prefs.apply_env(std::env::vars()));
errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str)));
for e in errors {
warn!(%e, "setting ignored");
}
prefs
}
/// Secrets in the OS keyring, or in memory when there is none (headless
/// Linux without a Secret Service).
#[cfg(not(target_os = "android"))]
struct FallbackSecrets {
keyring: voelin_store::KeyringSecrets,
memory: MemorySecrets,
} }
/// The secrets store when [`RunOptions::secrets`] is not given: the OS /// The secrets store when [`RunOptions::secrets`] is not given: the OS
/// keyring on desktop, memory elsewhere. /// keyring on desktop (memory behind it where the keyring refuses: a headless
/// Linux without a Secret Service), memory elsewhere.
fn default_secrets() -> Box<dyn Secrets> { fn default_secrets() -> Box<dyn Secrets> {
#[cfg(not(target_os = "android"))] #[cfg(not(target_os = "android"))]
return Box::new(FallbackSecrets { return Box::new(voelin_store::FallbackSecrets::new("voelin"));
keyring: voelin_store::KeyringSecrets::new("voelin"),
memory: MemorySecrets::default(),
});
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
return Box::new(MemorySecrets::default()); return Box::new(MemorySecrets::default());
} }
#[cfg(not(target_os = "android"))]
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::Result<Option<String>> {
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
}
}
fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> {
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
}
Ok(())
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
}
/// The lines of a chat as the chat view shows them. /// The lines of a chat as the chat view shows them.
pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>; pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>;
+37 -1
View File
@@ -15,6 +15,7 @@ use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB};
use crate::social::Social; use crate::social::Social;
use crate::studio::StudioState; use crate::studio::StudioState;
use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update}; use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update};
use crate::vm::servers::sequence::Backing;
/// What the transitions ask while they run: the window, the store and the /// What the transitions ask while they run: the window, the store and the
/// settings, borrowed from the app besides its state. /// settings, borrowed from the app besides its state.
@@ -87,6 +88,16 @@ impl App {
pub(crate) fn with_social<R>( pub(crate) fn with_social<R>(
&mut self, &mut self,
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>) -> R, f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>) -> R,
) -> R {
self.with_parts(|state, social, host, _| f(state, social, host))
}
/// Run `f` with the state, the social state, the host and the
/// [`Backing`] of the server sequences (the store, the secrets and the
/// identity, borrowed from the app besides its state).
fn with_parts<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>, &Backing<'_>) -> R,
) -> R { ) -> R {
let host = SlintHost { let host = SlintHost {
demo_ui: self.demo_ui, demo_ui: self.demo_ui,
@@ -99,7 +110,11 @@ impl App {
prefs: &self.prefs, prefs: &self.prefs,
studio: &self.studio, studio: &self.studio,
}; };
f(&mut self.state, &mut self.social, &host) let identity = |named| {
voelin_core::ts::identity::to_blob(&self.store.identity_for(named, &self.identity))
};
let backing = Backing { store: &self.store, secrets: &*self.secrets, identity: &identity };
f(&mut self.state, &mut self.social, &host, &backing)
} }
/// An engine event: what it does to the state is in `voelin-ui-vm` /// An engine event: what it does to the state is in `voelin-ui-vm`
@@ -123,6 +138,22 @@ impl App {
result result
} }
/// Like [`App::transition`], for a sequence that also reads and writes the
/// store and the secrets and picks the identity
/// (`voelin_ui_vm::servers::sequence`).
pub(crate) fn transition_with<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Cx<'_>, &Backing<'_>) -> R,
) -> R {
let (result, update) = self.with_parts(|state, _, host, backing| {
let mut cx = Cx::new(host);
let result = f(state, &mut cx, backing);
(result, cx.update)
});
self.perform(update);
result
}
/// Like [`App::transition`], for a transition that changes the social /// Like [`App::transition`], for a transition that changes the social
/// state too. /// state too.
pub(crate) fn social_transition<R>( pub(crate) fn social_transition<R>(
@@ -148,6 +179,7 @@ impl App {
commands, commands,
persist, persist,
reloaded, reloaded,
discover,
input_level, input_level,
password, password,
notices, notices,
@@ -169,6 +201,10 @@ impl App {
for command in commands { for command in commands {
self.engine.send(command); self.engine.send(command);
} }
// The gateways to look up, on the engine's runtime.
for (id, address) in discover {
self.look_up_gateway(id, address);
}
// The capture and the decoder. // The capture and the decoder.
if let Some(sink) = stream.attach if let Some(sink) = stream.attach
&& let Some(share) = &self.share && let Some(share) = &self.share
+58 -215
View File
@@ -3,273 +3,116 @@
//! the channel tree, and the callbacks' ways into the transitions of //! the channel tree, and the callbacks' ways into the transitions of
//! `voelin_ui_vm::servers::logic`. //! `voelin_ui_vm::servers::logic`.
use std::time::Instant;
use slint::ComponentHandle; use slint::ComponentHandle;
use tracing::{debug, info, warn}; use voelin_core::JoinFailure;
use voelin_core::{Command, JoinFailure, ObserveState}; use voelin_core::stream::PeerConfig;
use voelin_model::ChannelId; use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport}; use voelin_store::Bookmark;
use crate::app::{App, Bridge, later}; use crate::app::{App, Bridge, later};
use crate::bind::convert; use crate::bind::convert;
use crate::vm; use crate::vm;
use crate::vm::bridge::BookmarkForm; use crate::vm::bridge::BookmarkForm;
use crate::vm::servers::logic::{self as logic, GatewayFound, ObservePlan}; use crate::vm::servers::logic;
use crate::vm::servers::sequence;
impl App { impl App {
/// Connect the server on screen with voice, into its default channel
/// ([`sequence::connect_voice`]).
pub(crate) fn connect_voice(&mut self) { pub(crate) fn connect_voice(&mut self) {
let channel = self let peer = self.stream_peer();
.state self.transition_with(|state, cx, backing| {
.current sequence::connect_voice(state, cx, backing, Some(peer))
.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 /// Connect the current server with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given; /// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for. /// whether it was asked for ([`sequence::connect_voice_to`]).
pub(crate) fn connect_voice_to( pub(crate) fn connect_voice_to(
&mut self, &mut self,
channel: Option<String>, channel: Option<String>,
channel_password: Option<String>, channel_password: Option<String>,
token: Option<String>, token: Option<String>,
) -> bool { ) -> bool {
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else { let peer = self.stream_peer();
return false; self.transition_with(|state, cx, backing| {
}; sequence::connect_voice_to(
if self.demo_ui { state,
return false; cx,
} backing,
let mut options = match logic::voice_options(&b, channel, channel_password, token) { channel,
Ok(options) => options, channel_password,
Err(error) => { token,
self.set_status(error); Some(peer),
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 /// What this front end can decode of a stream, to connect with: the
/// from TeamSpeak keeps the nickname used there), else the system user's. /// codecs of the machine, the configured one first.
fn stream_peer(&self) -> PeerConfig {
self.video.peer_config(PeerConfig::default())
}
/// The nickname a new server gets ([`sequence::default_nickname`]).
pub(crate) fn default_nickname(&self) -> String { pub(crate) fn default_nickname(&self) -> String {
self.store sequence::default_nickname(&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 /// Look the gateway of a server up on the engine's runtime
/// run ([`logic::discover_wanted`]): every one the server publishes is /// ([`sequence::find_gateways`]), as `Update::discover` asks; what is found
/// kept, best first, and tried in turn; they take the place of a stored /// comes back through [`later`].
/// one that is no longer published (a gateway that moved, or one typed pub(crate) fn look_up_gateway(&mut self, id: i64, address: String) {
/// 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 { self.engine.runtime().spawn(async move {
let started = Instant::now(); if let Some(found) = sequence::find_gateways(&address).await {
let urls = voelin_core::discover::gateways(&address).await; later(move |app| app.gateway_found(id, &address, found.urls, found.elapsed_ms));
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 /// Gateways were found for the server at `address`
/// are kept unless the server changed meanwhile ([`logic::gateway_found`]), /// ([`sequence::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) { 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)); self.transition_with(|state, cx, backing| {
match found { sequence::gateway_found(state, cx, backing, id, address, urls, elapsed_ms)
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 /// Observe the server invisibly ([`sequence::observe`]).
/// 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) { pub(crate) fn observe(&mut self, id: i64) {
let Some(b) = self.bookmark(id).cloned() else { return }; self.transition_with(|state, cx, backing| sequence::observe(state, cx, backing, id));
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. /// Show a server, and observe it ([`sequence::select_server`]).
pub(crate) fn select_server(&mut self, id: i64) { pub(crate) fn select_server(&mut self, id: i64) {
self.transition(|state, cx| logic::select_server(state, cx, id)); self.transition_with(|state, cx, backing| sequence::select_server(state, cx, backing, id));
self.observe(id);
} }
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm { pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else { sequence::bookmark_form(&self.state, &self.store, &*self.secrets, id)
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 /// Save the server dialog's server, and show it; its id, none when it
/// could not be saved (the toast says why). /// could not be saved (the toast says why) ([`sequence::save_bookmark`]).
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> { pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
let old = self.bookmark(form.id as i64).cloned(); self.transition_with(|state, cx, backing| sequence::save_bookmark(state, cx, backing, form))
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 /// 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 /// voice, into the channel of the link that filled the form if one did
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is /// ([`sequence::save_and_connect`]). Whether it was saved.
/// 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 { pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
let saved = self.save_bookmark(form); let peer = self.stream_peer();
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else { self.transition_with(|state, cx, backing| {
return false; sequence::save_and_connect(state, cx, backing, form, Some(peer))
}; })
self.connect_voice_to(to.channel, to.channel_password, to.token);
true
} }
pub(crate) fn delete_bookmark(&mut self, id: i64) { pub(crate) fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 }); self.transition_with(|state, cx, backing| {
if let Some(b) = self.bookmark(id).cloned() { sequence::delete_bookmark(state, cx, backing, id)
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 { pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
+49 -5
View File
@@ -38,7 +38,10 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit
viewer's rows and texts viewer's rows and texts
servers/logic.rs which server is shown and how it is observed, joining a channel; 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 the rail, the server card and the channel tree as plain data
settings.rs the UI's settings keys, the audio form servers/sequence.rs what both front ends do for a server over the store, the secrets
and the engine (connect, observe, the gateway lookup, save and
remove a bookmark), as transitions over a `Backing`
settings.rs the UI's settings keys, the audio form, `open_settings`
settings_pages/logic.rs, studio/logic.rs settings_pages/logic.rs, studio/logic.rs
the decisions of the settings pages and of the Stream Studio the decisions of the settings pages and of the Stream Studio
dev/logic.rs the sample data of `VOELIN_DEMO_UI` as plain values and events dev/logic.rs the sample data of `VOELIN_DEMO_UI` as plain values and events
@@ -87,8 +90,9 @@ crates/voelin-ui/ the Slint front end
the Slint side of each area (previews.rs: pictures in chat; the Slint side of each area (previews.rs: pictures in chat;
popout.rs: the stream's own window) popout.rs: the stream's own window)
chat/ mod.rs, bind.rs: the chat view's Bridge writes and models chat/ mod.rs, bind.rs: the chat view's Bridge writes and models
servers/ mod.rs, bind.rs: connecting and observing (store, secrets, engine), servers/ mod.rs, bind.rs: connecting and observing (the callbacks of
the rail, the server card and the tree on the Bridge `servers/sequence.rs`, the gateway lookup's thread hop), the rail,
the server card and the tree on the Bridge
social/ mod.rs (the models), bind.rs: contacts, the bell and the search on social/ mod.rs (the models), bind.rs: contacts, the bell and the search on
the Bridge, the desktop toasts, the navigation after a move the Bridge, the desktop toasts, the navigation after a move
settings_page/ mod.rs, bind.rs: the audio devices, the hotkey, the codec download, settings_page/ mod.rs, bind.rs: the audio devices, the hotkey, the codec download,
@@ -981,6 +985,7 @@ crates/voelin-gpui/
app.rs AppState, the root Entity: the voelin-ui-vm state and Social, the app.rs AppState, the root Entity: the voelin-ui-vm state and Social, the
backend, the three loops (events in batches, a quiet tick, Later) backend, the three loops (events in batches, a quiet tick, Later)
and the callbacks of the Slint `bind/servers.rs` that the shell has and the callbacks of the Slint `bind/servers.rs` that the shell has
(over `voelin_ui_vm::servers::sequence`, which Slint calls too)
view.rs MainView, the window's root view: the shell or the swatch, the view.rs MainView, the window's root view: the shell or the swatch, the
handlers of the actions, the server form, the title, the window's place handlers of the actions, the server form, the title, the window's place
shell/ the desktop shell (below): rail.rs, sidebar.rs, topbar.rs, shell/ the desktop shell (below): rail.rs, sidebar.rs, topbar.rs,
@@ -1193,8 +1198,10 @@ minimum size is 640 by 480.
The eleven callbacks of `bind/servers.rs` that the shell has are GPUI actions The eleven callbacks of `bind/servers.rs` that the shell has are GPUI actions
(`shell/actions.rs`); a click dispatches one with `Window::dispatch_action`, (`shell/actions.rs`); a click dispatches one with `Window::dispatch_action`,
`MainView` handles it, and the handler asks the root state for what the Slint `MainView` handles it, and the handler asks the root state for what the Slint
callback did, through `voelin-ui-vm`'s `servers::logic` and the engine's callback did, through `voelin-ui-vm`'s `servers::logic` and
commands: `servers::sequence`, the one sequence over the store, the secrets and the
engine's commands that the Slint front end runs too ([Shared with the Slint
front end](#shared-with-the-slint-front-end)):
| Slint callback | Action | What it does | | Slint callback | Action | What it does |
|---|---|---| |---|---|---|
@@ -1216,6 +1223,43 @@ voice page), and `copied`, which the Slint toast of a copy needs and `Invite`
does for itself. `AddServer`, `CancelServerForm`, `OpenSearch` and does for itself. `AddServer`, `CancelServerForm`, `OpenSearch` and
`OpenSettings` are the shell's own. `OpenSettings` are the shell's own.
#### Shared with the Slint front end
What the Slint crate's `servers/bind.rs` and `app.rs` did and this front end
repeated lives in one place and both call it (the Slint methods are thin
wrappers, so its call sites are unchanged):
- **`voelin_ui_vm::servers::sequence`**: `connect_voice_to`, `connect_voice`,
`observe`, `discover_gateway`, `gateway_found`, `select_server`,
`save_bookmark`, `save_and_connect`, `delete_bookmark`, `bookmark_form` and
`default_nickname`. Each is a transition over the state, the `Cx` and a
`Backing` (the store, the secrets and the identity a connection is made
with), so the engine's commands, the status line, what is to be kept and the
gateways to look up (`Update::discover`) go out through the update, and
each front end's `perform` and its tests handle them as they handle every
other transition's (the GPUI tests see the commands as `take_sent`, and the
sample servers' are dropped there). `transition_with` of each front end hands
the `Backing` over: the GPUI root state's and the Slint `App`'s own fields.
`stream_peer` is the one input a front end gives (the Slint one's
`video.peer_config`; this one passes none).
- **`voelin_ui_vm::settings::open_settings`** and `register_keys`: the settings
service on `client.db` with the UI's keys, `config.toml`, `VOELIN_SETTING_*`
and `--set`; each front end registers its own key (`ui.window` here, the
Stream Studio's `studio.ui` there) through the function it passes.
- **`voelin_store::FallbackSecrets`** (the keyring first, memory where it
refuses) and **`Store::identity_for`** (the identity a bookmark names, else
the default, else the one made at start).
Left as copies, because they need the toolkit, the runtime or a front end's own
state: the thread hop of the gateway lookup (`look_up_gateway`: each front end
runs `sequence::find_gateways` on the engine's runtime and comes back through
its own `Later`/`later`), `perform` (what an `Update` does to a window), the
status line's toast, the invite's clipboard write, `HostedEngine` (`engine.rs`),
the guards of the GPUI shell's save (`save_refused`: the sample servers are not
kept, and a server needs an address, which the Slint dialog checks in
`dialogs.slint` before it calls), the store at start (`Backend::open` against `run()`: the identity import, the crash
reports and `--set` of the Slint one) and the form widgets themselves.
**The store at start** (`backend.rs`) is `run()` of the Slint front end through **The store at start** (`backend.rs`) is `run()` of the Slint front end through
`voelin-ui-vm`: the client's database at `<data dir>/client.db` (bookmarks, `voelin-ui-vm`: the client's database at `<data dir>/client.db` (bookmarks,
identities, chat read marks), the settings service on it with the UI's keys identities, chat read marks), the settings service on it with the UI's keys